Completed
Pull Request — master (#439)
by Anton
27:34
created

RequestFactory::fromGlobals()   D

Complexity

Conditions 9
Paths 3

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 9.0698

Importance

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