Completed
Pull Request — master (#363)
by Anton
06:05
created

Request::getAccept()   C

Complexity

Conditions 10
Paths 8

Size

Total Lines 55
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 11.3824

Importance

Changes 5
Bugs 1 Features 2
Metric Value
cc 10
eloc 25
nc 8
nop 1
dl 0
loc 55
ccs 19
cts 25
cp 0.76
crap 11.3824
rs 6.8372
c 5
b 1
f 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
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Bluz\Proxy;
13
14
use Bluz\Common\Exception\ComponentException;
15
use Bluz\Request\RequestFactory;
16
use Psr\Http\Message\UriInterface;
17
use Zend\Diactoros\ServerRequest as Instance;
18
19
/**
20
 * Proxy to Request
21
 *
22
 * Example of usage
23
 * <code>
24
 *     use Bluz\Proxy\Request;
25
 *
26
 *     Request::getParam('foo');
27
 * </code>
28
 *
29
 * @package  Bluz\Proxy
30
 * @author   Anton Shevchuk
31
 * 
32
 * @method   static \Psr\Http\Message\UriInterface getUri()
33
 * @see      \Zend\Diactoros\RequestTrait::getUri()
34
 *
35
 * @method   static Instance getInstance()
36
 */
37
class Request extends AbstractProxy
38
{
39
    /**
40
     * @const string HTTP methods
41
     */
42
    const METHOD_OPTIONS = 'OPTIONS';
43
    const METHOD_GET = 'GET';
44
    const METHOD_HEAD = 'HEAD';
45
    const METHOD_PATCH = 'PATCH';
46
    const METHOD_POST = 'POST';
47
    const METHOD_PUT = 'PUT';
48
    const METHOD_DELETE = 'DELETE';
49
    const METHOD_TRACE = 'TRACE';
50
    const METHOD_CONNECT = 'CONNECT';
51
52
    /**
53
     * @const string HTTP content types 
54
     */
55
    const TYPE_ANY = '*/*';
56
    const TYPE_HTML = 'text/html';
57
    const TYPE_JSON = 'application/json';
58
59
    /**
60
     * Init instance
61
     *
62
     * @throws ComponentException
63
     */
64
    protected static function initInstance()
65
    {
66
        throw new ComponentException("Class `Proxy\\Request` required external initialization");
67
    }
68
69
    /**
70
     * Retrieve a member of the $_SERVER super global
71
     *
72
     * If no $key is passed, returns the entire $_SERVER array.
73
     *
74
     * @param  string $key
75
     * @param  string $default Default value to use if key not found
76
     * @return string Returns null if key does not exist
77
     */
78 4
    public static function getServer($key = null, $default = null)
79
    {
80 4
        return RequestFactory::get($key, self::getInstance()->getServerParams(), $default);
81
    }
82
83
    /**
84
     * Retrieve a member of the $_COOKIE super global
85
     *
86
     * If no $key is passed, returns the entire $_COOKIE array.
87
     *
88
     * @param  string $key
89
     * @param  string $default Default value to use if key not found
90
     * @return string Returns null if key does not exist
91
     */
92
    public static function getCookie($key = null, $default = null)
93
    {
94
        return RequestFactory::get($key, self::getInstance()->getCookieParams(), $default);
95
    }
96
    /**
97
     * Retrieve a member of the $_ENV super global
98
     *
99
     * If no $key is passed, returns the entire $_ENV array.
100
     *
101
     * @param  string $key
102
     * @param  string $default Default value to use if key not found
103
     * @return string Returns null if key does not exist
104
     */
105
    public static function getEnv($key = null, $default = null)
106
    {
107
        return RequestFactory::get($key, $_ENV, $default);
108
    }
109
110
    /**
111
     * Search for a header value
112
     *
113
     * @param string $header
114
     * @param mixed  $default
115
     * @return string
116
     */
117 2
    public static function getHeader($header, $default = null)
118
    {
119 2
        return RequestFactory::getHeader($header, self::getInstance()->getHeaders(), $default);
120
    }
121
    
122
    /**
123
     * Access values contained in the superglobals as public members
124
     * Order of precedence: 1. GET, 2. POST, 3. COOKIE, 4. SERVER, 5. ENV
125
     *
126
     * @param  string $key
127
     * @param  null   $default
128
     * @return mixed
129
     * @link http://msdn.microsoft.com/en-us/library/system.web.httprequest.item.aspx
130
     */
131 40
    public static function getParam($key, $default = null)
132
    {
133
        switch (true) {
134 40
            case ($params = self::getInstance()->getQueryParams()) && isset($params[$key]):
135 3
                return $params[$key];
0 ignored issues
show
Bug introduced by
The variable $params seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
136 38
            case ($params = self::getInstance()->getParsedBody()) && isset($params[$key]):
137
                return $params[$key];
0 ignored issues
show
Bug introduced by
The variable $params seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
138 38
            case ($params = self::getInstance()->getCookieParams()) && isset($params[$key]):
139
                return $params[$key];
0 ignored issues
show
Bug introduced by
The variable $params seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
140 38
            case ($params = self::getInstance()->getServerParams()) && isset($params[$key]):
141
                return $params[$key];
0 ignored issues
show
Bug introduced by
The variable $params seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
142 38
            case isset($_ENV[$key]):
143
                return $_ENV[$key];
144
            default:
145 38
                return $default;
146
        }
147
    }
148
149
    /**
150
     * Get all params from GET and POST or PUT
151
     *
152
     * @return array
153
     */
154 3
    public static function getParams()
155
    {
156 3
        $query = (array) self::getInstance()->getQueryParams();
157 3
        $body = (array) self::getInstance()->getParsedBody();
158
159 3
        return array_merge($body, $query);
160
    }
161
162
    /**
163
     * Get uploaded file
164
     *
165
     * @param  string $name
166
     * @return \Zend\Diactoros\UploadedFile
167
     */
168
    public static function getFile($name)
169
    {
170
        return RequestFactory::get($name, self::getInstance()->getUploadedFiles());
171
    }
172
173
    /**
174
     * Get the client's IP address
175
     *
176
     * @param  bool $checkProxy
177
     * @return string
178
     */
179
    public static function getClientIp($checkProxy = true)
180
    {
181
        if ($checkProxy && self::getServer('HTTP_CLIENT_IP') != null) {
182
            $ip = self::getServer('HTTP_CLIENT_IP');
183
        } else {
184
            if ($checkProxy && self::getServer('HTTP_X_FORWARDED_FOR') != null) {
185
                $ip = self::getServer('HTTP_X_FORWARDED_FOR');
186
            } else {
187
                $ip = self::getServer('REMOTE_ADDR');
188
            }
189
        }
190
        return $ip;
191
    }
192
193
    /**
194
     * Get module
195
     *
196
     * @return string
197
     */
198 38
    public static function getModule()
199
    {
200 38
        return self::getParam('_module', Router::getDefaultModule());
201
    }
202
203
    /**
204
     * Get controller
205
     *
206
     * @return string
207
     */
208 38
    public static function getController()
209
    {
210 38
        return self::getParam('_controller', Router::getDefaultController());
211
    }
212
    
213
    /**
214
     * Get method
215
     *
216
     * @return string
217
     */
218
    public static function getMethod()
219
    {
220
        return self::getParam('_method', self::getInstance()->getMethod());
221
    }
222
223
    /**
224
     * Get Accept MIME Type
225
     *
226
     * @todo:  refactoring this method, accept types should be stored in static? variable
227
     * @param  array $allowTypes
228
     * @return string
229
     */
230 2
    public static function getAccept($allowTypes = [])
231
    {
232 2
        static $accept;
233
234 2
        if (!$accept) {
235
236
            // get header from request
237 1
            $header = self::getHeader('accept');
238
239
            // make array if types
240 1
            $header = explode(',', $header);
241 1
            $header = array_map('trim', $header);
242
243
            // result store
244 1
            $types = [];
245
246 1
            foreach ($header as $a) {
247
                // the default quality is 1.
248 1
                $q = 1;
249
                // check if there is a different quality
250 1
                if (strpos($a, ';q=') or strpos($a, '; q=')) {
251
                    // divide "mime/type;q=X" into two parts: "mime/type" i "X"
252
                    $res = preg_split('/;([ ]?)q=/', $a);
253
                    $a = $res[0];
254
                    $q = $res[1];
255
                }
256
                // remove other extension
257 1
                if (strpos($a, ';')) {
258
                    $a = substr($a, 0, strpos($a, ';'));
259
                }
260
261
                // mime-type $a is accepted with the quality $q
262
                // WARNING: $q == 0 means, that mime-type isn’t supported!
263 1
                $types[$a] = (float) $q;
264
            }
265 1
            arsort($types);
266 1
            $accept = $types;
267
        }
268
269
        // if no parameter was passed, just return parsed data
270 2
        if (empty($allowTypes)) {
271
            return $accept;
272
        }
273
274 2
        $mimeTypes = array_map('strtolower', $allowTypes);
275
276
        // let’s check our supported types:
277 2
        foreach ($accept as $mime => $q) {
278 2
            if ($q && in_array($mime, $mimeTypes)) {
279 2
                return $mime;
280
            }
281
        }
282
        // no mime-type found
283
        return null;
284
    }
285
    
286
    /**
287
     * Check CLI
288
     *
289
     * @return bool
290
     */
291
    public static function isCli()
292
    {
293
        return (PHP_SAPI === 'cli');
294
    }
295
296
    /**
297
     * Check HTTP
298
     *
299
     * @return bool
300
     */
301 1
    public static function isHttp()
302
    {
303 1
        return (PHP_SAPI !== 'cli');
304
    }
305
306
    /**
307
     * Is this a GET method request?
308
     *
309
     * @return bool
310
     */
311
    public static function isGet()
312
    {
313
        return (self::getInstance()->getMethod() === 'GET');
314
    }
315
316
    /**
317
     * Is this a POST method request?
318
     *
319
     * @return bool
320
     */
321
    public static function isPost()
322
    {
323
        return (self::getInstance()->getMethod() === 'POST');
324
    }
325
326
    /**
327
     * Is this a PUT method request?
328
     *
329
     * @return bool
330
     */
331
    public static function isPut()
332
    {
333
        return (self::getInstance()->getMethod() === 'PUT');
334
    }
335
336
    /**
337
     * Is this a DELETE method request?
338
     *
339
     * @return bool
340
     */
341
    public static function isDelete()
342
    {
343
        return (self::getInstance()->getMethod() === 'DELETE');
344
    }
345
346
    /**
347
     * Is the request a Javascript XMLHttpRequest?
348
     *
349
     * Should work with Prototype/Script.aculo.us, possibly others.
350
     *
351
     * @return bool
352
     */
353 2
    public static function isXmlHttpRequest()
354
    {
355 2
        return (self::getHeader('X-Requested-With') == 'XMLHttpRequest');
356
    }
357
}
358