Completed
Pull Request — master (#438)
by Anton
06:33
created

RequestFactory::fromGlobals()   D

Complexity

Conditions 9
Paths 3

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 9.111

Importance

Changes 0
Metric Value
cc 9
eloc 28
nc 3
nop 5
dl 0
loc 37
ccs 16
cts 18
cp 0.8889
crap 9.111
rs 4.909
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\Request;
12
13
use Bluz\Http\RequestMethod;
14
use Bluz\Proxy\Request;
15
use Zend\Diactoros\ServerRequest;
16
use Zend\Diactoros\ServerRequestFactory;
17
18
/**
19
 * Request Factory
20
 *
21
 * @package  Bluz\Request
22
 * @author   Anton Shevchuk
23
 */
24
class RequestFactory extends ServerRequestFactory
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29 557
    public static function fromGlobals(
30
        array $server = null,
31
        array $query = null,
32
        array $body = null,
33
        array $cookies = null,
34
        array $files = null
35
    ) {
36 557
        $server = static::normalizeServer($server ?: $_SERVER);
37 557
        $files = static::normalizeFiles($files ?: $_FILES);
38 557
        $headers = static::marshalHeaders($server);
39 557
        $request = new ServerRequest(
40
            $server,
41
            $files,
42 557
            static::marshalUriFromServer($server, $headers),
43 557
            static::get('REQUEST_METHOD', $server, RequestMethod::GET),
44 557
            'php://input',
45
            $headers
46
        );
47
48 557
        $contentType = current($request->getHeader('Content-Type'));
49
50 557
        $input = file_get_contents('php://input');
51
52
        // support header like "application/json" and "application/json; charset=utf-8"
53 557
        if (false !== $contentType && false !== stripos($contentType, Request::TYPE_JSON)) {
54
            $data = (array) json_decode($input);
55 557
        } elseif ($request->getMethod() === RequestMethod::POST) {
56
            $data = $_POST;
57
        } else {
58 557
            parse_str($input, $data);
59
        }
60
61
        return $request
62 557
            ->withCookieParams($cookies ?: $_COOKIE)
63 557
            ->withQueryParams($query ?: $_GET)
64 557
            ->withParsedBody($body ?: $data);
65
    }
66
}
67