Completed
Push — master ( 5163a0...712d21 )
by Valentyn
06:59
created

TmdbSearchService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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