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