Completed
Push — master ( e5828a...2adef4 )
by Tobias
02:33 queued 01:22
created

ServerRequestCreator::getMethodFromEnv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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