Files
ltbxd-actorle/src/Gateway/TMDBGateway.php
2026-01-15 14:01:45 +01:00

79 lines
2.5 KiB
PHP

<?php
namespace App\Gateway;
use App\Context\TMDB\MovieCreditsContext;
use App\Context\TMDB\MovieSearchContext;
use App\Exception\GatewayException;
use App\Model\TMDB\TMDBMovie;
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 Symfony\Contracts\HttpClient\ResponseInterface;
use function Symfony\Component\String\u;
class TMDBGateway
{
private const string SEARCH_URI = '/search/movie';
private const string MOVIE_CREDITS_URI = '/movie/{id}/credits';
public function __construct(
private readonly HttpClientInterface $client,
private readonly SerializerInterface $serializer,
#[Autowire('%env(TMDB_API_TOKEN)%')]
private readonly string $apiToken,
#[Autowire('%tmdb_host%')]
private readonly string $host,
) {
}
/**
* @throws GatewayException
*/
public function searchMovie(string $movieName): ?TMDBMovie
{
$url = $this->host.self::SEARCH_URI.'?'.http_build_query(['query' => $movieName]);
$searchContext = $this->fetchSerialized('GET', $url, MovieSearchContext::class);
if (empty($searchResult = $searchContext->getResults())) {
return null;
}
return reset($searchResult);
}
/**
* @throws GatewayException
*/
public function getMovieCredits(int $movieId): ?MovieCreditsContext
{
$url = str_replace('{id}', $movieId, $this->host.self::MOVIE_CREDITS_URI);
return $this->fetchSerialized('GET', $url, MovieCreditsContext::class);
}
/**
* @throws GatewayException
*/
private function fetch(string $method, string $url): ResponseInterface
{
try {
return $this->client->request($method, $url, ['headers' => ['Authorization' => 'Bearer '.$this->apiToken, 'accept' => 'application/json']]);
} catch (\Throwable $e) {
throw new GatewayException(self::class, $e->getMessage(), $e);
}
}
/**
* @throws GatewayException
*/
private function fetchSerialized(string $method, string $url, string $class, string $type = 'json'): mixed
{
$result = $this->fetch($method, $url);
try {
return $this->serializer->deserialize($result->getContent(), $class, $type);
} catch (\Throwable $e) {
throw new GatewayException(self::class, $e->getMessage(), $e);
}
}
}