Completed
Push — master ( 1fdf1f...4537f5 )
by Anton
10s
created

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