ltbxd-actorle/src/Gateway/TMDBGateway.php

49 lines
1.6 KiB
PHP
Raw Normal View History

2026-01-13 12:58:53 +00:00
<?php
namespace App\Gateway;
2026-01-13 20:26:00 +00:00
use App\Context\TMDB\MovieSearchContext;
2026-01-13 23:54:49 +00:00
use App\Model\TMDB\TMDBMovie;
2026-01-13 12:58:53 +00:00
use Symfony\Component\DependencyInjection\Attribute\Autowire;
2026-01-13 20:26:00 +00:00
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
2026-01-13 12:58:53 +00:00
use Symfony\Contracts\HttpClient\HttpClientInterface;
2026-01-13 20:26:00 +00:00
use function Symfony\Component\String\u;
2026-01-13 12:58:53 +00:00
class TMDBGateway
{
2026-01-13 20:26:00 +00:00
private const string SEARCH_URI = '/search/movie';
2026-01-13 12:58:53 +00:00
public function __construct(
private readonly HttpClientInterface $client,
2026-01-13 20:26:00 +00:00
private readonly SerializerInterface $serializer,
2026-01-13 12:58:53 +00:00
#[Autowire('%env(TMDB_API_TOKEN)%')]
private readonly string $apiToken,
2026-01-15 12:16:09 +00:00
#[Autowire('%tmdb_host%')]
2026-01-13 20:26:00 +00:00
private readonly string $host,
2026-01-13 12:58:53 +00:00
) {
}
2026-01-13 23:54:49 +00:00
public function searchMovie(string $movieName): ?TMDBMovie
2026-01-13 12:58:53 +00:00
{
2026-01-13 23:54:49 +00:00
$url = $this->host.self::SEARCH_URI.'?'.http_build_query(['query' => $movieName]);
try {
$response = $this->client->request('GET', $url, ['headers' => $this->getHeaders()]);
$result = $response->getContent();
$searchContext = $this->serializer->deserialize($result, MovieSearchContext::class, 'json');
if (empty($searchResult = $searchContext->getResults())) {
2026-01-13 20:26:00 +00:00
return null;
}
2026-01-13 23:54:49 +00:00
return reset($searchResult);
} catch (\Throwable) {
return null;
}
2026-01-13 12:58:53 +00:00
}
private function getHeaders(): array
{
return ['Authorization' => 'Bearer '.$this->apiToken, 'accept' => 'application/json'];
}
}