Completed
Push — master ( aab296...4db66c )
by Tobias
02:11
created

ServerRequestCreator::fromGlobals()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 8.0155

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 15
cts 16
cp 0.9375
rs 8.4444
c 0
b 0
f 0
cc 8
nc 16
nop 0
crap 8.0155
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nyholm\Psr7Server;
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\UploadedFileInterface;
13
use Psr\Http\Message\UriFactoryInterface;
14
use Psr\Http\Message\UriInterface;
15
16
/**
17
 * @author Tobias Nyholm <[email protected]>
18
 * @author Martijn van der Ven <[email protected]>
19
 */
20
final class ServerRequestCreator implements ServerRequestCreatorInterface
21
{
22
    private $serverRequestFactory;
23
24
    private $uriFactory;
25
26
    private $uploadedFileFactory;
27
28
    private $streamFactory;
29
30 29
    public function __construct(
31
        ServerRequestFactoryInterface $serverRequestFactory,
32
        UriFactoryInterface $uriFactory,
33
        UploadedFileFactoryInterface $uploadedFileFactory,
34
        StreamFactoryInterface $streamFactory
35
    ) {
36 29
        $this->serverRequestFactory = $serverRequestFactory;
37 29
        $this->uriFactory = $uriFactory;
38 29
        $this->uploadedFileFactory = $uploadedFileFactory;
39 29
        $this->streamFactory = $streamFactory;
40 29
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 8
    public function fromGlobals(): ServerRequestInterface
46
    {
47 8
        $server = $_SERVER;
48 8
        if (false === isset($server['REQUEST_METHOD'])) {
49 1
            $server['REQUEST_METHOD'] = 'GET';
50
        }
51
52 8
        $headers = \function_exists('getallheaders') ? getallheaders() : static::getHeadersFromServer($_SERVER);
53
54 8
        $post = null;
55 8
        if ('POST' === $this->getMethodFromEnv($server)) {
56 7
            foreach ($headers as $headerName => $headerValue) {
57 6
                if ('content-type' !== \strtolower($headerName)) {
58
                    continue;
59
                }
60 6
                if (\in_array(
61 6
                    \strtolower(\trim(\explode(';', $headerValue, 2)[0])),
62 6
                    ['application/x-www-form-urlencoded', 'multipart/form-data']
63
                )) {
64 5
                    $post = $_POST;
65
66 6
                    break;
67
                }
68
            }
69
        }
70
71 8
        return $this->fromArrays($server, $headers, $_COOKIE, $_GET, $post, $_FILES, \fopen('php://input', 'r') ?: null);
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77 16
    public function fromArrays(array $server, array $headers = [], array $cookie = [], array $get = [], array $post = null, array $files = [], $body = null): ServerRequestInterface
78
    {
79 16
        $method = $this->getMethodFromEnv($server);
80 16
        $uri = $this->getUriFromEnvWithHTTP($server);
81 16
        $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';
82
83 16
        $serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
84 16
        foreach ($headers as $name => $value) {
85
            // Because PHP automatically casts array keys set with numeric strings to integers, we have to make sure
86
            // that numeric headers will not be sent along as integers, as withAddedHeader can only accept strings.
87 7
            if (\is_int($name)) {
88 1
                $name = (string) $name;
89
            }
90 7
            $serverRequest = $serverRequest->withAddedHeader($name, $value);
91
        }
92
93
        $serverRequest = $serverRequest
94 16
            ->withProtocolVersion($protocol)
95 16
            ->withCookieParams($cookie)
96 16
            ->withQueryParams($get)
97 16
            ->withParsedBody($post)
98 16
            ->withUploadedFiles($this->normalizeFiles($files));
99
100 15
        if (null === $body) {
101 6
            return $serverRequest;
102
        }
103
104 9
        if (\is_resource($body)) {
105 8
            $body = $this->streamFactory->createStreamFromResource($body);
106 1
        } elseif (\is_string($body)) {
107 1
            $body = $this->streamFactory->createStream($body);
108
        } elseif (!$body instanceof StreamInterface) {
109
            throw new \InvalidArgumentException('The $body parameter to ServerRequestCreator::fromArrays must be string, resource or StreamInterface');
110
        }
111
112 9
        return $serverRequest->withBody($body);
113
    }
114
115
    /**
116
     * Implementation from Zend\Diactoros\marshalHeadersFromSapi().
117
     */
118 10
    public static function getHeadersFromServer(array $server): array
119
    {
120 10
        $headers = [];
121 10
        foreach ($server as $key => $value) {
122
            // Apache prefixes environment variables with REDIRECT_
123
            // if they are added by rewrite rules
124 10
            if (0 === \strpos($key, 'REDIRECT_')) {
125 1
                $key = \substr($key, 9);
126
127
                // We will not overwrite existing variables with the
128
                // prefixed versions, though
129 1
                if (\array_key_exists($key, $server)) {
130 1
                    continue;
131
                }
132
            }
133
134 10
            if ($value && 0 === \strpos($key, 'HTTP_')) {
135 8
                $name = \strtr(\strtolower(\substr($key, 5)), '_', '-');
136 8
                $headers[$name] = $value;
137
138 8
                continue;
139
            }
140
141 9
            if ($value && 0 === \strpos($key, 'CONTENT_')) {
142 1
                $name = 'content-'.\strtolower(\substr($key, 8));
143 1
                $headers[$name] = $value;
144
145 9
                continue;
146
            }
147
        }
148
149 10
        return $headers;
150
    }
151
152 16
    private function getMethodFromEnv(array $environment): string
153
    {
154 16
        if (false === isset($environment['REQUEST_METHOD'])) {
155
            throw new \InvalidArgumentException('Cannot determine HTTP method');
156
        }
157
158 16
        return $environment['REQUEST_METHOD'];
159
    }
160
161 16
    private function getUriFromEnvWithHTTP(array $environment): UriInterface
162
    {
163 16
        $uri = $this->createUriFromArray($environment);
164 16
        if (empty($uri->getScheme())) {
165 15
            $uri = $uri->withScheme('http');
166
        }
167
168 16
        return $uri;
169
    }
170
171
    /**
172
     * Return an UploadedFile instance array.
173
     *
174
     * @param array $files A array which respect $_FILES structure
175
     *
176
     * @return UploadedFileInterface[]
177
     *
178
     * @throws \InvalidArgumentException for unrecognized values
179
     */
180 16
    private function normalizeFiles(array $files): array
181
    {
182 16
        $normalized = [];
183
184 16
        foreach ($files as $key => $value) {
185 7
            if ($value instanceof UploadedFileInterface) {
186 2
                $normalized[$key] = $value;
187 6
            } elseif (\is_array($value) && isset($value['tmp_name'])) {
188 4
                $normalized[$key] = $this->createUploadedFileFromSpec($value);
189 2
            } elseif (\is_array($value)) {
190 1
                $normalized[$key] = $this->normalizeFiles($value);
191
            } else {
192 7
                throw new \InvalidArgumentException('Invalid value in files specification');
193
            }
194
        }
195
196 15
        return $normalized;
197
    }
198
199
    /**
200
     * Create and return an UploadedFile instance from a $_FILES specification.
201
     *
202
     * If the specification represents an array of values, this method will
203
     * delegate to normalizeNestedFileSpec() and return that return value.
204
     *
205
     * @param array $value $_FILES struct
206
     *
207
     * @return array|UploadedFileInterface
208
     */
209 5
    private function createUploadedFileFromSpec(array $value)
210
    {
211 5
        if (\is_array($value['tmp_name'])) {
212 1
            return $this->normalizeNestedFileSpec($value);
213
        }
214
215
        try {
216 5
            $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
217 1
        } catch (\RuntimeException $e) {
218 1
            $stream = $this->streamFactory->createStream();
219
        }
220
221 5
        return $this->uploadedFileFactory->createUploadedFile(
222 5
            $stream,
223 5
            (int) $value['size'],
224 5
            (int) $value['error'],
225 5
            $value['name'],
226 5
            $value['type']
227
        );
228
    }
229
230
    /**
231
     * Normalize an array of file specifications.
232
     *
233
     * Loops through all nested files and returns a normalized array of
234
     * UploadedFileInterface instances.
235
     *
236
     * @return UploadedFileInterface[]
237
     */
238 1
    private function normalizeNestedFileSpec(array $files = []): array
239
    {
240 1
        $normalizedFiles = [];
241
242 1
        foreach (\array_keys($files['tmp_name']) as $key) {
243
            $spec = [
244 1
                'tmp_name' => $files['tmp_name'][$key],
245 1
                'size' => $files['size'][$key],
246 1
                'error' => $files['error'][$key],
247 1
                'name' => $files['name'][$key],
248 1
                'type' => $files['type'][$key],
249
            ];
250 1
            $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
251
        }
252
253 1
        return $normalizedFiles;
254
    }
255
256
    /**
257
     * Create a new uri from server variable.
258
     *
259
     * @param array $server typically $_SERVER or similar structure
260
     */
261 26
    private function createUriFromArray(array $server): UriInterface
262
    {
263 26
        $uri = $this->uriFactory->createUri('');
264
265 26
        if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
266 1
            $uri = $uri->withScheme($server['HTTP_X_FORWARDED_PROTO']);
267
        } else {
268 25
            if (isset($server['REQUEST_SCHEME'])) {
269
                $uri = $uri->withScheme($server['REQUEST_SCHEME']);
270 25
            } elseif (isset($server['HTTPS'])) {
271 9
                $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
272
            }
273
274 25
            if (isset($server['SERVER_PORT'])) {
275 9
                $uri = $uri->withPort($server['SERVER_PORT']);
276
            }
277
        }
278
279 26
        if (isset($server['HTTP_HOST'])) {
280 9
            if (1 === \preg_match('/^(.+)\:(\d+)$/', $server['HTTP_HOST'], $matches)) {
281 3
                $uri = $uri->withHost($matches[1])->withPort($matches[2]);
282
            } else {
283 9
                $uri = $uri->withHost($server['HTTP_HOST']);
284
            }
285 17
        } elseif (isset($server['SERVER_NAME'])) {
286 1
            $uri = $uri->withHost($server['SERVER_NAME']);
287
        }
288
289 26
        if (isset($server['REQUEST_URI'])) {
290 10
            $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
291
        }
292
293 26
        if (isset($server['QUERY_STRING'])) {
294 10
            $uri = $uri->withQuery($server['QUERY_STRING']);
295
        }
296
297 26
        return $uri;
298
    }
299
}
300