Completed
Branch master (6f5620)
by Anton
02:08
created

RequestFactory::fromGlobals()   D

Complexity

Conditions 9
Paths 3

Size

Total Lines 42
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 9.1582

Importance

Changes 0
Metric Value
cc 9
eloc 32
nc 3
nop 5
dl 0
loc 42
ccs 21
cts 24
cp 0.875
crap 9.1582
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 713
    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 713
        $server = static::normalizeServer($server ?: $_SERVER);
37 713
        $files = static::normalizeFiles($files ?: $_FILES);
38 713
        $headers = static::marshalHeaders($server);
39 713
        $request = new ServerRequest(
40 713
            $server,
41 713
            $files,
42 713
            static::marshalUriFromServer($server, $headers),
43 713
            static::get('REQUEST_METHOD', $server, RequestMethod::GET),
44 713
            'php://input',
45 713
            $headers
46
        );
47
48 713
        $contentType = current($request->getHeader('Content-Type'));
49
50 713
        $input = file_get_contents('php://input');
51
52
        // support header like "application/json" and "application/json; charset=utf-8"
53 713
        if ($contentType !== false && stristr($contentType, Request::TYPE_JSON)) {
54
            $data = (array)json_decode($input);
55
        } else {
56 713
            switch ($request->getMethod()) {
57 713
                case RequestMethod::POST:
58
                    $data = $_POST;
59
                    break;
60
                default:
61 713
                    parse_str($input, $data);
62 713
                    break;
63
            }
64
        }
65
66
        return $request
67 713
            ->withCookieParams($cookies ?: $_COOKIE)
68 713
            ->withQueryParams($query ?: $_GET)
69 713
            ->withParsedBody($body ?: $data);
70
    }
71
}
72