Completed
Push — master ( fcdf89...4a0ecc )
by Alexander
14:58
created

src/ServerRequestFactory.php (1 issue)

Severity
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
21
    public function __construct(
22
        ServerRequestFactoryInterface $serverRequestFactory,
23
        UriFactoryInterface $uriFactory,
24
        UploadedFileFactoryInterface $uploadedFileFactory,
25
        StreamFactoryInterface $streamFactory
26
    ) {
27
        $this->serverRequestFactory = $serverRequestFactory;
28
        $this->uriFactory = $uriFactory;
29
        $this->uploadedFileFactory = $uploadedFileFactory;
30
        $this->streamFactory = $streamFactory;
31
    }
32
33
    public function createFromGlobals(): ServerRequestInterface
34
    {
35
        return $this->createFromParameters(
36
            $_SERVER,
37
            self::getHeadersFromGlobals(),
38
            $_COOKIE,
39
            $_GET,
40
            $_POST,
41
            $_FILES,
42
            \fopen('php://input', 'r') ?: null
43
        );
44
    }
45
46
    /**
47
     * @param array $server
48
     * @param array $headers
49
     * @param array $cookies
50
     * @param array $get
51
     * @param array $post
52
     * @param array $files
53
     * @param StreamInterface|resource|string|null $body
54
     * @return ServerRequestInterface
55
     */
56
    public function createFromParameters(array $server, array $headers = [], array $cookies = [], array $get = [], array $post = [], array $files = [], $body = null): ServerRequestInterface
57
    {
58
        $method = $server['REQUEST_METHOD'] ?? null;
59
        if ($method === null) {
60
            throw new \RuntimeException('Unable to determine HTTP request method.');
61
        }
62
63
        $uri = $this->getUri($server);
64
65
        $request = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
66
67
        foreach ($headers as $name => $value) {
68
            $request = $request->withAddedHeader($name, $value);
69
        }
70
71
        $protocol = '1.1';
72
        if (!empty($_SERVER['SERVER_PROTOCOL'])) {
73
            $protocol = str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']);
74
        }
75
76
        $request = $request
77
            ->withProtocolVersion($protocol)
78
            ->withQueryParams($get)
79
            ->withParsedBody($post)
80
            ->withCookieParams($cookies)
81
            ->withUploadedFiles($this->getUploadedFilesArray($files));
82
83
        if ($body === null) {
84
            return $request;
85
        }
86
87
        if (\is_resource($body)) {
88
            $body = $this->streamFactory->createStreamFromResource($body);
89
        } elseif (\is_string($body)) {
90
            $body = $this->streamFactory->createStream($body);
91
        } elseif (!$body instanceof StreamInterface) {
0 ignored issues
show
$body is always a sub-type of Psr\Http\Message\StreamInterface.
Loading history...
92
            throw new \InvalidArgumentException('Body parameter for ServerRequestFactory::createFromParameters() must be instance of StreamInterface, resource or null.');
93
        }
94
95
96
        return $request->withBody($body);
97
    }
98
99
    private function getUri(array $server): UriInterface
100
    {
101
        $uri = $this->uriFactory->createUri();
102
103
        if (isset($server['HTTPS'])) {
104
            $uri = $uri->withScheme($server['HTTPS'] === 'on' ? 'https' : 'http');
105
        }
106
107
        if (isset($server['HTTP_HOST'])) {
108
            if (1 === \preg_match('/^(.+)\:(\d+)$/', $server['HTTP_HOST'], $matches)) {
109
                $uri = $uri->withHost($matches[1])->withPort($matches[2]);
110
            } else {
111
                $uri = $uri->withHost($server['HTTP_HOST']);
112
            }
113
        } elseif (isset($server['SERVER_NAME'])) {
114
            $uri = $uri->withHost($server['SERVER_NAME']);
115
        }
116
117
        if (isset($server['SERVER_PORT'])) {
118
            $uri = $uri->withPort($server['SERVER_PORT']);
119
        }
120
121
        if (isset($server['REQUEST_URI'])) {
122
            $uri = $uri->withPath(\explode('?', $server['REQUEST_URI'])[0]);
123
        }
124
125
        if (isset($server['QUERY_STRING'])) {
126
            $uri = $uri->withQuery($server['QUERY_STRING']);
127
        }
128
129
        return $uri;
130
    }
131
132
    private static 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(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
144
                    $headers[$name] = $value;
145
                }
146
            }
147
        }
148
149
        return $headers;
150
    }
151
152
    private function getUploadedFilesArray(array $filesArray): array
153
    {
154
        // TODO: simplify?
155
        $files = [];
156
        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
        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(&$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