GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ServerRequest::getAttributes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * This file is part of the O2System Framework package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author         Steeve Andrian Salim
9
 * @copyright      Copyright (c) Steeve Andrian Salim
10
 */
11
12
// ------------------------------------------------------------------------
13
14
namespace O2System\Kernel\Http\Message;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Psr\Http\Message\ServerRequestInterface;
19
use O2System\Psr\Http\Message\StreamInterface;
20
use O2System\Psr\Http\Message\UploadedFileInterface;
21
22
/**
23
 * Class ServerRequest
24
 *
25
 * @package O2System\Kernel\Http\Message
26
 */
27
class ServerRequest extends Request implements ServerRequestInterface
28
{
29
    /**
30
     * Server Params
31
     *
32
     * @var array
33
     */
34
    protected $serverParams = [];
35
36
    /**
37
     * Server Cookie
38
     *
39
     * @var array
40
     */
41
    protected $cookieParams = [];
42
43
    /**
44
     * Server Query
45
     *
46
     * @var array
47
     */
48
    protected $queryParams = [];
49
50
    /**
51
     * Server Uploaded Files
52
     *
53
     * @var array
54
     */
55
    protected $uploadedFiles = [];
56
57
    /**
58
     * ServerRequest::__construct
59
     */
60
    public function __construct()
61
    {
62
        parent::__construct();
63
64
        // Set Cookie Params
65
        $this->cookieParams = $_COOKIE;
66
67
        // Set Header Params
68
        // In Apache, you can simply call apache_request_headers()
69
        if (function_exists('apache_request_headers')) {
70
            $this->headers = apache_request_headers();
0 ignored issues
show
Documentation Bug introduced by
It seems like apache_request_headers() can also be of type false. However, the property $headers is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
71
        }
72
73
        $this->headers[ 'Content-Type' ] = isset($_SERVER[ 'CONTENT_TYPE' ])
74
            ? $_SERVER[ 'CONTENT_TYPE' ]
75
            : @getenv(
76
                'CONTENT_TYPE'
77
            );
78
79
        foreach ($_SERVER as $key => $val) {
80
            if (strpos($key, 'SERVER') !== false) {
81
                $key = str_replace('SERVER_', '', $key);
82
                $this->serverParams[ $key ] = $val;
83
            }
84
85
            if (sscanf($key, 'HTTP_%s', $header) === 1) {
86
                // take SOME_HEADER and turn it into Some-Header
87
                $header = str_replace('_', ' ', strtolower($header));
88
                $header = str_replace(' ', '-', ucwords($header));
89
90
                $this->headers[ $header ] = $_SERVER[ $key ];
91
            }
92
        }
93
94
        // Set Query Params
95
        if (null !== ($queryString = $this->uri->getQuery())) {
0 ignored issues
show
introduced by
The condition null !== $queryString = $this->uri->getQuery() is always true.
Loading history...
96
            parse_str($queryString, $this->queryParams);
97
        }
98
99
        // Populate file array
100
        $uploadedFiles = [];
101
102
        if (count($_FILES)) {
103
            foreach ($_FILES as $key => $value) {
104
                if (is_array($value[ 'name' ])) {
105
                    for ($i = 0; $i < count($value[ 'name' ]); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
106
                        if ( ! is_array($value[ 'name' ])) {
107
                            $uploadedFiles[ $key ][ $i ] = $value;
108
                            break;
109
                        }
110
111
                        $uploadedFiles[ $key ][ $i ][ 'name' ] = $value[ 'name' ][ $i ];
112
                        $uploadedFiles[ $key ][ $i ][ 'type' ] = $value[ 'type' ][ $i ];
113
                        $uploadedFiles[ $key ][ $i ][ 'tmp_name' ] = $value[ 'tmp_name' ][ $i ];
114
                        $uploadedFiles[ $key ][ $i ][ 'error' ] = $value[ 'error' ][ $i ];
115
                        $uploadedFiles[ $key ][ $i ][ 'size' ] = $value[ 'size' ][ $i ];
116
                    }
117
                } else {
118
                    $uploadedFiles[ $key ][ 'name' ] = $value[ 'name' ];
119
                    $uploadedFiles[ $key ][ 'type' ] = $value[ 'type' ];
120
                    $uploadedFiles[ $key ][ 'tmp_name' ] = $value[ 'tmp_name' ];
121
                    $uploadedFiles[ $key ][ 'error' ] = $value[ 'error' ];
122
                    $uploadedFiles[ $key ][ 'size' ] = $value[ 'size' ];
123
                }
124
            }
125
        }
126
127
        $this->uploadedFiles = $uploadedFiles;
128
    }
129
130
    //--------------------------------------------------------------------
131
132
    /**
133
     * ServerRequest::getServerParams
134
     *
135
     * Retrieve server parameters.
136
     *
137
     * Retrieves data related to the incoming request environment,
138
     * typically derived from PHP's $_SERVER superglobal. The data IS NOT
139
     * REQUIRED to originate from $_SERVER.
140
     *
141
     * @return array
142
     */
143
    public function getServerParams()
144
    {
145
        return $this->serverParams;
146
    }
147
148
    //--------------------------------------------------------------------
149
150
    /**
151
     * ServerRequest::getCookieParams
152
     *
153
     * Retrieve cookies.
154
     *
155
     * Retrieves cookies sent by the client to the server.
156
     *
157
     * The data MUST be compatible with the structure of the $_COOKIE
158
     * superglobal.
159
     *
160
     * @return array
161
     */
162
    public function getCookieParams()
163
    {
164
        return $this->cookieParams;
165
    }
166
167
    //--------------------------------------------------------------------
168
169
    /**
170
     * ServerRequest::withCookieParams
171
     *
172
     * Return an instance with the specified cookies.
173
     *
174
     * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
175
     * be compatible with the structure of $_COOKIE. Typically, this data will
176
     * be injected at instantiation.
177
     *
178
     * This method MUST NOT update the related Cookie header of the request
179
     * instance, nor related values in the server params.
180
     *
181
     * This method MUST be implemented in such a way as to retain the
182
     * immutability of the message, and MUST return an instance that has the
183
     * updated cookie values.
184
     *
185
     * @param array $cookies Array of key/value pairs representing cookies.
186
     *
187
     * @return static
188
     */
189
    public function withCookieParams(array $cookies)
190
    {
191
        $message = clone $this;
192
193
        foreach ($cookies as $key => $value) {
194
            $message->cookieParams[ $key ] = $value;
195
        }
196
197
        return $message;
198
    }
199
200
    //--------------------------------------------------------------------
201
202
    /**
203
     * ServerRequest::getQueryParams
204
     *
205
     * Retrieve query string arguments.
206
     *
207
     * Retrieves the deserialized query string arguments, if any.
208
     *
209
     * Note: the query params might not be in sync with the URI or server
210
     * params. If you need to ensure you are only getting the original
211
     * values, you may need to parse the query string from `getUri()->getQuery()`
212
     * or from the `QUERY_STRING` server param.
213
     *
214
     * @return array
215
     */
216
    public function getQueryParams()
217
    {
218
        return $this->queryParams;
219
    }
220
221
    //--------------------------------------------------------------------
222
223
    /**
224
     * ServerRequest::withQueryParams
225
     *
226
     * Return an instance with the specified query string arguments.
227
     *
228
     * These values SHOULD remain immutable over the course of the incoming
229
     * request. They MAY be injected during instantiation, such as from PHP's
230
     * $_GET superglobal, or MAY be derived from some other value such as the
231
     * URI. In cases where the arguments are parsed from the URI, the data
232
     * MUST be compatible with what PHP's parse_str() would return for
233
     * purposes of how duplicate query parameters are handled, and how nested
234
     * sets are handled.
235
     *
236
     * Setting query string arguments MUST NOT change the URI stored by the
237
     * request, nor the values in the server params.
238
     *
239
     * This method MUST be implemented in such a way as to retain the
240
     * immutability of the message, and MUST return an instance that has the
241
     * updated query string arguments.
242
     *
243
     * @param array $query Array of query string arguments, typically from
244
     *                     $_GET.
245
     *
246
     * @return static
247
     */
248
    public function withQueryParams(array $query)
249
    {
250
        $message = clone $this;
251
        $message->queryParams = $query;
252
        $message->uri = $this->uri->withQuery(http_build_query($query));
253
254
        return $message;
255
    }
256
257
    //--------------------------------------------------------------------
258
259
    /**
260
     * ServerRequest::getUploadedFiles
261
     *
262
     * Retrieve normalized file upload data.
263
     *
264
     * This method returns upload metadata in a normalized tree, with each leaf
265
     * an instance of Psr\Http\Message\UploadedFileInterface.
266
     *
267
     * These values MAY be prepared from $_FILES or the message body during
268
     * instantiation, or MAY be injected via withUploadedFiles().
269
     *
270
     * @return array An array tree of UploadedFileInterface instances; an empty
271
     *     array MUST be returned if no data is present.
272
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadPhpExtensionCallException
273
     */
274
    public function getUploadedFiles()
275
    {
276
        $response = [];
277
        foreach ($this->uploadedFiles as $key => $uploadedFile) {
278
            if (empty($uploadedFile[ 'name' ])) {
279
                continue;
280
            } elseif (is_numeric(key($uploadedFile))) {
281
                foreach ($uploadedFile as $index => $file) {
282
                    $response[ $key ][ $index ] = new UploadFile($file);
283
                }
284
            } else {
285
                $response[ $key ] = new UploadFile($uploadedFile);
286
            }
287
        }
288
289
        return $response;
290
    }
291
292
    // --------------------------------------------------------------------------------------
293
294
    /**
295
     * ServerRequest::withUploadedFiles
296
     *
297
     * Create a new instance with the specified uploaded files.
298
     *
299
     * This method MUST be implemented in such a way as to retain the
300
     * immutability of the message, and MUST return an instance that has the
301
     * updated body parameters.
302
     *
303
     * @param array $uploadedFiles An array tree of UploadedFileInterface instances.
304
     *
305
     * @return static
306
     * @throws \InvalidArgumentException if an invalid structure is provided.
307
     */
308
    public function withUploadedFiles(array $uploadedFiles)
309
    {
310
        $message = clone $this;
311
312
        foreach ($uploadedFiles as $uploadedFile) {
313
            if ($uploadedFile instanceof UploadedFileInterface) {
314
                $message->uploadedFiles[] = $uploadedFile;
315
            } else {
316
                throw new \InvalidArgumentException('Not Instance Of UploadedFileInterface');
317
                break;
318
            }
319
        }
320
321
        return $message;
322
    }
323
324
    //--------------------------------------------------------------------
325
326
    /**
327
     * ServerRequest::getParsedBody
328
     *
329
     * Retrieve any parameters provided in the request body.
330
     *
331
     * If the request Content-Type is either application/x-www-form-urlencoded
332
     * or multipart/form-data, and the request method is POST, this method MUST
333
     * return the contents of $_POST.
334
     *
335
     * Otherwise, this method may return any results of deserializing
336
     * the request body content; as parsing returns structured content, the
337
     * potential types MUST be arrays or objects only. A null value indicates
338
     * the absence of body content.
339
     *
340
     * @return null|array|object The deserialized body parameters, if any.
341
     *     These will typically be an array or object.
342
     */
343
    public function getParsedBody()
344
    {
345
        if (isset($this->headers[ 'Content-Type' ])) {
346
            if (in_array(
347
                strtolower($this->headers[ 'Content-Type' ]),
348
                [
349
                    'application/x-www-form-urlencoded',
350
                    'multipart/form-data',
351
                ]
352
            )) {
353
                return $_POST;
354
            }
355
        }
356
357
        return $_REQUEST;
358
    }
359
360
    //--------------------------------------------------------------------
361
362
    /**
363
     * ServerRequest::withParsedBody
364
     *
365
     * Return an instance with the specified body parameters.
366
     *
367
     * These MAY be injected during instantiation.
368
     *
369
     * If the request Content-Type is either application/x-www-form-urlencoded
370
     * or multipart/form-data, and the request method is POST, use this method
371
     * ONLY to inject the contents of $_POST.
372
     *
373
     * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
374
     * deserializing the request body content. Deserialization/parsing returns
375
     * structured data, and, as such, this method ONLY accepts arrays or objects,
376
     * or a null value if nothing was available to parse.
377
     *
378
     * As an example, if content negotiation determines that the request data
379
     * is a JSON payload, this method could be used to create a request
380
     * instance with the deserialized parameters.
381
     *
382
     * This method MUST be implemented in such a way as to retain the
383
     * immutability of the message, and MUST return an instance that has the
384
     * updated body parameters.
385
     *
386
     * @param null|array|object $data The deserialized body data. This will
387
     *                                typically be in an array or object.
388
     *
389
     * @return static
390
     * @throws \InvalidArgumentException if an unsupported argument type is
391
     *     provided.
392
     */
393
    public function withParsedBody($data)
394
    {
395
        $message = clone $this;
396
397
        if ($data instanceof StreamInterface) {
398
            $message->body = $data;
0 ignored issues
show
Documentation Bug introduced by
$data is of type O2System\Psr\Http\Message\StreamInterface, but the property $body was declared to be of type O2System\Kernel\Http\Message\Stream. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
399
        } elseif (is_string($data)) {
0 ignored issues
show
introduced by
The condition is_string($data) is always false.
Loading history...
400
            $message->body->write($data);
401
        }
402
403
        return $message;
404
    }
405
406
    //--------------------------------------------------------------------
407
408
    /**
409
     * ServerRequest::getAttributes
410
     *
411
     * Retrieve attributes derived from the request.
412
     *
413
     * The request "attributes" may be used to allow injection of any
414
     * parameters derived from the request: e.g., the results of path
415
     * match operations; the results of decrypting cookies; the results of
416
     * deserializing non-form-encoded message bodies; etc. Attributes
417
     * will be application and request specific, and CAN be mutable.
418
     *
419
     * @return mixed[] Attributes derived from the request.
420
     */
421
    public function getAttributes()
422
    {
423
        return array_keys($this->serverParams);
424
    }
425
426
    //--------------------------------------------------------------------
427
428
    /**
429
     * ServerRequest::getAttribute
430
     *
431
     * Retrieve a single derived request attribute.
432
     *
433
     * Retrieves a single derived request attribute as described in
434
     * getAttributes(). If the attribute has not been previously set, returns
435
     * the default value as provided.
436
     *
437
     * This method obviates the need for a hasAttribute() method, as it allows
438
     * specifying a default value to return if the attribute is not found.
439
     *
440
     * @see getAttributes()
441
     *
442
     * @param string $name    The attribute name.
443
     * @param mixed  $default Default value to return if the attribute does not exist.
444
     *
445
     * @return mixed
446
     */
447
    public function getAttribute($name, $default = null)
448
    {
449
        $name = str_replace('SERVER_', '', $name);
450
        $name = strtoupper($name);
451
452
        if (isset($this->serverParams[ $name ])) {
453
            return $this->serverParams[ $name ];
454
        } elseif (isset($_SERVER[ $name ])) {
455
            return $_SERVER[ $name ];
456
        }
457
458
        return $default;
459
    }
460
461
    //--------------------------------------------------------------------
462
463
    /**
464
     * ServerRequest::withAttribute
465
     *
466
     * Return an instance with the specified derived request attribute.
467
     *
468
     * This method allows setting a single derived request attribute as
469
     * described in getAttributes().
470
     *
471
     * This method MUST be implemented in such a way as to retain the
472
     * immutability of the message, and MUST return an instance that has the
473
     * updated attribute.
474
     *
475
     * @see getAttributes()
476
     *
477
     * @param string $name  The attribute name.
478
     * @param mixed  $value The value of the attribute.
479
     *
480
     * @return static
481
     */
482
    public function withAttribute($name, $value)
483
    {
484
        $name = str_replace('SERVER_', '', $name);
485
        $name = strtoupper($name);
486
487
        $message = clone $this;
488
        $message->serverParams[ $name ] = $value;
489
490
        if (empty($_SERVER[ 'SERVER_' . $name ])) {
491
            $_SERVER[ 'SERVER_' . $name ] = $value;
492
        }
493
494
        return $message;
495
    }
496
497
    //--------------------------------------------------------------------
498
499
    /**
500
     * ServerRequest::withoutAttribute
501
     *
502
     * Return an instance that removes the specified derived request attribute.
503
     *
504
     * This method allows removing a single derived request attribute as
505
     * described in getAttributes().
506
     *
507
     * This method MUST be implemented in such a way as to retain the
508
     * immutability of the message, and MUST return an instance that removes
509
     * the attribute.
510
     *
511
     * @see getAttributes()
512
     *
513
     * @param string $name The attribute name.
514
     *
515
     * @return static
516
     */
517
    public function withoutAttribute($name)
518
    {
519
        $name = str_replace('SERVER_', '', $name);
520
        $name = strtoupper($name);
521
522
        $message = clone $this;
523
524
        if (isset($this->serverParams[ $name ])) {
525
            unset($this->serverParams[ $name ]);
526
        }
527
528
        return $message;
529
    }
530
}