-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
ServerRequestFactory.php
310 lines (266 loc) · 9.58 KB
/
ServerRequestFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
declare(strict_types=1);
namespace Laminas\Diactoros;
use Laminas\Diactoros\ServerRequestFilter\FilterServerRequestInterface;
use Laminas\Diactoros\ServerRequestFilter\FilterUsingXForwardedHeaders;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use function array_key_exists;
use function is_callable;
/**
* Class for marshaling a request object from the current PHP environment.
*
* Logic largely refactored from the Laminas Laminas\Http\PhpEnvironment\Request class.
*
* @copyright Copyright (c) 2005-2015 Laminas (https://www.zend.com)
* @license https://getlaminas.org/license/new-bsd New BSD License
*/
class ServerRequestFactory implements ServerRequestFactoryInterface
{
/**
* Function to use to get apache request headers; present only to simplify mocking.
*
* @var callable
*/
private static $apacheRequestHeaders = 'apache_request_headers';
/**
* Create a request from the supplied superglobal values.
*
* If any argument is not supplied, the corresponding superglobal value will
* be used.
*
* The ServerRequest created is then passed to the fromServer() method in
* order to marshal the request URI and headers.
*
* @see fromServer()
* @param array $server $_SERVER superglobal
* @param array $query $_GET superglobal
* @param array $body $_POST superglobal
* @param array $cookies $_COOKIE superglobal
* @param array $files $_FILES superglobal
* @param null|FilterServerRequestInterface $requestFilter If present, the
* generated request will be passed to this instance and the result
* returned by this method. When not present, a default instance of
* FilterUsingXForwardedHeaders is created, using the `trustReservedSubnets()`
* constructor.
* @return ServerRequest
*/
public static function fromGlobals(
array $server = null,
array $query = null,
array $body = null,
array $cookies = null,
array $files = null,
?FilterServerRequestInterface $requestFilter = null
) : ServerRequest {
$requestFilter = $requestFilter ?: FilterUsingXForwardedHeaders::trustReservedSubnets();
$server = normalizeServer(
$server ?: $_SERVER,
is_callable(self::$apacheRequestHeaders) ? self::$apacheRequestHeaders : null
);
$files = normalizeUploadedFiles($files ?: $_FILES);
$headers = marshalHeadersFromSapi($server);
if (null === $cookies && array_key_exists('cookie', $headers)) {
$cookies = parseCookieHeader($headers['cookie']);
}
return $requestFilter(new ServerRequest(
$server,
$files,
self::marshalUriFromSapi($server, $headers),
marshalMethodFromSapi($server),
'php://input',
$headers,
$cookies ?: $_COOKIE,
$query ?: $_GET,
$body ?: $_POST,
marshalProtocolVersionFromSapi($server)
));
}
/**
* {@inheritDoc}
*/
public function createServerRequest(string $method, $uri, array $serverParams = []) : ServerRequestInterface
{
$uploadedFiles = [];
return new ServerRequest(
$serverParams,
$uploadedFiles,
$uri,
$method,
'php://temp'
);
}
/**
* Marshal a Uri instance based on the values present in the $_SERVER array and headers.
*
* @param array<string, string|list<string>> $headers
* @param array $server SAPI parameters
*/
private static function marshalUriFromSapi(array $server, array $headers) : Uri
{
$uri = new Uri('');
// URI scheme
$https = false;
if (array_key_exists('HTTPS', $server)) {
$https = self::marshalHttpsValue($server['HTTPS']);
} elseif (array_key_exists('https', $server)) {
$https = self::marshalHttpsValue($server['https']);
}
$uri = $uri->withScheme($https ? 'https' : 'http');
// Set the host
[$host, $port] = self::marshalHostAndPort($server, $headers);
if (! empty($host)) {
$uri = $uri->withHost($host);
if (! empty($port)) {
$uri = $uri->withPort($port);
}
}
// URI path
$path = self::marshalRequestPath($server);
// Strip query string
$path = explode('?', $path, 2)[0];
// URI query
$query = '';
if (isset($server['QUERY_STRING'])) {
$query = ltrim((string) $server['QUERY_STRING'], '?');
}
// URI fragment
$fragment = '';
if (strpos($path, '#') !== false) {
[$path, $fragment] = explode('#', $path, 2);
}
return $uri
->withPath($path)
->withFragment($fragment)
->withQuery($query);
}
/**
* Marshal the host and port from the PHP environment.
*
* @param array<string, string|list<string>> $headers
* @return array{string, int|null} Array of two items, host and port,
* in that order (can be passed to a list() operation).
*/
private static function marshalHostAndPort(array $server, array $headers) : array
{
static $defaults = ['', null];
$host = self::getHeaderFromArray('host', $headers, false);
if ($host !== false) {
return self::marshalHostAndPortFromHeader($host);
}
if (! isset($server['SERVER_NAME'])) {
return $defaults;
}
$host = (string) $server['SERVER_NAME'];
$port = isset($server['SERVER_PORT']) ? (int) $server['SERVER_PORT'] : null;
if (! isset($server['SERVER_ADDR'])
|| ! preg_match('/^\[[0-9a-fA-F\:]+\]$/', $host)
) {
return [$host, $port];
}
// Misinterpreted IPv6-Address
// Reported for Safari on Windows
return self::marshalIpv6HostAndPort($server, $port);
}
/**
* @return array{string, int|null} Array of two items, host and port,
* in that order (can be passed to a list() operation).
*/
private static function marshalIpv6HostAndPort(array $server, ?int $port) : array
{
$host = '[' . (string) $server['SERVER_ADDR'] . ']';
$port = $port ?: 80;
$portSeparatorPos = strrpos($host, ':');
if (false === $portSeparatorPos) {
return [$host, $port];
}
if ($port . ']' === substr($host, $portSeparatorPos + 1)) {
// The last digit of the IPv6-Address has been taken as port
// Unset the port so the default port can be used
$port = null;
}
return [$host, $port];
}
/**
* Detect the path for the request
*
* Looks at a variety of criteria in order to attempt to autodetect the base
* request path, including:
*
* - IIS7 UrlRewrite environment
* - REQUEST_URI
* - ORIG_PATH_INFO
*/
private static function marshalRequestPath(array $server) : string
{
// IIS7 with URL Rewrite: make sure we get the unencoded url
// (double slash problem).
$iisUrlRewritten = $server['IIS_WasUrlRewritten'] ?? null;
$unencodedUrl = $server['UNENCODED_URL'] ?? '';
if ('1' === $iisUrlRewritten && is_string($unencodedUrl) && '' !== $unencodedUrl) {
return $unencodedUrl;
}
$requestUri = $server['REQUEST_URI'] ?? null;
if (is_string($requestUri)) {
return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
}
$origPathInfo = $server['ORIG_PATH_INFO'] ?? '';
if (! is_string($origPathInfo) || '' === $origPathInfo) {
return '/';
}
return $origPathInfo;
}
/**
* @param mixed $https
*/
private static function marshalHttpsValue($https) : bool
{
if (is_bool($https)) {
return $https;
}
if (! is_string($https)) {
throw new Exception\InvalidArgumentException(sprintf(
'SAPI HTTPS value MUST be a string or boolean; received %s',
gettype($https)
));
}
return 'on' === strtolower($https);
}
/**
* @param string|list<string> $host
* @return array Array of two items, host and port, in that order (can be
* passed to a list() operation).
*/
private static function marshalHostAndPortFromHeader($host): array
{
if (is_array($host)) {
$host = implode(', ', $host);
}
$port = null;
// works for regname, IPv4 & IPv6
if (preg_match('|\:(\d+)$|', $host, $matches)) {
$host = substr($host, 0, -1 * (strlen($matches[1]) + 1));
$port = (int) $matches[1];
}
return [$host, $port];
}
/**
* Retrieve a header value from an array of headers using a case-insensitive lookup.
*
* @param array<string, string|list<string>> $headers Key/value header pairs
* @param mixed $default Default value to return if header not found
* @return mixed
*/
private static function getHeaderFromArray(string $name, array $headers, $default = null)
{
$header = strtolower($name);
$headers = array_change_key_case($headers, CASE_LOWER);
if (! array_key_exists($header, $headers)) {
return $default;
}
if (is_string($headers[$header])) {
return $headers[$header];
}
return implode(', ', $headers[$header]);
}
}