Completed
Push — master ( 070a1e...ccce77 )
by Anton
12s
created

Request::getClientIp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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