-
-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathRequestBodyParsingMiddleware.php
More file actions
70 lines (63 loc) · 2.49 KB
/
Copy pathRequestBodyParsingMiddleware.php
File metadata and controls
70 lines (63 loc) · 2.49 KB
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
<?php
declare(strict_types=1);
namespace Neos\Flow\Http\Middleware;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\ObjectManagement\ObjectManagerInterface;
use Neos\Flow\Property\PropertyMapper;
use Neos\Flow\Property\PropertyMappingConfiguration;
use Neos\Flow\Property\TypeConverter\MediaTypeConverterInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Parses the request body and adds the result to the ServerRequest instance.
*/
class RequestBodyParsingMiddleware implements MiddlewareInterface
{
/**
* @Flow\Inject
* @var PropertyMapper
*/
protected $propertyMapper;
/**
* @Flow\Inject
* @var ObjectManagerInterface
*/
protected $objectManager;
/**
* @inheritDoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
{
if (!empty($request->getParsedBody())) {
return $next->handle($request);
}
$parsedBody = $this->parseRequestBody($request);
return $next->handle($request->withParsedBody($parsedBody));
}
/**
* Parses the request body according to the media type.
*
* @param ServerRequestInterface $httpRequest
* @return null|array|string|integer
*/
protected function parseRequestBody(ServerRequestInterface $httpRequest)
{
$requestBody = $httpRequest->getBody()->getContents();
if ($httpRequest->getBody()->isSeekable()) {
$httpRequest->getBody()->rewind();
}
if ($requestBody === null || $requestBody === '') {
return $requestBody;
}
/** @var MediaTypeConverterInterface $mediaTypeConverter */
$mediaTypeConverter = $this->objectManager->get(MediaTypeConverterInterface::class);
$propertyMappingConfiguration = new PropertyMappingConfiguration();
$propertyMappingConfiguration->setTypeConverter($mediaTypeConverter);
$requestedContentType = $httpRequest->getHeaderLine('Content-Type');
$propertyMappingConfiguration->setTypeConverterOption(MediaTypeConverterInterface::class, MediaTypeConverterInterface::CONFIGURATION_MEDIA_TYPE, $requestedContentType);
// FIXME: The MediaTypeConverter returns an empty array for "error cases", which might be unintended
return $this->propertyMapper->convert($requestBody, 'array', $propertyMappingConfiguration);
}
}