Completed
Push — master ( 44d7c9...9d8d85 )
by
unknown
02:30
created

Tmdb::decodeRequest()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0092

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 11
cts 12
cp 0.9167
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 6
nop 4
crap 4.0092
1
<?php declare(strict_types = 1);
2
3
/**
4
 * This file is part of the Tmdb package.
5
 *
6
 * (c) Vincent Faliès <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 *
11
 * @author Vincent Faliès <[email protected]>
12
 * @copyright Copyright (c) 2017
13
 */
14
15
namespace VfacTmdb;
16
17
use VfacTmdb\Interfaces\TmdbInterface;
18
use VfacTmdb\Interfaces\HttpRequestInterface;
19
use Psr\Log\LoggerInterface;
20
use VfacTmdb\Exceptions\TmdbException;
21
use VfacTmdb\Exceptions\IncorrectParamException;
22
use VfacTmdb\Exceptions\ServerErrorException;
23
24
/**
25
 * Tmdb wrapper core class
26
 * @package Tmdb
27
 * @author Vincent Faliès <[email protected]>
28
 * @copyright Copyright (c) 2017
29
 */
30
class Tmdb implements TmdbInterface
31
{
32
33
    /**
34
     * API Key
35
     * @var string
36
     */
37
    private $api_key = null;
38
39
    /**
40
     * API configuration
41
     * @var \stdClass
42
     */
43
    protected $configuration = null;
44
45
    /**
46
     * API Genres
47
     * @var \stdClass
48
     */
49
    protected $genres = null;
50
51
    /**
52
     * Base URL of the API
53
     * @var string
54
     */
55
    public $base_api_url = 'https://api.themoviedb.org/';
56
57
    /**
58
     * Logger
59
     * @var LoggerInterface
60
     */
61
    protected $logger = null;
62
63
    /**
64
     * API Version
65
     * @var int
66
     */
67
    protected $version = 3;
68
69
    /**
70
     * Http request object
71
     * @var HttpRequestInterface
72
     */
73
    protected $http_request = null;
74
    /**
75
     * Request object
76
     * @var \stdClass
77
     */
78
    protected $request;
79
    /**
80
     * Last request url
81
     * @var string
82
     */
83
    protected $url = null;
84
85
    /**
86
     * Constructor
87
     * @param string $api_key TMDB API Key
88
     * @param int $version Version of API (Not yet used)
89
     * @param LoggerInterface $logger Logger used in the class
90
     * @param HttpRequestInterface $http_request
91
     */
92 356
    public function __construct(string $api_key, int $version = 3, LoggerInterface $logger, HttpRequestInterface $http_request)
93
    {
94 356
        $this->api_key      = $api_key;
95 356
        $this->logger       = $logger;
96 356
        $this->version      = $version;
97 356
        $this->http_request = $http_request;
98 356
        $this->request      = new \stdClass;
99 356
    }
100
101
    /**
102
     * Send request to TMDB API with GET method
103
     * @param string $action API action to request
104
     * @param array $options Array of options of the request (optional)
105
     * @return \stdClass|null
106
     */
107 317
    public function getRequest(string $action, array $options = array()) : ?\stdClass
108
    {
109 317
        $this->logger->debug('Start sending HTTP request with GET method', array('action' => $action, 'options' => $options));
110 317
        $this->url = $this->buildHTTPUrl($action, $options);
111 317
        return $this->sendRequest('GET', $this->url);
112
    }
113
114
    /**
115
     * Send request to TMDB API with POST method
116
     * @param string $action API action to request
117
     * @param array $options Array of options of the request (optional)
118
     * @param array $form_params form_params for request options
119
     * @return \stdClass|null
120
     */
121 15
    public function postRequest(string $action, array $options = array(), array $form_params = array()) : ?\stdClass
122
    {
123 15
        $this->logger->debug('Start sending HTTP request with POST method', array('action' => $action, 'options' => $options, 'form_params' => $form_params));
124 15
        $this->url = $this->buildHTTPUrl($action, $options);
125 15
        return $this->sendRequest('POST', $this->url, $form_params);
126
    }
127
128
    /**
129
     * Send request to TMDB API with DELETE method
130
     * @param  string $action  API action to request
131
     * @param  array  $options Array of options of the request (optional)
132
     * @return \stdClass|null
133
     */
134 5
    public function deleteRequest(string $action, array $options = array()) : ?\stdClass
135
    {
136 5
        $this->logger->debug('Start sending HTTP request with DELETE method', array('action' => $action, 'options' => $options));
137 5
        $this->url = $this->buildHTTPUrl($action, $options);
138 5
        return $this->sendRequest('DELETE', $this->url);
139
    }
140
141
    /**
142
     * Send request to TMDB API with GET method
143
     * @param string $method HTTP method (GET, POST)
144
     * @param string $url API url to request
145
     * @param array $form_params form params request options
146
     * @return \stdClass|null
147
     */
148 6
    protected function sendRequest(string $method, string $url, array $form_params = array()) : ?\stdClass
149
    {
150
        try {
151 6
            $res = new \stdClass();
152 6
            $method_name = strtolower($method).'Response';
153 6
            $res = $this->http_request->$method_name($url, [], $form_params);
154 6
            $response = $this->decodeRequest($res, $method, $url, $form_params);
155 3
            return $response;
156 3
        } catch (TmdbException $e) {
157 3
            $this->logger->error('sendRequest failed : '.$e->getMessage(), array('method' => $method, 'url' => $url, 'form_params' => $form_params));
158 3
            throw $e;
159
        }
160
    }
161
162
    /**
163
     * Decode request response
164
     * @param  mixed $res
165
     * @param  string $method
166
     * @param  string $url
167
     * @param  array $form_params
168
     * @return \stdClass
169
     */
170 6
    private function decodeRequest($res, $method, $url, $form_params) : \stdClass
171
    {
172 6
        $content = $res->getBody();
173 6
        if (is_object($content))
174
        {
175
            $content = $content->getContents();
176
        }
177
178 6
        if (empty($content)) {
179 2
            $this->logger->error('Request Body empty', array('method' => $method, 'url' => $url, 'form_params' => $form_params));
180 2
            throw new ServerErrorException();
181
        }
182 4
        $response = json_decode($content);
183 4
        if (empty($response)) {
184 1
            $this->logger->error('Request Body can not be decode', array('method' => $method, 'url' => $url, 'form_params' => $form_params));
185 1
            throw new ServerErrorException();
186
        }
187 3
        return $response;
188
    }
189
190
    /**
191
     * Build URL for HTTP Call
192
     * @param string $action API action to request
193
     * @param array $options Array of options of the request (optional)
194
     * @return string
195
     */
196 319
    private function buildHTTPUrl(string $action, array $options) : string
197
    {
198
        // Url construction
199 319
        $url = $this->base_api_url . $this->version . '/' . $action;
200
201
        // Parameters
202 319
        $params            = [];
203 319
        $params['api_key'] = $this->api_key;
204
205 319
        $params = array_merge($params, $options);
206
207
        // URL with paramters construction
208 319
        $url = $url . '?' . http_build_query($params);
209
210 319
        return $url;
211
    }
212
213
    /**
214
     * Get API Configuration
215
     * @return \stdClass
216
     * @throws TmdbException
217
     */
218 50
    public function getConfiguration() : \stdClass
219
    {
220
        try {
221 50
            $this->logger->debug('Start getting configuration');
222 50
            if (is_null($this->configuration)) {
223 50
                $this->logger->debug('No configuration found, sending HTTP request to get it');
224 50
                $this->configuration = $this->getRequest('configuration');
225
            }
226 49
            return $this->configuration;
227 1
        } catch (TmdbException $ex) {
228 1
            throw $ex;
229
        }
230
    }
231
232
    /**
233
     * Get logger
234
     * @return LoggerInterface
235
     */
236 324
    public function getLogger() : LoggerInterface
237
    {
238 324
        return $this->logger;
239
    }
240
241
    /**
242
     * Magical property getter
243
     * @param  string $name Name of the property
244
     * @return string       Value of the property
245
     */
246 73
    public function __get(string $name) : string
247
    {
248
        switch ($name) {
249 73
            case 'url':
250 72
                return $this->$name;
251
            default:
252 1
                throw new IncorrectParamException;
253
        }
254
    }
255
256
    /**
257
     * Check year option and return correct value
258
     * @param array $options
259
     * @param array &$return Return array to save valid option
260
     * @return void
261
     */
262 29
    public function checkOptionYear(array $options, array &$return) : void
263
    {
264 29
        if (isset($options['year'])) {
265 1
            $return['year'] = (int) $options['year'];
266
        }
267 29
    }
268
269
    /**
270
     * Check Language string with format ISO 639-1
271
     * @param array $options
272
     * @param array &$return Return array to save valid option
273
     * @return void
274
     */
275 277
    public function checkOptionLanguage(array $options, array &$return) : void
276
    {
277 277
        if (isset($options['language'])) {
278 35
            $check = preg_match("#([a-z]{2})-([A-Z]{2})#", $options['language']);
279 35
            if ($check === 0 || $check === false) {
280 1
                $this->logger->error('Incorrect language param option', array('language' => $options['language']));
281 1
                throw new IncorrectParamException;
282
            }
283 34
            $return['language'] = $options['language'];
284
        }
285 276
    }
286
287
    /**
288
     * Check include adult option
289
     * @param  array $options
290
     * @param array &$return Return array to save valid option
291
     * @return void
292
     */
293 29
    public function checkOptionIncludeAdult(array $options, array &$return) : void
294
    {
295 29
        if (isset($options['include_adult'])) {
296 1
            $return['include_adult'] = filter_var($options['include_adult'], FILTER_VALIDATE_BOOLEAN);
297
        }
298 29
    }
299
300
    /**
301
     * Check page option
302
     * @param  array  $options
303
     * @param array &$return Return array to save valid option
304
     * @return void
305
     */
306 38
    public function checkOptionPage(array $options, array &$return) : void
307
    {
308 38
        if (isset($options['page'])) {
309 1
            $return['page'] = (int) $options['page'];
310
        }
311 38
    }
312
313
    /**
314
     * Check sort by option
315
     * @param  array  $options
316
     * @param array &$return Return array to save valid option
317
     * @return void
318
     */
319 9
    public function checkOptionSortBy(array $options, array &$return) : void
320
    {
321 9
        if (isset($options['sort_by'])) {
322 2
            switch ($options['sort_by']) {
323 2
                case 'asc':
324 1
                case 'desc':
325 1
                    break;
326
                default:
327 1
                    throw new IncorrectParamException;
328
            }
329 1
            $return['sort_by'] = 'created_at.'.$options['sort_by'];
330
        }
331 8
    }
332
333
    /**
334
     * Check query option
335
     * @param  array  $options
336
     * @param array &$return Return array to save valid option
337
     * @return void
338
     */
339 28
    public function checkOptionQuery(array $options, array &$return) : void
340
    {
341 28
        if (isset($options['query'])) {
342 28
            $return['query'] = trim($options['query']);
343
        }
344 28
    }
345
346
    /**
347
     * Check session_id option
348
     * @param array  $options
349
     * @param array &$return Return array to save valid option
350
     * @return void
351
     */
352 7
    public function checkOptionSessionId(array $options, array &$return) : void
353
    {
354 7
        if (isset($options['session_id'])) {
355 7
            $return['session_id'] = trim($options['session_id']);
356
        }
357 7
    }
358
}
359