Completed
Pull Request — master (#16)
by Mischa
19:07 queued 12:02
created

Request::processParameters()   C

Complexity

Conditions 22
Paths 25

Size

Total Lines 52
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 52
rs 5.8396
cc 22
eloc 38
nc 25
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file is part of the PHP SDK library for the Superdesk Content API.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú.
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace Superdesk\ContentApiSdk\API;
16
17
use Superdesk\ContentApiSdk\API\Request\RequestInterface;
18
use Superdesk\ContentApiSdk\ContentApiSdk;
19
use Superdesk\ContentApiSdk\Exception\ResponseException;
20
use Superdesk\ContentApiSdk\Exception\RequestException;
21
use Superdesk\ContentApiSdk\Exception\InvalidArgumentException;
22
use Superdesk\ContentApiSdk\Exception\InvalidDataException;
23
24
/**
25
 * API Request object.
26
 */
27
class Request implements RequestInterface
28
{
29
    /**
30
     * Protocol for api request.
31
     *
32
     * @var string
33
     */
34
    protected $protocol = 'https';
35
36
    /**
37
     * Hostname for api request.
38
     *
39
     * @var string
40
     */
41
    protected $host;
42
43
    /**
44
     * Api port.
45
     *
46
     * @var int
47
     */
48
    protected $port = 80;
49
50
    /**
51
     * Request uri.
52
     *
53
     * @var string
54
     */
55
    protected $uri;
56
57
    /**
58
     * Parameters for request.
59
     *
60
     * @var mixed[]
61
     */
62
    protected $parameters = array();
63
64
    /**
65
     * Boolean for status of parameter handling. When set to true invalid
66
     * parameters will be cleaned out before being sent to the API.
67
     *
68
     * @var boolean
69
     */
70
    protected $cleanParameters = true;
71
72
    /**
73
     * A list of parameters the Content API accepts.
74
     *
75
     * For a list of accepted parameters find the variable allowed_params in
76
     * the following file:
77
     * https://github.com/superdesk/superdesk-content-api/blob/master/content_api/items/service.py
78
     *
79
     * @var string[]
80
     */
81
    protected $validParameters = array(
82
        'start_date', 'end_date', 'q', 'max_results', 'page',
83
        'include_fields', 'exclude_fields'
84
    );
85
86
    /**
87
     * Request headers.
88
     *
89
     * @var string[]
90
     */
91
    protected $headers = array();
92
93
    /**
94
     * Request options, usuably in clients, etc.
95
     *
96
     * @var mixed[]
97
     */
98
    protected $options = array();
99
100
    /**
101
     * Construct a request object.
102
     *
103
     * @param string $hostname Host name
104
     * @param string $uri Request uri
105
     * @param mixed[] $parameters Parameters
106
     * @param int $port Port
107
     * @param string $protocol Protocol
108
     */
109
    public function __construct(
110
        $hostname = null,
111
        $uri = null,
112
        array $parameters = null,
113
        $port = null,
114
        $protocol = null
115
    ) {
116
        if (is_string($hostname) && !empty($hostname)) {
117
            $this->setHost($hostname);
118
        }
119
        if (is_string($uri) && !empty($uri)) {
120
            $this->setUri($uri);
121
        }
122
        if (!empty($parameters)) {
123
            $this->setParameters($parameters);
124
        }
125
        if (is_int($port)) {
126
            $this->setPort($port);
127
        }
128
        if (is_string($protocol) && !empty($protocol)) {
129
            $this->setProtocol($protocol);
130
        }
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136
    public function getProtocol()
137
    {
138
        return $this->protocol;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function setProtocol($protocol)
145
    {
146
        if ($protocol !== 'http' && $protocol !== 'https') {
147
            throw new InvalidArgumentException('Property protocol can only have the values "http" or "https".');
148
        }
149
150
        $this->protocol = $protocol;
151
152
        return $this;
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getHost()
159
    {
160
        return $this->host;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function setHost($host)
167
    {
168
        if ($host === null || !is_string($host) || empty($host)) {
169
            throw new InvalidArgumentException('Property host should be of type string and cannot be empty.');
170
        }
171
172
        $this->host = $host;
173
174
        return $this;
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     */
180
    public function getPort()
181
    {
182
        return $this->port;
183
    }
184
185
    /**
186
     * {@inheritdoc}
187
     */
188
    public function setPort($port)
189
    {
190
        if (!is_int($port)) {
191
            throw new InvalidArgumentException('Property port should be of type integer.');
192
        }
193
194
        $this->port = $port;
195
196
        return $this;
197
    }
198
199
    /**
200
     * {@inheritdoc}
201
     */
202
    public function getUri()
203
    {
204
        return $this->uri;
205
    }
206
207
    /**
208
     * {@inheritdoc}
209
     */
210
    public function setUri($uri)
211
    {
212
        $this->uri = $uri;
213
214
        return $this;
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function getParameters()
221
    {
222
        return $this->parameters;
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228
    public function setParameters(array $parameters)
229
    {
230
        try {
231
            $this->parameters = $this->processParameters($parameters, $this->cleanParameters);
232
        } catch (InvalidArgumentException $e) {
233
            throw new RequestException($e->getMessage(), $e->getCode(), $e);
234
        }
235
236
        return $this;
237
    }
238
239
    /**
240
     * {@inheritdoc}
241
     */
242
    public function getCleanParameters()
243
    {
244
        return $this->cleanParameters;
245
    }
246
247
    /**
248
     * {@inheritdoc}
249
     */
250
    public function enableParameterCleaning()
251
    {
252
        $this->cleanParameters = true;
253
254
        return $this;
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function disableParameterCleaning()
261
    {
262
        $this->cleanParameters = false;
263
264
        return $this;
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    public function getHeaders()
271
    {
272
        return $this->headers;
273
    }
274
275
    /**
276
     * {@inheritdoc}
277
     */
278
    public function setHeaders(array $headers)
279
    {
280
        $this->headers = $headers;
281
282
        return $this;
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288
    public function getOptions()
289
    {
290
        return $this->options;
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296
    public function setOptions(array $options)
297
    {
298
        $this->options = $options;
299
300
        return $this;
301
    }
302
303
    /**
304
     * {@inheritdoc}
305
     */
306
    public function getBaseUrl()
307
    {
308
        return sprintf('%s://%s:%s', $this->protocol, $this->host, $this->port);
309
    }
310
311
    /**
312
     * {@inheritdoc}
313
     */
314
    public function getFullUrl()
315
    {
316
        return sprintf('%s/%s?%s', $this->getBaseUrl(), trim($this->uri, '/ '), http_build_query($this->parameters));
317
    }
318
319
    /**
320
     * Type conversion method for parameters accepted by the API. Will
321
     * by default automatically unset invalid parameters, this behaviour can be
322
     * overridden with the second argument.
323
     *
324
     * @param  mixed[] $requestParameters Array of parameters
325
     * @param  boolean $unsetInvalidParameters Boolean to clean out invalid
326
     *                                         parameters
327
     *
328
     * @return mixed[] Returns an array of parameters with API safe types
329
     * @throws InvalidArgumentException When an invalid type is set for a
330
     *                                  valid parameter
331
     */
332
    public function processParameters(
333
        array $requestParameters,
334
        $unsetInvalidParameters = true
335
    ) {
336
        $processedParameters = $requestParameters;
337
338
        foreach ($requestParameters as $name => $value) {
339
340
            if ($unsetInvalidParameters && !in_array($name, $this->validParameters)) {
341
                unset($processedParameters[$name]);
342
                continue;
343
            }
344
345
            switch ($name) {
346
                case 'start_date':
347
                case 'end_date':
348
                        if (!is_string($value) && !($value instanceof \DateTime)) {
349
                            throw new InvalidArgumentException(sprintf('Parameter %s should be of type string or DateTime.', $name));
350
                        } elseif ($value instanceof \DateTime) {
351
                            $value = $value->format('Y-m-d');
352
                        } elseif (!preg_match('/\d\d\d\d\-\d\d\-\d\d/', $value)) {
353
                            throw new InvalidArgumentException(sprintf('Parameter %s has invalid format, please use yyyy-mm-dd.', $name));
354
                        }
355
                    break;
356
                case 'q':
357
                        if (!is_string($value)) {
358
                            throw new InvalidArgumentException(sprintf('Parameter %s should be of type string.', $name));
359
                        }
360
                    break;
361
                case 'include_fields':
362
                case 'exclude_fields':
363
                        if (!is_string($value) && !is_array($value)) {
364
                            throw new InvalidArgumentException(sprintf('Parameter %s should be of type string or array.', $name));
365
                        } elseif (is_array($value)) {
366
                            $value = implode(',', $value);
367
                        }
368
                    break;
369
                case 'page':
370
                case 'max_results':
371
                        if (!is_int($value) && !ctype_digit($value)) {
372
                            throw new InvalidArgumentException(sprintf('Parameter %s should be of type integer.', $name));
373
                        } elseif (!is_int($value)) {
374
                            $value = (int) $value;
375
                        }
376
                    break;
377
            }
378
379
            $processedParameters[$name] = $value;
380
        }
381
382
        return $processedParameters;
383
    }
384
}
385