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
|
|
|
|
20
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
21
|
|
|
{ |
22
|
|
|
$contentType = $request->getHeaderLine(Header::CONTENT_TYPE); |
23
|
|
|
|
24
|
|
|
if ($contentType && \strpos(\strtolower($contentType), 'application/json') !== false) { |
25
|
|
|
$request = $request->withParsedBody( |
26
|
|
|
$this->parse($request->getBody()->getContents()) |
27
|
|
|
); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return $handler->handle($request); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function withAssoc(): self |
34
|
|
|
{ |
35
|
|
|
$new = clone $this; |
36
|
|
|
$new->assoc = true; |
37
|
|
|
return $new; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function withoutAssoc(): self |
41
|
|
|
{ |
42
|
|
|
$new = clone $this; |
43
|
|
|
$new->assoc = false; |
44
|
|
|
return $new; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function withDepth(int $value): self |
48
|
|
|
{ |
49
|
|
|
$new = clone $this; |
50
|
|
|
$new->depth = $value; |
51
|
|
|
return $new; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function withOptions(int $value): self |
55
|
|
|
{ |
56
|
|
|
$new = clone $this; |
57
|
|
|
$new->options = self::DEFAULT_FLAGS | $value; |
58
|
|
|
return $new; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return array|object|null |
63
|
|
|
*/ |
64
|
|
|
private function parse(string $body) |
65
|
|
|
{ |
66
|
|
|
$result = \json_decode($body, $this->assoc, $this->depth, $this->options); |
67
|
|
|
if (\is_array($result) || \is_object($result)) { |
68
|
|
|
return $result; |
69
|
|
|
} |
70
|
|
|
return null; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|