Completed
Pull Request — master (#422)
by Anton
04:34
created

Request::isPut()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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