Test Failed
Pull Request — master (#17)
by
unknown
03:56
created

Tmdb::sendRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 4
crap 2
1
<?php
2
3
namespace vfalies\tmdb;
4
5
use vfalies\tmdb\Interfaces\TmdbInterface;
6
use vfalies\tmdb\Interfaces\HttpRequestInterface;
7
use Psr\Log\LoggerInterface;
8
use vfalies\tmdb\lib\Guzzle\Client as HttpClient;
9
use vfalies\tmdb\Exceptions\IncorrectParamException;
10
use vfalies\tmdb\Exceptions\ServerErrorException;
11
12
/**
13
 * Tmdb wrapper core class
14
 */
15
class Tmdb implements TmdbInterface
16
{
17
18
    // Private variables
19
    private $api_key         = null; // API Key
20
    private $language        = 'fr-FR'; // Default language for API response'; // Base URL of the API
21
    private $include_adult   = false; // Include adult content in search result
22
    private $page            = 1; // API Page result
23
    // Protected variables
24
    protected $configuration = null; // API Configuration
25
    protected $genres        = null; // API Genres
26
    // Public variables
27
    public $base_api_url     = 'https://api.themoviedb.org/3/'; // Base URL of the API
28
29 139
    /**
30
     *
31 139
     * @var LoggerInterface
32 139
     */
33
    public $logger           = null;
34
35
    /**
36
     * Constructor
37
     * @param string $api_key TMDB API Key
38
     * @param LoggerInterface $logger Logger used in the class
39
     */
40
    public function __construct(string $api_key, LoggerInterface $logger)
41
    {
42 5
        $this->api_key = $api_key;
43
        $this->logger  = $logger;
44 5
    }
45
46 5
    /**
47 5
     * Send request to TMDB API
48 5
     * @param HttpRequestInterface $http_request
49 5
     * @param string $action API action to request
50 5
     * @param string $query Query of the request (optional)
51 5
     * @param array $options Array of options of the request (optional)
52 5
     * @return \stdClass
53
     */
54 5
    public function sendRequest(HttpRequestInterface $http_request, string $action, string $query = null, array $options = array()): \stdClass
55
    {
56 4
        $this->logger->debug('Start sending HTTP request');
57
        $url = $this->buildHTTPUrl($action, $query, $options);
58 4
        $res = $http_request->getResponse($url);
59
60 2
        $response = json_decode($res->getBody());
61
        if (empty($response)) {
62 1
            $this->logger->error('Request Body can not be decode', array('action' => $action, 'query' => $query, 'options' => $options));
63 1
            throw new ServerErrorException();
64 1
        }
65 1
        return $response;
66
    }
67 1
68
    /**
69 1
     * Build URL for HTTP Call
70
     * @param string $action API action to request
71
     * @param string $query Query of the request (optional)
72
     * @param array $options Array of options of the request (optional)
73 2
     * @return string
74
     */
75 2
    private function buildHTTPUrl($action, $query, $options)
76 2
    {
77
        // Url construction
78 1
        $url = $this->base_api_url . $action;
79
80 1
        // Parameters
81
        $params            = [];
82
        $params['api_key'] = $this->api_key;
83
        if (!is_null($query)) {
84
            $params['query'] = $query;
85
        }
86
87
        $params = array_merge($params, $options);
88
89
        // URL with paramters construction
90
        $url = $url . '?' . http_build_query($params);
91
92
        return $url;
93
    }
94
95
    /**
96
     * Get API Configuration
97
     * @return \stdClass
98
     * @throws TmdbException
99
     */
100
    public function getConfiguration(): \stdClass
101
    {
102
        try {
103
            $this->logger->debug('Start getting configuration');
104
            if (is_null($this->configuration)) {
105
                $this->logger->debug('No configuration found, sending HTTP request to get it');
106
                $this->configuration = $this->sendRequest(new HttpClient(new \GuzzleHttp\Client()), 'configuration');
107
            }
108
            return $this->configuration;
109
        } catch (TmdbException $ex) {
110
            throw $ex;
111
        }
112
    }
113
114
    /**
115 8
     * Check options rules before send request
116
     * @param array $options Array of options to validate
117
     * @return array
118
     * @throws IncorrectParamException
119 8
     */
120
    public function checkOptions(array $options): array
121 8
    {
122
        $params                  = [];
123 7
        // Set default options
124 1
        $params['language']      = $this->language;
125
        $params['include_adult'] = $this->include_adult;
126 1
        $params['page']          = $this->page;
127
        // Check options
128
        foreach ($options as $key => $value) {
129
            switch ($key) {
130
                case 'year':
131
                    $params[$key] = $this->checkYear($value);
132
                    break;
133
                case 'language':
134
                    $params[$key] = $this->checkLanguage($value);
135
                    break;
136 131
                case 'include_adult':
137
                    $params[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
138 131
                    break;
139
                case 'page':
140 131
                    $params[$key] = (int) $value;
141 131
                    break;
142 131
                default:
143
                    $this->logger->error('Unknown param options', array('options', $options));
144 131
                    throw new IncorrectParamException;
145
            }
146
        }
147
        return $params;
148 48
    }
149 2
150 1
    /**
151 47
     * Check year format
152 44
     * @param mixed $year year to validate
153 43
     * @return int year validated
154 4
     * @throws \Exception
155 1
     */
156 1
    private function checkYear(int $year): int
157 4
    {
158 1
        $year = (int) $year;
159 1
        return $year;
160
    }
161 46
162
    /**
163
     * Check language
164 126
     * @param string $language Language string with format ISO 639-1
165
     * @return string Language string validated
166
     * @throws IncorrectParamException
167
     */
168
    private function checkLanguage(string $language): string
169
    {
170
        $check = preg_match("#([a-z]{2})-([A-Z]{2})#", $language);
171
        if ($check === 0 || $check === false) {
172
            $this->logger->error('Incorrect language param option', array('language' => $language));
173 1
            throw new IncorrectParamException;
174
        }
175 1
        return $language;
176 1
    }
177
}
178