Passed
Pull Request — master (#336)
by Wilmer
02:46
created

ServerRequestFactory::createFromParameters()   B

Complexity

Conditions 9
Paths 21

Size

Total Lines 40
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 9.3317

Importance

Changes 0
Metric Value
cc 9
eloc 25
c 0
b 0
f 0
nc 21
nop 7
dl 0
loc 40
ccs 21
cts 25
cp 0.84
crap 9.3317
rs 8.0555
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web;
6
7
use Psr\Http\Message\ServerRequestFactoryInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Message\StreamFactoryInterface;
10
use Psr\Http\Message\StreamInterface;
11
use Psr\Http\Message\UploadedFileFactoryInterface;
12
use Psr\Http\Message\UriFactoryInterface;
13
use Psr\Http\Message\UriInterface;
14
15
final class ServerRequestFactory
16
{
17
    private ServerRequestFactoryInterface $serverRequestFactory;
18
    private UriFactoryInterface $uriFactory;
19
    private UploadedFileFactoryInterface $uploadedFileFactory;
20
    private StreamFactoryInterface $streamFactory;
21
22 34
    public function __construct(
23
        ServerRequestFactoryInterface $serverRequestFactory,
24
        UriFactoryInterface $uriFactory,
25
        UploadedFileFactoryInterface $uploadedFileFactory,
26
        StreamFactoryInterface $streamFactory
27
    ) {
28 34
        $this->serverRequestFactory = $serverRequestFactory;
29 34
        $this->uriFactory = $uriFactory;
30 34
        $this->uploadedFileFactory = $uploadedFileFactory;
31 34
        $this->streamFactory = $streamFactory;
32 34
    }
33
34 17
    public function createFromGlobals(): ServerRequestInterface
35
    {
36 17
        return $this->createFromParameters(
37
            $_SERVER,
38 17
            $this->getHeadersFromGlobals(),
39
            $_COOKIE,
40
            $_GET,
41
            $_POST,
42
            $_FILES,
43 17
            \fopen('php://input', 'rb') ?: null
44
        );
45
    }
46
47
    /**
48
     * @param array $server
49
     * @param array $headers
50
     * @param array $cookies
51
     * @param array $get
52
     * @param array $post
53
     * @param array $files
54
     * @param StreamInterface|resource|string|null $body
55
     * @return ServerRequestInterface
56
     */
57 34
    public function createFromParameters(array $server, array $headers = [], array $cookies = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
58
    {
59 34
        $method = $server['REQUEST_METHOD'] ?? null;
60 34
        if ($method === null) {
61 1
            throw new \RuntimeException('Unable to determine HTTP request method.');
62
        }
63
64 33
        $uri = $this->getUri($server);
65
66 33
        $request = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
67
68 33
        foreach ($headers as $name => $value) {
69 8
            $request = $request->withAddedHeader($name, $value);
70
        }
71
72 33
        $protocol = '1.1';
73 33
        if (array_key_exists('SERVER_PROTOCOL', $server) && $server['SERVER_PROTOCOL'] !== '') {
74 2
            $protocol = str_replace('HTTP/', '', $server['SERVER_PROTOCOL']);
75
        }
76
77
        $request = $request
78 33
            ->withProtocolVersion($protocol)
79 33
            ->withQueryParams($get)
80 33
            ->withParsedBody($post)
81 33
            ->withCookieParams($cookies)
82 33
            ->withUploadedFiles($this->getUploadedFilesArray($files));
83
84 33
        if ($body === null) {
85 16
            return $request;
86
        }
87
88 17
        if (\is_resource($body)) {
89 17
            $body = $this->streamFactory->createStreamFromResource($body);
90
        } elseif (\is_string($body)) {
91
            $body = $this->streamFactory->createStream($body);
92
        } elseif (!$body instanceof StreamInterface) {
0 ignored issues
show
introduced by
$body is always a sub-type of Psr\Http\Message\StreamInterface.
Loading history...
93
            throw new \InvalidArgumentException('Body parameter for ServerRequestFactory::createFromParameters() must be instance of StreamInterface, resource or null.');
94
        }
95
96 17
        return $request->withBody($body);
97
    }
98
99 33
    private function getUri(array $server): UriInterface
100
    {
101 33
        $uri = $this->uriFactory->createUri();
102
103 33
        if (array_key_exists('HTTPS', $server) && $server['HTTPS'] !== '' && $server['HTTPS'] !== 'off') {
104 4
            $uri = $uri->withScheme('https');
105
        } else {
106 29
            $uri = $uri->withScheme('http');
107
        }
108
109 33
        if (isset($server['HTTP_HOST'])) {
110 15
            if (1 === \preg_match('/^(.+):(\d+)$/', $server['HTTP_HOST'], $matches)) {
111 6
                $uri = $uri->withHost($matches[1])->withPort($matches[2]);
112
            } else {
113 15
                $uri = $uri->withHost($server['HTTP_HOST']);
114
            }
115 18
        } elseif (isset($server['SERVER_NAME'])) {
116 2
            $uri = $uri->withHost($server['SERVER_NAME']);
117
        }
118
119 33
        if (isset($server['SERVER_PORT'])) {
120 2
            $uri = $uri->withPort($server['SERVER_PORT']);
121
        }
122
123 33
        if (isset($server['REQUEST_URI'])) {
124 2
            $uri = $uri->withPath(\explode('?', $server['REQUEST_URI'])[0]);
125
        }
126
127 33
        if (isset($server['QUERY_STRING'])) {
128 2
            $uri = $uri->withQuery($server['QUERY_STRING']);
129
        }
130
131 33
        return $uri;
132
    }
133
134
    /**
135
     * @suppress PhanUndeclaredFunction
136
     */
137 17
    private function getHeadersFromGlobals(): array
138
    {
139 17
        if (\function_exists('\getallheaders')) {
140
            $headers = \getallheaders();
141
            if ($headers === false) {
142
                $headers = [];
143
            }
144
        } else {
145 17
            $headers = [];
146 17
            foreach ($_SERVER as $name => $value) {
147 17
                if (strncmp($name, 'HTTP_', 5) === 0) {
148 8
                    $name = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($name, 5))));
149 8
                    $headers[$name] = $value;
150
                }
151
            }
152
        }
153
154 17
        return $headers;
155
    }
156
157 33
    private function getUploadedFilesArray(array $filesArray): array
158
    {
159
        // TODO: simplify?
160 33
        $files = [];
161 33
        foreach ($filesArray as $class => $info) {
162 17
            $files[$class] = [];
163 17
            $this->populateUploadedFileRecursive($files[$class], $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
164
        }
165 33
        return $files;
166
    }
167
168
    /**
169
     * Populates uploaded files array from $_FILE data structure recursively.
170
     * @param array $files uploaded files array to be populated.
171
     * @param mixed $names file names provided by PHP
172
     * @param mixed $tempNames temporary file names provided by PHP
173
     * @param mixed $types file types provided by PHP
174
     * @param mixed $sizes file sizes provided by PHP
175
     * @param mixed $errors uploading issues provided by PHP
176
     */
177 17
    private function populateUploadedFileRecursive(array &$files, $names, $tempNames, $types, $sizes, $errors): void
178
    {
179 17
        if (\is_array($names)) {
180 17
            foreach ($names as $i => $name) {
181 17
                $files[$i] = [];
182 17
                $this->populateUploadedFileRecursive($files[$i], $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
183
            }
184
        } else {
185
            try {
186 17
                $stream = $this->streamFactory->createStreamFromFile($tempNames);
187 17
            } catch (\RuntimeException $e) {
188 17
                $stream = $this->streamFactory->createStream();
189
            }
190
191 17
            $files = $this->uploadedFileFactory->createUploadedFile(
192 17
                $stream,
193 17
                (int)$sizes,
194 17
                (int)$errors,
195
                $names,
196
                $types
197
            );
198
        }
199 17
    }
200
}
201