3 * @see https://github.com/zendframework/zend-diactoros for the canonical source repository
4 * @copyright Copyright (c) 2015-2017 Zend Technologies USA Inc. (http://www.zend.com)
5 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
8 namespace Zend\Diactoros;
10 use InvalidArgumentException;
11 use Psr\Http\Message\UploadedFileInterface;
13 use UnexpectedValueException;
16 * Class for marshaling a request object from the current PHP environment.
18 * Logic largely refactored from the ZF2 Zend\Http\PhpEnvironment\Request class.
20 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
21 * @license http://framework.zend.com/license/new-bsd New BSD License
23 abstract class ServerRequestFactory
26 * Function to use to get apache request headers; present only to simplify mocking.
30 private static $apacheRequestHeaders = 'apache_request_headers';
33 * Create a request from the supplied superglobal values.
35 * If any argument is not supplied, the corresponding superglobal value will
38 * The ServerRequest created is then passed to the fromServer() method in
39 * order to marshal the request URI and headers.
42 * @param array $server $_SERVER superglobal
43 * @param array $query $_GET superglobal
44 * @param array $body $_POST superglobal
45 * @param array $cookies $_COOKIE superglobal
46 * @param array $files $_FILES superglobal
47 * @return ServerRequest
48 * @throws InvalidArgumentException for invalid file values
50 public static function fromGlobals(
54 array $cookies = null,
57 $server = static::normalizeServer($server ?: $_SERVER);
58 $files = static::normalizeFiles($files ?: $_FILES);
59 $headers = static::marshalHeaders($server);
61 if (null === $cookies && array_key_exists('cookie', $headers)) {
62 $cookies = self::parseCookieHeader($headers['cookie']);
65 return new ServerRequest(
68 static::marshalUriFromServer($server, $headers),
69 static::get('REQUEST_METHOD', $server, 'GET'),
75 static::marshalProtocolVersion($server)
80 * Access a value in an array, returning a default value if not found
82 * Will also do a case-insensitive search if a case sensitive search fails.
85 * @param array $values
86 * @param mixed $default
89 public static function get($key, array $values, $default = null)
91 if (array_key_exists($key, $values)) {
99 * Search for a header value.
101 * Does a case-insensitive search for a matching header.
103 * If found, it is returned as a string, using comma concatenation.
105 * If not, the $default is returned.
107 * @param string $header
108 * @param array $headers
109 * @param mixed $default
112 public static function getHeader($header, array $headers, $default = null)
114 $header = strtolower($header);
115 $headers = array_change_key_case($headers, CASE_LOWER);
116 if (array_key_exists($header, $headers)) {
117 $value = is_array($headers[$header]) ? implode(', ', $headers[$header]) : $headers[$header];
125 * Marshal the $_SERVER array
127 * Pre-processes and returns the $_SERVER superglobal.
129 * @param array $server
132 public static function normalizeServer(array $server)
134 // This seems to be the only way to get the Authorization header on Apache
135 $apacheRequestHeaders = self::$apacheRequestHeaders;
136 if (isset($server['HTTP_AUTHORIZATION'])
137 || ! is_callable($apacheRequestHeaders)
142 $apacheRequestHeaders = $apacheRequestHeaders();
143 if (isset($apacheRequestHeaders['Authorization'])) {
144 $server['HTTP_AUTHORIZATION'] = $apacheRequestHeaders['Authorization'];
148 if (isset($apacheRequestHeaders['authorization'])) {
149 $server['HTTP_AUTHORIZATION'] = $apacheRequestHeaders['authorization'];
157 * Normalize uploaded files
159 * Transforms each value into an UploadedFileInterface instance, and ensures
160 * that nested arrays are normalized.
162 * @param array $files
164 * @throws InvalidArgumentException for unrecognized values
166 public static function normalizeFiles(array $files)
169 foreach ($files as $key => $value) {
170 if ($value instanceof UploadedFileInterface) {
171 $normalized[$key] = $value;
175 if (is_array($value) && isset($value['tmp_name'])) {
176 $normalized[$key] = self::createUploadedFileFromSpec($value);
180 if (is_array($value)) {
181 $normalized[$key] = self::normalizeFiles($value);
185 throw new InvalidArgumentException('Invalid value in files specification');
191 * Marshal headers from $_SERVER
193 * @param array $server
196 public static function marshalHeaders(array $server)
199 foreach ($server as $key => $value) {
200 // Apache prefixes environment variables with REDIRECT_
201 // if they are added by rewrite rules
202 if (strpos($key, 'REDIRECT_') === 0) {
203 $key = substr($key, 9);
205 // We will not overwrite existing variables with the
206 // prefixed versions, though
207 if (array_key_exists($key, $server)) {
212 if ($value && strpos($key, 'HTTP_') === 0) {
213 $name = strtr(strtolower(substr($key, 5)), '_', '-');
214 $headers[$name] = $value;
218 if ($value && strpos($key, 'CONTENT_') === 0) {
219 $name = 'content-' . strtolower(substr($key, 8));
220 $headers[$name] = $value;
229 * Marshal the URI from the $_SERVER array and headers
231 * @param array $server
232 * @param array $headers
235 public static function marshalUriFromServer(array $server, array $headers)
241 $https = self::get('HTTPS', $server);
242 if (($https && 'off' !== $https)
243 || self::getHeader('x-forwarded-proto', $headers, false) === 'https'
247 $uri = $uri->withScheme($scheme);
250 $accumulator = (object) ['host' => '', 'port' => null];
251 self::marshalHostAndPortFromHeaders($accumulator, $server, $headers);
252 $host = $accumulator->host;
253 $port = $accumulator->port;
254 if (! empty($host)) {
255 $uri = $uri->withHost($host);
256 if (! empty($port)) {
257 $uri = $uri->withPort($port);
262 $path = self::marshalRequestUri($server);
263 $path = self::stripQueryString($path);
267 if (isset($server['QUERY_STRING'])) {
268 $query = ltrim($server['QUERY_STRING'], '?');
273 if (strpos($path, '#') !== false) {
274 list($path, $fragment) = explode('#', $path, 2);
279 ->withFragment($fragment)
284 * Marshal the host and port from HTTP headers and/or the PHP environment
286 * @param stdClass $accumulator
287 * @param array $server
288 * @param array $headers
290 public static function marshalHostAndPortFromHeaders(stdClass $accumulator, array $server, array $headers)
292 if (self::getHeader('host', $headers, false)) {
293 self::marshalHostAndPortFromHeader($accumulator, self::getHeader('host', $headers));
297 if (! isset($server['SERVER_NAME'])) {
301 $accumulator->host = $server['SERVER_NAME'];
302 if (isset($server['SERVER_PORT'])) {
303 $accumulator->port = (int) $server['SERVER_PORT'];
306 if (! isset($server['SERVER_ADDR']) || ! preg_match('/^\[[0-9a-fA-F\:]+\]$/', $accumulator->host)) {
310 // Misinterpreted IPv6-Address
311 // Reported for Safari on Windows
312 self::marshalIpv6HostAndPort($accumulator, $server);
316 * Detect the base URI for the request
318 * Looks at a variety of criteria in order to attempt to autodetect a base
319 * URI, including rewrite URIs, proxy URIs, etc.
321 * From ZF2's Zend\Http\PhpEnvironment\Request class
322 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
323 * @license http://framework.zend.com/license/new-bsd New BSD License
325 * @param array $server
328 public static function marshalRequestUri(array $server)
330 // IIS7 with URL Rewrite: make sure we get the unencoded url
331 // (double slash problem).
332 $iisUrlRewritten = self::get('IIS_WasUrlRewritten', $server);
333 $unencodedUrl = self::get('UNENCODED_URL', $server, '');
334 if ('1' == $iisUrlRewritten && ! empty($unencodedUrl)) {
335 return $unencodedUrl;
338 $requestUri = self::get('REQUEST_URI', $server);
340 // Check this first so IIS will catch.
341 $httpXRewriteUrl = self::get('HTTP_X_REWRITE_URL', $server);
342 if ($httpXRewriteUrl !== null) {
343 $requestUri = $httpXRewriteUrl;
346 // Check for IIS 7.0 or later with ISAPI_Rewrite
347 $httpXOriginalUrl = self::get('HTTP_X_ORIGINAL_URL', $server);
348 if ($httpXOriginalUrl !== null) {
349 $requestUri = $httpXOriginalUrl;
352 if ($requestUri !== null) {
353 return preg_replace('#^[^/:]+://[^/]+#', '', $requestUri);
356 $origPathInfo = self::get('ORIG_PATH_INFO', $server);
357 if (empty($origPathInfo)) {
361 return $origPathInfo;
365 * Strip the query string from a path
370 public static function stripQueryString($path)
372 if (($qpos = strpos($path, '?')) !== false) {
373 return substr($path, 0, $qpos);
379 * Marshal the host and port from the request header
381 * @param stdClass $accumulator
382 * @param string|array $host
385 private static function marshalHostAndPortFromHeader(stdClass $accumulator, $host)
387 if (is_array($host)) {
388 $host = implode(', ', $host);
391 $accumulator->host = $host;
392 $accumulator->port = null;
394 // works for regname, IPv4 & IPv6
395 if (preg_match('|\:(\d+)$|', $accumulator->host, $matches)) {
396 $accumulator->host = substr($accumulator->host, 0, -1 * (strlen($matches[1]) + 1));
397 $accumulator->port = (int) $matches[1];
402 * Marshal host/port from misinterpreted IPv6 address
404 * @param stdClass $accumulator
405 * @param array $server
407 private static function marshalIpv6HostAndPort(stdClass $accumulator, array $server)
409 $accumulator->host = '[' . $server['SERVER_ADDR'] . ']';
410 $accumulator->port = $accumulator->port ?: 80;
411 if ($accumulator->port . ']' === substr($accumulator->host, strrpos($accumulator->host, ':') + 1)) {
412 // The last digit of the IPv6-Address has been taken as port
413 // Unset the port so the default port can be used
414 $accumulator->port = null;
419 * Create and return an UploadedFile instance from a $_FILES specification.
421 * If the specification represents an array of values, this method will
422 * delegate to normalizeNestedFileSpec() and return that return value.
424 * @param array $value $_FILES struct
425 * @return array|UploadedFileInterface
427 private static function createUploadedFileFromSpec(array $value)
429 if (is_array($value['tmp_name'])) {
430 return self::normalizeNestedFileSpec($value);
433 return new UploadedFile(
443 * Normalize an array of file specifications.
445 * Loops through all nested files and returns a normalized array of
446 * UploadedFileInterface instances.
448 * @param array $files
449 * @return UploadedFileInterface[]
451 private static function normalizeNestedFileSpec(array $files = [])
453 $normalizedFiles = [];
454 foreach (array_keys($files['tmp_name']) as $key) {
456 'tmp_name' => $files['tmp_name'][$key],
457 'size' => $files['size'][$key],
458 'error' => $files['error'][$key],
459 'name' => $files['name'][$key],
460 'type' => $files['type'][$key],
462 $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
464 return $normalizedFiles;
468 * Return HTTP protocol version (X.Y)
470 * @param array $server
473 private static function marshalProtocolVersion(array $server)
475 if (! isset($server['SERVER_PROTOCOL'])) {
479 if (! preg_match('#^(HTTP/)?(?P<version>[1-9]\d*(?:\.\d)?)$#', $server['SERVER_PROTOCOL'], $matches)) {
480 throw new UnexpectedValueException(sprintf(
481 'Unrecognized protocol version (%s)',
482 $server['SERVER_PROTOCOL']
486 return $matches['version'];
490 * Parse a cookie header according to RFC 6265.
492 * PHP will replace special characters in cookie names, which results in other cookies not being available due to
493 * overwriting. Thus, the server request should take the cookies from the request header instead.
495 * @param $cookieHeader
498 private static function parseCookieHeader($cookieHeader)
502 (?P<name>[!#$%&\'*+-.0-9A-Z^_`a-z|~]+)
505 (?P<value>[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*)
508 )x', $cookieHeader, $matches, PREG_SET_ORDER);
512 foreach ($matches as $match) {
513 $cookies[$match['name']] = urldecode($match['value']);