Completed
Push — master ( 66f2ad...196fcb )
by Valentyn
03:19
created

TmdbSearchService::findSimilarMoviesById()   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
class TmdbSearchService
14
{
15
    private $apiKey;
16
    private $client;
17
    private $logger;
18
    private const ApiUrl = 'https://api.themoviedb.org/3';
19
20 9
    public function __construct(LoggerInterface $logger, ClientInterface $client)
21
    {
22 9
        $this->apiKey = \getenv('MOVIE_DB_API_KEY'); // is it ok to use \getenv() here?
23 9
        $this->client = $client;
24 9
        $this->logger = $logger;
25 9
    }
26
27
    /**
28
     * @param string $query
29
     * @param string $locale
30
     * @param array  $data
31
     *
32
     * @throws TmdbMovieNotFoundException
33
     * @throws TmdbRequestLimitException
34
     *
35
     * @return array
36
     */
37 1
    public function findMoviesByQuery(string $query, string $locale = 'en', $data = []): array
38
    {
39 1
        $data = array_merge([
40 1
            'api_key' => $this->apiKey,
41 1
            'language' => $locale,
42 1
            'query' => $query,
43 1
        ], $data);
44
45 1
        $movies = $this->request('/search/movie', 'GET', [
46 1
            'query' => $data,
47
        ]);
48
49 1
        return $movies;
50
    }
51
52
    /**
53
     * @param int    $tmdb_id
54
     * @param string $locale
55
     *
56
     * @throws TmdbMovieNotFoundException
57
     * @throws TmdbRequestLimitException
58
     *
59
     * @return array
60
     */
61 1
    public function findMovieById(int $tmdb_id, string $locale = 'en'): array
62
    {
63 1
        $movie = $this->request("/movie/{$tmdb_id}", 'GET', [
64
            'query' => [
65 1
                'api_key' => $this->apiKey,
66 1
                'language' => $locale,
67
            ],
68
        ]);
69
70 1
        return $movie;
71
    }
72
73
    /**
74
     * @param int $tmdb_id
75
     *
76
     * @throws TmdbMovieNotFoundException
77
     * @throws TmdbRequestLimitException
78
     *
79
     * @return array
80
     */
81
    public function findMovieTranslationsById(int $tmdb_id): array
82
    {
83
        $movie = $this->request("/movie/{$tmdb_id}/translations", 'GET', [
84
            'query' => [
85
                'api_key' => $this->apiKey,
86
            ],
87
        ]);
88
89
        return $movie;
90
    }
91
92
    /**
93
     * @param int $tmdb_id
94
     * @param int $page
95
     * @return array
96
     * @throws TmdbMovieNotFoundException
97
     * @throws TmdbRequestLimitException
98
     */
99
    public function findSimilarMoviesById(int $tmdb_id, int $page = 1): array
100
    {
101
        $movie = $this->request("/movie/{$tmdb_id}/similar", 'GET', [
102
            'query' => [
103
                'api_key' => $this->apiKey,
104
                'page' => $page,
105
            ],
106
        ]);
107
108
        return $movie;
109
    }
110
111
    /**
112
     * @param string $url
113
     * @param string $method
114
     * @param array $params
115
     * @return array
116
     * @throws TmdbMovieNotFoundException
117
     * @throws TmdbRequestLimitException
118
     */
119 2
    private function request(string $url, string $method = 'GET', array $params = []): array
120
    {
121 2
        $url = self::ApiUrl.$url;
122
123
        try {
124 2
            $response = $this->client->request($method, $url, $params);
125 2
            $response = json_decode($response->getBody()->getContents(), true);
126 2
            getenv('APP_ENV') === 'dev' && $this->logger->debug('Guzzle request:', [
127
                'url' => $url,
128
                'method' => $method,
129
                'params' => $params,
130 2
                'response' => $response,
131
            ]);
132
        } catch (GuzzleException $exception) {
133
            $this->logger->error('Guzzle request failed.', [
134
                'url' => $url,
135
                'method' => $method,
136
                'params' => $params,
137
                'exceptionMessage' => $exception->getMessage(),
138
                'exceptionCode' => $exception->getCode(),
139
            ]);
140
141
            $response = [];
142
143
            if ($exception->getCode() === 404) {
144
                throw new TmdbMovieNotFoundException();
145
            }
146
147
            if ($exception->getCode() === 429) {
148
                throw new TmdbRequestLimitException();
149
            }
150
        }
151
152 2
        return $response;
153
    }
154
}
155