49 lines
1.6 KiB
PHP
49 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Gateway;
|
|
|
|
use App\Context\TMDB\MovieSearchContext;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
use Symfony\Component\Serializer\SerializerInterface;
|
|
use Symfony\Contracts\Cache\CacheInterface;
|
|
use Symfony\Contracts\Cache\ItemInterface;
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
|
use function Symfony\Component\String\u;
|
|
|
|
class TMDBGateway
|
|
{
|
|
private const string SEARCH_URI = '/search/movie';
|
|
|
|
public function __construct(
|
|
private readonly HttpClientInterface $client,
|
|
private readonly SerializerInterface $serializer,
|
|
private readonly CacheInterface $cache,
|
|
#[Autowire('%env(TMDB_API_TOKEN)%')]
|
|
private readonly string $apiToken,
|
|
#[Autowire('%env(TMDB_HOST)%')]
|
|
private readonly string $host,
|
|
) {
|
|
}
|
|
|
|
public function searchMovie(string $movieName): ?MovieSearchContext
|
|
{
|
|
$cacheKey = 'tmdb_movie.'.u($movieName)->snake();
|
|
|
|
return $this->cache->get($cacheKey, function (ItemInterface $item) use ($movieName) {
|
|
$url = $this->host.self::SEARCH_URI.'?'.http_build_query(['query' => $movieName]);
|
|
try {
|
|
$response = $this->client->request('GET', $url, ['headers' => $this->getHeaders()]);
|
|
$result = $response->getContent();
|
|
return $this->serializer->deserialize($result, MovieSearchContext::class, 'json');
|
|
} catch (\Throwable) {
|
|
return null;
|
|
}
|
|
});
|
|
}
|
|
|
|
private function getHeaders(): array
|
|
{
|
|
return ['Authorization' => 'Bearer '.$this->apiToken, 'accept' => 'application/json'];
|
|
}
|
|
}
|