1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace App\Movies\Service; |
5
|
|
|
|
6
|
|
|
use App\Movies\Exception\TmdbMovieNotFoundException; |
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
|
11
|
|
|
class TmdbSearchService |
12
|
|
|
{ |
13
|
|
|
private $apiKey; |
14
|
|
|
private $client; |
15
|
|
|
private $logger; |
16
|
|
|
private const ApiUrl = 'https://api.themoviedb.org/3'; |
17
|
|
|
|
18
|
7 |
|
public function __construct(LoggerInterface $logger) |
19
|
|
|
{ |
20
|
7 |
|
$this->apiKey = \getenv('MOVIE_DB_API_KEY'); |
21
|
7 |
|
$this->client = new Client(); |
22
|
7 |
|
$this->logger = $logger; |
23
|
7 |
|
} |
24
|
|
|
|
25
|
1 |
|
public function findMoviesByQuery(string $query, string $locale = 'en'): array |
26
|
|
|
{ |
27
|
1 |
|
$movies = $this->request('/search/movie', 'GET', [ |
28
|
|
|
'query' => [ |
29
|
1 |
|
'api_key' => $this->apiKey, |
30
|
1 |
|
'language' => $locale, |
31
|
1 |
|
'query' => $query |
32
|
|
|
], |
33
|
|
|
]); |
34
|
|
|
|
35
|
1 |
|
return $movies; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param int $tmdb_id |
40
|
|
|
* @param string $locale |
41
|
|
|
* @return array |
42
|
|
|
* @throws TmdbMovieNotFoundException |
43
|
|
|
*/ |
44
|
1 |
|
public function findMovieById(int $tmdb_id, string $locale = 'en'): array |
45
|
|
|
{ |
46
|
1 |
|
$movie = $this->request("/movie/{$tmdb_id}", 'GET', [ |
47
|
|
|
'query' => [ |
48
|
1 |
|
'api_key' => $this->apiKey, |
49
|
1 |
|
'language' => $locale, |
50
|
|
|
], |
51
|
|
|
]); |
52
|
|
|
|
53
|
1 |
|
if (isset($movie['status_code']) && $movie['status_code'] == 34) { |
54
|
|
|
throw new TmdbMovieNotFoundException(); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
return $movie; |
58
|
|
|
} |
59
|
|
|
|
60
|
2 |
|
private function request(string $url, string $method = 'GET', array $params = []): array |
61
|
|
|
{ |
62
|
2 |
|
$url = self::ApiUrl . $url; |
63
|
|
|
|
64
|
|
|
try { |
65
|
2 |
|
$response = $this->client->request($method, $url, $params); |
66
|
2 |
|
$response = json_decode($response->getBody()->getContents(), true); |
67
|
2 |
|
getenv('APP_ENV') === 'dev' && $this->logger->debug('Guzzle request:', [ |
68
|
|
|
'url' => $url, |
69
|
|
|
'method' => $method, |
70
|
|
|
'params' => $params, |
71
|
2 |
|
'response' => $response, |
72
|
|
|
]); |
73
|
|
|
} catch (GuzzleException $exception) { |
74
|
|
|
$this->logger->error('Guzzle request failed.', [ |
75
|
|
|
'url' => $url, |
76
|
|
|
'method' => $method, |
77
|
|
|
'params' => $params, |
78
|
|
|
'exceptionMessage' => $exception->getMessage(), |
79
|
|
|
'exceptionCode' => $exception->getCode(), |
80
|
|
|
]); |
81
|
|
|
|
82
|
|
|
$response = []; |
83
|
|
|
|
84
|
|
|
if ($exception->getCode() == 404) { |
85
|
|
|
$response = [ |
86
|
|
|
'status_code' => 34 |
87
|
|
|
]; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|
91
|
2 |
|
return $response; |
92
|
|
|
} |
93
|
|
|
} |