Completed
Pull Request — master (#138)
by Zhukov
02:33
created

ServerRequestFactory   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 179
Duplicated Lines 0 %

Test Coverage

Coverage 43.18%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 92
dl 0
loc 179
ccs 38
cts 88
cp 0.4318
rs 9.84
c 4
b 0
f 0
wmc 32

7 Methods

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