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