to keep the system as vanilla as possible to allow upgrading etc, is it possible to “extend” the current request object?
2 days later and so far the only thing that comes close would be to duplicate the internals (How to overwrite request in SLIM 4 - #5 by andrei.neneve) and add my single method i want to add to the request object to it and then break with every update type thing.
class CustomServerRequestFactory implements ServerRequestFactoryInterface {
public function __construct(?StreamFactoryInterface $streamFactory = null, ?UriFactoryInterface $uriFactory = null)
{
if (!isset($streamFactory)) {
$streamFactory = new StreamFactory();
}
if (!isset($uriFactory)) {
$uriFactory = new UriFactory();
}
$this->streamFactory = $streamFactory;
$this->uriFactory = $uriFactory;
}
public static function createFromGlobals(): Request
{
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
$uri = (new UriFactory())->createFromGlobals($_SERVER);
$headers = Headers::createFromGlobals();
$cookies = Cookies::parseHeader($headers->getHeader('Cookie', []));
// Cache the php://input stream as it cannot be re-read
$cacheResource = fopen('php://temp', 'wb+');
$cache = $cacheResource ? new Stream($cacheResource) : null;
$body = (new StreamFactory())->createStreamFromFile('php://input', 'r', $cache);
$uploadedFiles = UploadedFile::createFromGlobals($_SERVER);
$request = new Request($method, $uri, $headers, $cookies, $_SERVER, $body, $uploadedFiles);
$contentTypes = $request->getHeader('Content-Type') ?? [];
$parsedContentType = '';
foreach ($contentTypes as $contentType) {
$fragments = explode(';', $contentType);
$parsedContentType = current($fragments);
}
$contentTypesWithParsedBodies = ['application/x-www-form-urlencoded', 'multipart/form-data'];
if ($method === 'POST' && in_array($parsedContentType, $contentTypesWithParsedBodies)) {
return $request->withParsedBody($_POST);
}
return $request;
}
}
just to be able to define a custom Request object that extends the base Request object. (new Request → new CustomRequest