1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Web\Middleware; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use Yiisoft\Http\Header; |
12
|
|
|
|
13
|
|
|
final class JsonBodyParser implements MiddlewareInterface |
14
|
|
|
{ |
15
|
|
|
private const DEFAULT_FLAGS = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_IGNORE; |
16
|
|
|
private bool $assoc = true; |
17
|
|
|
private int $depth = 512; |
18
|
|
|
private int $options = self::DEFAULT_FLAGS; |
19
|
|
|
private bool $throwException = true; |
20
|
|
|
|
21
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
22
|
|
|
{ |
23
|
|
|
$contentType = $request->getHeaderLine(Header::CONTENT_TYPE); |
24
|
|
|
|
25
|
|
|
if ($contentType && strpos(strtolower($contentType), 'application/json') !== false) { |
26
|
|
|
$request = $request->withParsedBody( |
27
|
|
|
$this->parse($request->getBody()->getContents()) |
28
|
|
|
); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return $handler->handle($request); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function withAssoc(bool $value): self |
35
|
|
|
{ |
36
|
|
|
$new = clone $this; |
37
|
|
|
$new->assoc = $value; |
38
|
|
|
return $new; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function withDepth(int $value): self |
42
|
|
|
{ |
43
|
|
|
$new = clone $this; |
44
|
|
|
$new->depth = $value; |
45
|
|
|
return $new; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function withOptions(int $value): self |
49
|
|
|
{ |
50
|
|
|
$new = clone $this; |
51
|
|
|
$new->options = self::DEFAULT_FLAGS | $value; |
52
|
|
|
return $new; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function withThrowException(bool $value): self |
56
|
|
|
{ |
57
|
|
|
$new = clone $this; |
58
|
|
|
$new->throwException = $value; |
59
|
|
|
return $new; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return mixed |
64
|
|
|
*/ |
65
|
|
|
private function parse(string $body) |
66
|
|
|
{ |
67
|
|
|
try { |
68
|
|
|
$result = json_decode($body, $this->assoc, $this->depth, $this->options); |
69
|
|
|
if (is_array($result) || is_object($result)) { |
70
|
|
|
return $result; |
71
|
|
|
} |
72
|
|
|
} catch (\JsonException $e) { |
73
|
|
|
if ($this->throwException) { |
74
|
|
|
throw new \InvalidArgumentException('Invalid JSON data in request body: ' . $e->getMessage()); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
return null; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|