Skip to content

Instantly share code, notes, and snippets.

@MarioBlazek
Created April 9, 2020 20:00
Show Gist options
  • Save MarioBlazek/c819cfcf5cfc9dcf4223f5c8aeee2ff3 to your computer and use it in GitHub Desktop.
Save MarioBlazek/c819cfcf5cfc9dcf4223f5c8aeee2ff3 to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Integration\TheCatApi;
use AppBundle\Integration\TheCatApi\Value\TheCatApiValue;
use eZ\Publish\Core\MVC\ConfigResolverInterface;
use Http\Client\HttpClient;
use Http\Message\MessageFactory;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
final class Service
{
/**
* @var \eZ\Publish\Core\MVC\ConfigResolverInterface
*/
private $configResolver;
/**
* @var \Http\Client\HttpClient
*/
private $httpClient;
/**
* @var \Http\Message\MessageFactory
*/
private $messageFactory;
public function __construct(
ConfigResolverInterface $configResolver,
HttpClient $httpClient,
MessageFactory $messageFactory
) {
$this->configResolver = $configResolver;
$this->httpClient = $httpClient;
$this->messageFactory = $messageFactory;
}
public function getCategories(): array
{
$request = $this->messageFactory
->createRequest(
Request::METHOD_GET,
$this->configResolver->getParameter('cats_api.url_categories', 'app'),
[
'x-api-key' => $this->configResolver->getParameter('cats_api.token', 'app'),
]
);
return $this->sendRequest($request);
}
public function getBreeds(): array
{
$request = $this->messageFactory
->createRequest(
Request::METHOD_GET,
$this->configResolver->getParameter('cats_api.url_breeds', 'app'),
[
'x-api-key' => $this->configResolver->getParameter('cats_api.token', 'app'),
]
);
return $this->sendRequest($request);
}
private function sendRequest(RequestInterface $request): array
{
try {
$response = $this->httpClient->sendRequest($request);
} catch (\Exception $exception) {
return [];
}
if ($response->getStatusCode() !== Response::HTTP_OK) {
return [];
}
$data = json_decode(
(string)$response->getBody(),
true
);
$objects = [];
foreach ($data as $datum) {
$objects[] = new TheCatApiValue($datum['id'], $datum['name']);
}
return $objects;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment