Completed
Push — master ( 2da458...7cefcd )
by Tobias
03:02
created

ServerRequestFactory::createServerRequest()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
cc 6
eloc 14
nc 8
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nyholm\Psr7\Factory;
6
7
use Interop\Http\Factory\ServerRequestFactoryInterface;
8
use Nyholm\Psr7\ServerRequest;
9
10
/**
11
 * @author Tobias Nyholm <[email protected]>
12
 */
13
class ServerRequestFactory implements ServerRequestFactoryInterface
14
{
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function createServerRequest(array $server, $method = null, $uri = null)
1 ignored issue
show
Coding Style introduced by
createServerRequest uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
19
    {
20
        if (null === $method && isset($server['REQUEST_METHOD'])) {
21
            $method = $server['REQUEST_METHOD'];
22
        }
23
        if (null === $method) {
24
            throw new \InvalidArgumentException('Cannot determine HTTP method');
25
        }
26
        // TODO: find a MUCH better way
27
        if (null === $uri) {
28
            $SERVER = $_SERVER;
29
            $_SERVER = $server;
30
            // Until https://github.com/guzzle/psr7/pull/116 is resolved
31
            if (!isset($_SERVER['HTTPS'])) {
32
                $_SERVER['HTTPS'] = 'off';
33
            }
34
            $uri = ServerRequest::getUriFromGlobals();
35
            $_SERVER = $SERVER;
36
            unset($SERVER);
37
        }
38
39
        return new ServerRequest($method, $uri, [], null, '1.1', $server);
40
    }
41
}
42