Completed
Push — master ( 369b2c...ffb215 )
by Anton
8s
created

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