1 | <?php declare(strict_types=1); |
||
2 | |||
3 | namespace jschreuder\Middle\ServerMiddleware; |
||
4 | |||
5 | use Psr\Http\Message\ResponseInterface; |
||
6 | use Psr\Http\Message\ServerRequestInterface; |
||
7 | use Psr\Http\Server\MiddlewareInterface; |
||
8 | use Psr\Http\Server\RequestHandlerInterface; |
||
9 | |||
10 | final class JsonRequestParserMiddleware implements MiddlewareInterface |
||
11 | { |
||
12 | /** @var string[] array of regexes to check against content-types */ |
||
13 | private array $jsonContentTypes; |
||
14 | |||
15 | 6 | public function __construct(array $jsonContentTypes = null) |
|
16 | { |
||
17 | 6 | if (is_null($jsonContentTypes)) { |
|
18 | 5 | $jsonContentTypes = ['#^application\/json(;|$)#iD']; |
|
19 | } |
||
20 | 6 | $this->jsonContentTypes = $jsonContentTypes; |
|
21 | } |
||
22 | |||
23 | 5 | public function process(ServerRequestInterface $request, RequestHandlerInterface $requestHandler): ResponseInterface |
|
24 | { |
||
25 | 5 | if ($this->isJsonRequest($request->getHeaderLine('Content-Type'))) { |
|
26 | 4 | $request = $request->withParsedBody($this->parseBody($request)); |
|
27 | } |
||
28 | 4 | return $requestHandler->handle($request); |
|
29 | } |
||
30 | |||
31 | 5 | private function isJsonRequest(?string $requestContentType) : bool |
|
32 | { |
||
33 | 5 | foreach ($this->jsonContentTypes as $jsonContentType) { |
|
34 | 5 | if (preg_match($jsonContentType, $requestContentType) > 0) { |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
35 | 4 | return true; |
|
36 | } |
||
37 | } |
||
38 | 1 | return false; |
|
39 | } |
||
40 | |||
41 | 4 | private function parseBody(ServerRequestInterface $request) : array |
|
42 | { |
||
43 | 4 | $parsedBody = json_decode($request->getBody()->getContents(), true); |
|
44 | 4 | if (json_last_error() !== JSON_ERROR_NONE) { |
|
45 | 1 | throw new \InvalidArgumentException('Could not decode JSON body: ' . json_last_error_msg()); |
|
46 | } |
||
47 | |||
48 | 3 | return $parsedBody; |
|
49 | } |
||
50 | } |
||
51 |