1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace App\Movies\Service; |
5
|
|
|
|
6
|
|
|
use App\Movies\Repository\MovieRepository; |
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use Symfony\Component\HttpFoundation\RequestStack; |
11
|
|
|
|
12
|
|
|
class TmdbSearchService |
13
|
|
|
{ |
14
|
|
|
private $apiKey; |
15
|
|
|
private $client; |
16
|
|
|
private $logger; |
17
|
|
|
private const ApiUrl = 'https://api.themoviedb.org/3'; |
18
|
|
|
|
19
|
|
|
public function __construct(LoggerInterface $logger) |
20
|
|
|
{ |
21
|
|
|
$this->apiKey = \getenv('MOVIE_DB_API_KEY'); |
22
|
|
|
$this->client = new Client(); |
23
|
|
|
$this->logger = $logger; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function findMoviesByQuery(string $query, string $locale = 'en-US'): array |
27
|
|
|
{ |
28
|
|
|
$movies = $this->request('/search/movie', 'GET', [ |
29
|
|
|
'query' => [ |
30
|
|
|
'api_key' => $this->apiKey, |
31
|
|
|
'locale' => $locale, |
32
|
|
|
'query' => $query |
33
|
|
|
], |
34
|
|
|
]); |
35
|
|
|
|
36
|
|
|
return $movies; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
private function request(string $url, string $method = 'GET', array $params = []): array |
40
|
|
|
{ |
41
|
|
|
$url = self::ApiUrl . $url; |
42
|
|
|
|
43
|
|
|
try { |
44
|
|
|
$response = $this->client->request($method, $url, $params); |
45
|
|
|
$response = json_decode($response->getBody()->getContents(), true); |
46
|
|
|
getenv('APP_ENV') === 'dev' && $this->logger->debug('Guzzle request:', [ |
47
|
|
|
'url' => $url, |
48
|
|
|
'method' => $method, |
49
|
|
|
'params' => $params, |
50
|
|
|
'response' => $response, |
51
|
|
|
]); |
52
|
|
|
} catch (GuzzleException $exception) { |
53
|
|
|
$this->logger->error('Guzzle request failed.', [ |
54
|
|
|
'url' => $url, |
55
|
|
|
'method' => $method, |
56
|
|
|
'params' => $params, |
57
|
|
|
'exceptionMessage' => $exception->getMessage(), |
58
|
|
|
'exceptionCode' => $exception->getCode(), |
59
|
|
|
]); |
60
|
|
|
$response = []; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $response; |
64
|
|
|
} |
65
|
|
|
} |