Passed
Pull Request — master (#48)
by
unknown
03:49
created

Tmdb::checkOptionDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
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 1236
    public function __construct(string $api_key, int $version = 3, LoggerInterface $logger, HttpRequestInterface $http_request)
93
    {
94 1236
        $this->api_key      = $api_key;
95 1236
        $this->logger       = $logger;
96 1236
        $this->version      = $version;
97 1236
        $this->http_request = $http_request;
98 1236
        $this->request      = new \stdClass;
99 1236
    }
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 1086
    public function getRequest(string $action, array $options = array()) : ?\stdClass
108
    {
109 1086
        $this->logger->debug('Start sending HTTP request with GET method', array('action' => $action, 'options' => $options));
110 1086
        $this->url = $this->buildHTTPUrl($action, $options);
111 1086
        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 45
    public function postRequest(string $action, array $options = array(), array $form_params = array()) : ?\stdClass
122
    {
123 45
        $this->logger->debug('Start sending HTTP request with POST method', array('action' => $action, 'options' => $options, 'form_params' => $form_params));
124 45
        $this->url = $this->buildHTTPUrl($action, $options);
125 45
        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 15
    public function deleteRequest(string $action, array $options = array()) : ?\stdClass
135
    {
136 15
        $this->logger->debug('Start sending HTTP request with DELETE method', array('action' => $action, 'options' => $options));
137 15
        $this->url = $this->buildHTTPUrl($action, $options);
138 15
        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 18
    protected function sendRequest(string $method, string $url, array $form_params = array()) : ?\stdClass
149
    {
150
        try {
151 18
            $method_name = strtolower($method).'Response';
152 18
            $res = $this->http_request->$method_name($url, [], $form_params);
153 18
            $response = $this->decodeRequest($res, $method, $url, $form_params);
154 9
            return $response;
155 9
        } catch (TmdbException $e) {
156 9
            $this->logger->error('sendRequest failed : '.$e->getMessage(), array('method' => $method, 'url' => $url, 'form_params' => $form_params));
157 9
            throw $e;
158
        }
159
    }
160
161
    /**
162
     * Decode request response
163
     * @param  mixed $res
164
     * @param  string $method
165
     * @param  string $url
166
     * @param  array $form_params
167
     * @return \stdClass
168
     */
169 18
    private function decodeRequest($res, $method, $url, $form_params) : \stdClass
170
    {
171 18
        $content = $res->getBody();
172
173 18
        if (is_object($content)) {
174
            $content = $content->getContents();
175
        }
176 18
        if (empty($content)) {
177 6
            $this->logger->error('Request Body empty', array('method' => $method, 'url' => $url, 'form_params' => $form_params));
178 6
            throw new ServerErrorException();
179
        }
180 12
        $response = json_decode($content);
181 12
        if (empty($response)) {
182 3
            $this->logger->error('Request Body can not be decode', array('method' => $method, 'url' => $url, 'form_params' => $form_params));
183 3
            throw new ServerErrorException();
184
        }
185 9
        return $response;
186
    }
187
188
    /**
189
     * Build URL for HTTP Call
190
     * @param string $action API action to request
191
     * @param array $options Array of options of the request (optional)
192
     * @return string
193
     */
194 1092
    private function buildHTTPUrl(string $action, array $options) : string
195
    {
196
        // Url construction
197 1092
        $url = $this->base_api_url . $this->version . '/' . $action;
198
199
        // Parameters
200 1092
        $params            = [];
201 1092
        $params['api_key'] = $this->api_key;
202
203 1092
        $params = array_merge($params, $options);
204
205
        // URL with paramters construction
206 1092
        $url = $url . '?' . http_build_query($params);
207
208 1092
        return $url;
209
    }
210
211
    /**
212
     * Get API Configuration
213
     * @return \stdClass
214
     * @throws TmdbException
215
     */
216 162
    public function getConfiguration() : \stdClass
217
    {
218
        try {
219 162
            $this->logger->debug('Start getting configuration');
220 162
            if (is_null($this->configuration)) {
221 162
                $this->logger->debug('No configuration found, sending HTTP request to get it');
222 162
                $this->configuration = $this->getRequest('configuration');
223
            }
224 159
            return $this->configuration;
225 3
        } catch (TmdbException $ex) {
226 3
            throw $ex;
227
        }
228
    }
229
230
    /**
231
     * Get logger
232
     * @return LoggerInterface
233
     */
234 1122
    public function getLogger() : LoggerInterface
235
    {
236 1122
        return $this->logger;
237
    }
238
239
    /**
240
     * Magical property getter
241
     * @param  string $name Name of the property
242
     * @return string       Value of the property
243
     */
244 246
    public function __get(string $name) : string
245
    {
246 164
        switch ($name) {
247 246
            case 'url':
248 243
                return $this->$name;
249
            default:
250 3
                throw new IncorrectParamException;
251
        }
252
    }
253
254
    /**
255
     * Check year option and return correct value
256
     * @param array $options
257
     * @param array &$return Return array to save valid option
258
     * @return void
259
     */
260 87
    public function checkOptionYear(array $options, array &$return) : void
261
    {
262 87
        if (isset($options['year'])) {
263 3
            $return['year'] = (int) $options['year'];
264
        }
265 87
    }
266
267
    /**
268
     * Check Language string with format ISO 639-1
269
     * @param array $options
270
     * @param array &$return Return array to save valid option
271
     * @return void
272
     */
273 942
    public function checkOptionLanguage(array $options, array &$return) : void
274
    {
275 942
        if (isset($options['language'])) {
276 105
            $check = preg_match("#([a-z]{2})-([A-Z]{2})#", $options['language']);
277 105
            if ($check === 0 || $check === false) {
278 3
                $this->logger->error('Incorrect language param option', array('language' => $options['language']));
279 3
                throw new IncorrectParamException;
280
            }
281 102
            $return['language'] = $options['language'];
282
        }
283 939
    }
284
285
    /**
286
     * Check include adult option
287
     * @param  array $options
288
     * @param array &$return Return array to save valid option
289
     * @return void
290
     */
291 87
    public function checkOptionIncludeAdult(array $options, array &$return) : void
292
    {
293 87
        if (isset($options['include_adult'])) {
294 3
            $return['include_adult'] = filter_var($options['include_adult'], FILTER_VALIDATE_BOOLEAN);
295
        }
296 87
    }
297
298
    /**
299
     * Check page option
300
     * @param  array  $options
301
     * @param array &$return Return array to save valid option
302
     * @return void
303
     */
304 147
    public function checkOptionPage(array $options, array &$return) : void
305
    {
306 147
        if (isset($options['page'])) {
307 3
            $return['page'] = (int) $options['page'];
308
        }
309 147
    }
310
311
    /**
312
     * Check sort by option
313
     * @param  array  $options
314
     * @param array &$return Return array to save valid option
315
     * @return void
316
     */
317 27
    public function checkOptionSortBy(array $options, array &$return) : void
318
    {
319 27
        if (isset($options['sort_by'])) {
320 6
            switch ($options['sort_by']) {
321 6
                case 'asc':
322 3
                case 'desc':
323 3
                    break;
324
                default:
325 3
                    throw new IncorrectParamException;
326
            }
327 3
            $return['sort_by'] = 'created_at.'.$options['sort_by'];
328
        }
329 24
    }
330
331
    /**
332
     * Check query option
333
     * @param  array  $options
334
     * @param array &$return Return array to save valid option
335
     * @return void
336
     */
337 84
    public function checkOptionQuery(array $options, array &$return) : void
338
    {
339 84
        if (isset($options['query'])) {
340 84
            $return['query'] = trim($options['query']);
341
        }
342 84
    }
343
344
    /**
345
     * Check session_id option
346
     * @param array  $options
347
     * @param array &$return Return array to save valid option
348
     * @return void
349
     */
350 21
    public function checkOptionSessionId(array $options, array &$return) : void
351
    {
352 21
        if (isset($options['session_id'])) {
353 21
            $return['session_id'] = trim($options['session_id']);
354
        }
355 21
    }
356
357
    /**
358
     * Check date option
359
     * @param  string $option
360
     * @param  string $format
361
     * @return bool
362
     * @author Steve Richter <[email protected]>
363
     */
364 27
    public function checkOptionDate(string $option, string $format = 'Y-m-d') : bool
365
    {
366 27
        $date = \DateTime::createFromFormat($format, $option);
367
368 27
        return $date && $date->format($format) === $option;
369
    }
370
371
    /**
372
     * Check date range options
373
     * @param  array $options
374
     * @param  array &$return Return array to save valid options
375
     * @return void
376
     * @throws IncorrectParamException
377
     * @author Steve Richter <[email protected]>
378
     */
379 42
    public function checkOptionDateRange(array $options, array &$return) : void
380
    {
381 42
        foreach (['start_date', 'end_date'] as $optionName) {
382 42
            if (isset($options[$optionName])) {
383 27
                if ($this->checkOptionDate($options[$optionName])) {
384 15
                    $return[$optionName] = $options[$optionName];
385
                } else {
386 15
                    $this->logger->error('Incorrect date param option', array($optionName => $options[$optionName]));
387 33
                    throw new IncorrectParamException;
388
                }
389
            }
390
        }
391 27
    }
392
}
393