Completed
Push — master ( 33aa7c...5c2434 )
by Tobias
13:05 queued 03:15
created

ServerRequestCreator   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 284
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 95.97%

Importance

Changes 0
Metric Value
wmc 53
lcom 1
cbo 6
dl 0
loc 284
ccs 119
cts 124
cp 0.9597
rs 6.96
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
B fromArrays() 0 37 8
B getHeadersFromServer() 0 33 8
A getMethodFromEnv() 0 8 2
A getUriFromEnvWithHTTP() 0 9 2
A normalizeFiles() 0 18 6
A createUploadedFileFromSpec() 0 24 4
A normalizeNestedFileSpec() 0 17 2
B createUriFromArray() 0 38 11
B fromGlobals() 0 28 9

How to fix   Complexity   

Complex Class

Complex classes like ServerRequestCreator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ServerRequestCreator, and based on these observations, apply Extract Interface, too.

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 (true === \is_int($headerName) || '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 Laminas\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
        if (UPLOAD_ERR_OK !== $value['error']) {
216 5
            $stream = $this->streamFactory->createStream();
217 1
        } else {
218 1
            try {
219
                $stream = $this->streamFactory->createStreamFromFile($value['tmp_name']);
220
            } catch (\RuntimeException $e) {
221 5
                $stream = $this->streamFactory->createStream();
222 5
            }
223 5
        }
224 5
225 5
        return $this->uploadedFileFactory->createUploadedFile(
226 5
            $stream,
227
            (int) $value['size'],
228
            (int) $value['error'],
229
            $value['name'],
230
            $value['type']
231
        );
232
    }
233
234
    /**
235
     * Normalize an array of file specifications.
236
     *
237
     * Loops through all nested files and returns a normalized array of
238 1
     * UploadedFileInterface instances.
239
     *
240 1
     * @return UploadedFileInterface[]
241
     */
242 1
    private function normalizeNestedFileSpec(array $files = []): array
243
    {
244 1
        $normalizedFiles = [];
245 1
246 1
        foreach (\array_keys($files['tmp_name']) as $key) {
247 1
            $spec = [
248 1
                'tmp_name' => $files['tmp_name'][$key],
249
                'size' => $files['size'][$key],
250 1
                'error' => $files['error'][$key],
251
                'name' => $files['name'][$key],
252
                'type' => $files['type'][$key],
253 1
            ];
254
            $normalizedFiles[$key] = $this->createUploadedFileFromSpec($spec);
255
        }
256
257
        return $normalizedFiles;
258
    }
259
260
    /**
261 26
     * Create a new uri from server variable.
262
     *
263 26
     * @param array $server typically $_SERVER or similar structure
264
     */
265 26
    private function createUriFromArray(array $server): UriInterface
266 1
    {
267
        $uri = $this->uriFactory->createUri('');
268 25
269
        if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
270 25
            $uri = $uri->withScheme($server['HTTP_X_FORWARDED_PROTO']);
271 9
        } else {
272
            if (isset($server['REQUEST_SCHEME'])) {
273
                $uri = $uri->withScheme($server['REQUEST_SCHEME']);
274 25
            } elseif (isset($server['HTTPS'])) {
275 9
                $uri = $uri->withScheme('on' === $server['HTTPS'] ? 'https' : 'http');
276
            }
277
278
            if (isset($server['SERVER_PORT'])) {
279 26
                $uri = $uri->withPort($server['SERVER_PORT']);
280 9
            }
281 3
        }
282
283 9
        if (isset($server['HTTP_HOST'])) {
284
            if (1 === \preg_match('/^(.+)\:(\d+)$/', $server['HTTP_HOST'], $matches)) {
285 17
                $uri = $uri->withHost($matches[1])->withPort($matches[2]);
286 1
            } else {
287
                $uri = $uri->withHost($server['HTTP_HOST']);
288
            }
289 26
        } elseif (isset($server['SERVER_NAME'])) {
290 10
            $uri = $uri->withHost($server['SERVER_NAME']);
291
        }
292
293 26
        if (isset($server['REQUEST_URI'])) {
294 10
            $uri = $uri->withPath(\current(\explode('?', $server['REQUEST_URI'])));
295
        }
296
297 26
        if (isset($server['QUERY_STRING'])) {
298
            $uri = $uri->withQuery($server['QUERY_STRING']);
299
        }
300
301
        return $uri;
302
    }
303
}
304