Completed
Push — master ( 59ed7d...9fb967 )
by Valentyn
02:51
created

TmdbSearchService::findActorById()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 5
cp 0
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Movies\Service;
6
7
use App\Movies\Exception\TmdbMovieNotFoundException;
8
use App\Movies\Exception\TmdbRequestLimitException;
9
use GuzzleHttp\ClientInterface;
10
use GuzzleHttp\Exception\GuzzleException;
11
use Psr\Log\LoggerInterface;
12
13
// todo use append_to_response + cache to decrease amount of requests to external api
14
class TmdbSearchService
15
{
16
    private $apiKey;
17
    private $client;
18
    private $logger;
19
    private const ApiUrl = 'https://api.themoviedb.org/3';
20
21 9
    public function __construct(LoggerInterface $logger, ClientInterface $client)
22
    {
23 9
        $this->apiKey = \getenv('MOVIE_DB_API_KEY'); // is it ok to use \getenv() here?
24 9
        $this->client = $client;
25 9
        $this->logger = $logger;
26 9
    }
27
28
    /**
29
     * @param string $query
30
     * @param string $locale
31
     * @param array  $data
32
     *
33
     * @throws TmdbMovieNotFoundException
34
     * @throws TmdbRequestLimitException
35
     *
36
     * @return array
37
     */
38 1
    public function findMoviesByQuery(string $query, string $locale = 'en', $data = []): array
39
    {
40 1
        $data = array_merge([
41 1
            'api_key' => $this->apiKey,
42 1
            'language' => $locale,
43 1
            'query' => $query,
44 1
        ], $data);
45
46 1
        $movies = $this->request('/search/movie', 'GET', [
47 1
            'query' => $data,
48
        ]);
49
50 1
        return $movies;
51
    }
52
53
    /**
54
     * @param int    $tmdb_id
55
     * @param string $locale
56
     *
57
     * @throws TmdbMovieNotFoundException
58
     * @throws TmdbRequestLimitException
59
     *
60
     * @return array
61
     */
62 1
    public function findMovieById(int $tmdb_id, string $locale = 'en'): array
63
    {
64 1
        $movie = $this->request("/movie/{$tmdb_id}", 'GET', [
65
            'query' => [
66 1
                'api_key' => $this->apiKey,
67 1
                'language' => $locale,
68
            ],
69
        ]);
70
71 1
        return $movie;
72
    }
73
74
    public function findActorsByMovieId(int $personId, string $locale = 'en'): array
75
    {
76
        $actors = $this->request("/movie/{$personId}/credits", 'GET', [
77
            'query' => [
78
                'api_key' => $this->apiKey,
79
                'language' => $locale,
80
            ],
81
        ]);
82
83
        return $actors;
84
    }
85
86
    public function findActorById(int $personId, string $locale = 'en'): array
87
    {
88
        $actors = $this->request("/person/{$personId}", 'GET', [
89
            'query' => [
90
                'api_key' => $this->apiKey,
91
                'language' => $locale,
92
            ],
93
        ]);
94
95
        return $actors;
96
    }
97
98
    public function findActorTranslationsById(int $personId, string $locale = 'en'): array
99
    {
100
        $actors = $this->request("/person/{$personId}/translations", 'GET', [
101
            'query' => [
102
                'api_key' => $this->apiKey,
103
                'language' => $locale,
104
            ],
105
        ]);
106
107
        return $actors;
108
    }
109
110
    /**
111
     * @param int $tmdb_id
112
     *
113
     * @throws TmdbMovieNotFoundException
114
     * @throws TmdbRequestLimitException
115
     *
116
     * @return array
117
     */
118
    public function findMovieTranslationsById(int $tmdb_id): array
119
    {
120
        $movie = $this->request("/movie/{$tmdb_id}/translations", 'GET', [
121
            'query' => [
122
                'api_key' => $this->apiKey,
123
            ],
124
        ]);
125
126
        return $movie;
127
    }
128
129
    /**
130
     * @param int $tmdb_id
131
     * @param int $page
132
     *
133
     * @throws TmdbMovieNotFoundException
134
     * @throws TmdbRequestLimitException
135
     *
136
     * @return array
137
     */
138
    public function findSimilarMoviesById(int $tmdb_id, int $page = 1): array
139
    {
140
        $movie = $this->request("/movie/{$tmdb_id}/similar", 'GET', [
141
            'query' => [
142
                'api_key' => $this->apiKey,
143
                'page' => $page,
144
            ],
145
        ]);
146
147
        return $movie;
148
    }
149
150
    /**
151
     * @param string $url
152
     * @param string $method
153
     * @param array  $params
154
     *
155
     * @throws TmdbMovieNotFoundException
156
     * @throws TmdbRequestLimitException
157
     *
158
     * @return array
159
     */
160 2
    private function request(string $url, string $method = 'GET', array $params = []): array
161
    {
162 2
        $url = self::ApiUrl.$url;
163
164
        try {
165 2
            $response = $this->client->request($method, $url, $params);
166 2
            $response = json_decode($response->getBody()->getContents(), true);
167 2
            getenv('APP_ENV') === 'dev' && $this->logger->debug('Guzzle request:', [
168
                'url' => $url,
169
                'method' => $method,
170
                'params' => $params,
171 2
                'response' => $response,
172
            ]);
173
        } catch (GuzzleException $exception) {
174
            $this->logger->error('Guzzle request failed.', [
175
                'url' => $url,
176
                'method' => $method,
177
                'params' => $params,
178
                'exceptionMessage' => $exception->getMessage(),
179
                'exceptionCode' => $exception->getCode(),
180
            ]);
181
182
            $response = [];
183
184
            if ($exception->getCode() === 404) {
185
                throw new TmdbMovieNotFoundException();
186
            }
187
188
            if ($exception->getCode() === 429) {
189
                throw new TmdbRequestLimitException();
190
            }
191
        }
192
193 2
        return $response;
194
    }
195
}
196