Completed
Push — master ( d15cf4...5163a0 )
by Valentyn
06:05
created

TmdbSearchService   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 54
ccs 0
cts 29
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A findMoviesByQuery() 0 12 1
B request() 0 26 3
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
}