Completed
Push — master ( ccce77...cf02e9 )
by Anton
9s
created

Request   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 331
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 66.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 331
ccs 50
cts 75
cp 0.6667
rs 9.2
c 1
b 0
f 0
wmc 34
lcom 1
cbo 5

23 Methods

Rating   Name   Duplication   Size   Complexity  
A getQuery() 0 4 1
A getPost() 0 4 1
A getServer() 0 4 1
A getCookie() 0 4 1
A getEnv() 0 4 1
A getHeader() 0 4 1
A initInstance() 0 4 1
A getParam() 0 7 1
A getParams() 0 7 1
A getFile() 0 4 1
A getClientIp() 0 7 2
A getModule() 0 4 1
A getController() 0 4 1
A getMethod() 0 4 1
C getAccept() 0 41 7
B checkAccept() 0 20 5
A isCli() 0 4 1
A isHttp() 0 4 1
A isGet() 0 4 1
A isPost() 0 4 1
A isPut() 0 4 1
A isDelete() 0 4 1
A isXmlHttpRequest() 0 4 1
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Proxy;
12
13
use Bluz\Common\Exception\ComponentException;
14
use Bluz\Http\RequestMethod;
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
 * @todo Proxy class should be clean
33
 *
34
 * @method   static Instance getInstance()
35
 *
36
 * @method   static UriInterface getUri()
37
 * @see      \Zend\Diactoros\RequestTrait::getUri()
38
 */
39
class Request
40
{
41
    use ProxyTrait;
42
43
    /**
44
     * @const string HTTP content types
45
     */
46
    const TYPE_ANY = '*/*';
47
    const TYPE_HTML = 'text/html';
48
    const TYPE_JSON = 'application/json';
49
50
    /**
51
     * Init instance
52
     *
53
     * @throws ComponentException
54
     */
55
    protected static function initInstance()
56
    {
57
        throw new ComponentException('Class `Proxy\\Request` required external initialization');
58
    }
59
60
    /**
61
     * Retrieve a member of the $_GET super global
62
     *
63
     * If no $key is passed, returns the entire $_GET array.
64
     *
65
     * @param  string $key
66
     * @param  string $default Default value to use if key not found
67
     * @return string Returns null if key does not exist
68
     */
69 60
    public static function getQuery($key = null, $default = null)
70
    {
71 60
        return RequestFactory::get($key, self::getInstance()->getQueryParams(), $default);
72
    }
73
74
    /**
75
     * Retrieve a member of the $_POST super global
76
     *
77
     * If no $key is passed, returns the entire $_POST array.
78
     *
79
     * @param  string $key
80
     * @param  string $default Default value to use if key not found
81
     * @return string Returns null if key does not exist
82
     */
83 53
    public static function getPost($key = null, $default = null)
84
    {
85 53
        return RequestFactory::get($key, (array)self::getInstance()->getParsedBody(), $default);
86
    }
87
88
    /**
89
     * Retrieve a member of the $_SERVER super global
90
     *
91
     * If no $key is passed, returns the entire $_SERVER array.
92
     *
93
     * @param  string $key
94
     * @param  string $default Default value to use if key not found
95
     * @return string Returns null if key does not exist
96
     */
97 5
    public static function getServer($key = null, $default = null)
98
    {
99 5
        return RequestFactory::get($key, self::getInstance()->getServerParams(), $default);
100
    }
101
102
    /**
103
     * Retrieve a member of the $_COOKIE super global
104
     *
105
     * If no $key is passed, returns the entire $_COOKIE array.
106
     *
107
     * @param  string $key
108
     * @param  string $default Default value to use if key not found
109
     * @return string Returns null if key does not exist
110
     */
111 1
    public static function getCookie($key = null, $default = null)
112
    {
113 1
        return RequestFactory::get($key, self::getInstance()->getCookieParams(), $default);
114
    }
115
    /**
116
     * Retrieve a member of the $_ENV super global
117
     *
118
     * If no $key is passed, returns the entire $_ENV array.
119
     *
120
     * @param  string $key
121
     * @param  string $default Default value to use if key not found
122
     * @return string Returns null if key does not exist
123
     */
124
    public static function getEnv($key = null, $default = null)
125
    {
126
        return RequestFactory::get($key, $_ENV, $default);
127
    }
128
129
    /**
130
     * Search for a header value
131
     *
132
     * @param string $header
133
     * @param mixed  $default
134
     * @return string
135
     */
136 6
    public static function getHeader($header, $default = null)
137
    {
138 6
        return RequestFactory::getHeader($header, self::getInstance()->getHeaders(), $default);
139
    }
140
    
141
    /**
142
     * Access values contained in the superglobals as public members
143
     * Order of precedence: 1. GET, 2. POST
144
     *
145
     * @param  string $key
146
     * @param  null   $default
147
     * @return string|null
148
     * @link http://msdn.microsoft.com/en-us/library/system.web.httprequest.item.aspx
149
     */
150 60
    public static function getParam($key, $default = null)
151
    {
152
        return
153 60
            self::getQuery($key) ??
154 52
            self::getPost($key) ??
155 60
            $default;
156
    }
157
158
    /**
159
     * Get all params from GET and POST or PUT
160
     *
161
     * @return array
162
     */
163 19
    public static function getParams()
164
    {
165 19
        $body = (array) self::getInstance()->getParsedBody();
166 19
        $query = (array) self::getInstance()->getQueryParams();
167
168 19
        return array_merge($body, $query);
169
    }
170
171
    /**
172
     * Get uploaded file
173
     *
174
     * @param  string $name
175
     * @return \Zend\Diactoros\UploadedFile
176
     */
177
    public static function getFile($name)
178
    {
179
        return RequestFactory::get($name, self::getInstance()->getUploadedFiles());
180
    }
181
182
    /**
183
     * Get the client's IP address
184
     *
185
     * @param  bool $checkProxy
186
     * @return string
187
     */
188
    public static function getClientIp($checkProxy = true)
189
    {
190
        if ($checkProxy) {
191
            $result = self::getServer('HTTP_CLIENT_IP') ?? self::getServer('HTTP_X_FORWARDED_FOR') ?? null;
192
        }
193
        return $result ?? self::getServer('REMOTE_ADDR');
194
    }
195
196
    /**
197
     * Get module
198
     *
199
     * @return string
200
     */
201 43
    public static function getModule() : string
202
    {
203 43
        return self::getParam('_module', Router::getDefaultModule());
204
    }
205
206
    /**
207
     * Get controller
208
     *
209
     * @return string
210
     */
211 43
    public static function getController() : string
212
    {
213 43
        return self::getParam('_controller', Router::getDefaultController());
214
    }
215
    
216
    /**
217
     * Get method
218
     *
219
     * @return string
220
     */
221 11
    public static function getMethod() : string
222
    {
223 11
        return self::getParam('_method', self::getInstance()->getMethod());
224
    }
225
226
    /**
227
     * Get Accept MIME Type
228
     *
229
     * @return array
230
     */
231 6
    public static function getAccept() : array
232
    {
233 6
        static $accept;
234
235 6
        if (!$accept) {
236
            // save to static variable
237 1
            $accept = [];
238
239
            // get header from request
240 1
            $header = self::getHeader('accept');
241
242
            // nothing ...
243 1
            if (!$header) {
244
                return $accept;
245
            }
246
247
            // make array if types
248 1
            $header = explode(',', $header);
249 1
            $header = array_map('trim', $header);
250
251 1
            foreach ($header as $a) {
252
                // the default quality is 1.
253 1
                $q = 1;
254
                // check if there is a different quality
255 1
                if (strpos($a, ';q=') or strpos($a, '; q=')) {
256
                    // divide "mime/type;q=X" into two parts: "mime/type" i "X"
257
                    list($a, $q) = preg_split('/;([ ]?)q=/', $a);
258
                }
259
                // remove other extension
260 1
                if (strpos($a, ';')) {
261
                    $a = substr($a, 0, strpos($a, ';'));
262
                }
263
264
                // mime-type $a is accepted with the quality $q
265
                // WARNING: $q == 0 means, that mime-type isn’t supported!
266 1
                $accept[$a] = (float) $q;
267
            }
268 1
            arsort($accept);
269
        }
270 6
        return $accept;
271
    }
272
273
    /**
274
     * Check Accept header
275
     *
276
     * @param array $allowTypes
277
     * @return string
278
     */
279 6
    public static function checkAccept(array $allowTypes = [])
280
    {
281 6
        $accept = self::getAccept();
282
283
        // if no parameter was passed, just return first mime type from parsed data
284 6
        if (empty($allowTypes)) {
285
            return current(array_keys($accept));
286
        }
287
288 6
        $allowTypes = array_map('strtolower', $allowTypes);
289
290
        // let’s check our supported types:
291 6
        foreach ($accept as $mime => $quality) {
292 6
            if ($quality && in_array($mime, $allowTypes)) {
293 6
                return $mime;
294
            }
295
        }
296
        // no mime-type found
297
        return null;
298
    }
299
    
300
    /**
301
     * Check CLI
302
     *
303
     * @return bool
304
     */
305
    public static function isCli() : bool
306
    {
307
        return (PHP_SAPI === 'cli');
308
    }
309
310
    /**
311
     * Check HTTP
312
     *
313
     * @return bool
314
     */
315 3
    public static function isHttp() : bool
316
    {
317 3
        return (PHP_SAPI !== 'cli');
318
    }
319
320
    /**
321
     * Is this a GET method request?
322
     *
323
     * @return bool
324
     */
325
    public static function isGet() : bool
326
    {
327
        return (self::getInstance()->getMethod() === RequestMethod::GET);
328
    }
329
330
    /**
331
     * Is this a POST method request?
332
     *
333
     * @return bool
334
     */
335
    public static function isPost() : bool
336
    {
337
        return (self::getInstance()->getMethod() === RequestMethod::POST);
338
    }
339
340
    /**
341
     * Is this a PUT method request?
342
     *
343
     * @return bool
344
     */
345
    public static function isPut() : bool
346
    {
347
        return (self::getInstance()->getMethod() === RequestMethod::PUT);
348
    }
349
350
    /**
351
     * Is this a DELETE method request?
352
     *
353
     * @return bool
354
     */
355
    public static function isDelete() : bool
356
    {
357
        return (self::getInstance()->getMethod() === RequestMethod::DELETE);
358
    }
359
360
    /**
361
     * Is the request a Javascript XMLHttpRequest?
362
     *
363
     * @return bool
364
     */
365 6
    public static function isXmlHttpRequest() : bool
366
    {
367 6
        return (self::getHeader('X-Requested-With') === 'XMLHttpRequest');
368
    }
369
}
370