Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Last active April 10, 2017 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zegnat/6fd5c1774be4a597772b4c8febb0958a to your computer and use it in GitHub Desktop.
Save Zegnat/6fd5c1774be4a597772b4c8febb0958a to your computer and use it in GitHub Desktop.
Construct a PSR-7 ServerRequest through a PSR-17 factory for the current HTTP request.
<?php
declare(strict_types=1);
namespace Zegnat\Utils;
use Interop\Http\Factory\ServerRequestFactoryInterface;
use Interop\Http\Factory\StreamFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
final class ServerRequestFromGlobals
{
private $requestFactory = null;
private $streamFactory = null;
public function __construct(
ServerRequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory
) {
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
}
public function create(): ServerRequestInterface
{
$serverRequest = $this->requestFactory
->createServerRequestFromArray($_SERVER)
->withCookieParams($_COOKIE)
->withQueryParams($_GET);
if (isset($_SERVER['SERVER_PROTOCOL'])
&& preg_match('@HTTP/(\d+(?:\.\d+)?)@A', $_SERVER['SERVER_PROTOCOL'], $protocol) === 1
) {
$serverRequest = $serverRequest->withProtocolVersion($protocol[1]);
}
$headers = getallheaders();
if (false !== $headers) {
foreach ($headers as $name => $value) {
$serverRequest = $serverRequest->withHeader($name, $value);
}
}
if ($serverRequest->getMethod() === 'POST'
&& in_array(
$serverRequest->getHeaderLine('Content-Type'),
['application/x-www-form-urlencoded', 'multipart/form-data']
)
) {
$serverRequest = $serverRequest->withParsedBody($_POST);
}
$body = $this->streamFactory->createStreamFromFile('php://input', 'rb');
$serverRequest = $serverRequest->withBody($body);
return $serverRequest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment