|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
7
|
|
|
use Psr7Middlewares\Transformers; |
|
8
|
|
|
use Psr7Middlewares\Utils; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Middleware to parse the body. |
|
12
|
|
|
*/ |
|
13
|
|
|
class Payload |
|
14
|
|
|
{ |
|
15
|
|
|
use Utils\ResolverTrait; |
|
16
|
|
|
|
|
17
|
|
|
/** @var mixed[] */ |
|
18
|
|
|
private $options; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var bool Whether or not Middleware\Payload has precedence over existing parsed bodies |
|
22
|
|
|
*/ |
|
23
|
|
|
private $override = false; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Payload constructor. |
|
27
|
|
|
* |
|
28
|
|
|
* @param mixed[] $options |
|
29
|
|
|
*/ |
|
30
|
|
|
public function __construct(array $options = []) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->options = $options; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* If the Request object already has a parsedBody, normally Payload will skip parsing. This is not always |
|
37
|
|
|
* desirable behavior. Calling this setter allows you to override this behavior. |
|
38
|
|
|
* |
|
39
|
|
|
* @param bool $override |
|
40
|
|
|
* |
|
41
|
|
|
* @return self |
|
42
|
|
|
*/ |
|
43
|
|
|
public function override($override = true) |
|
|
|
|
|
|
44
|
|
|
{ |
|
45
|
|
|
$this->override = true; |
|
46
|
|
|
|
|
47
|
|
|
return $this; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Execute the middleware. |
|
52
|
|
|
* |
|
53
|
|
|
* @param ServerRequestInterface $request |
|
54
|
|
|
* @param ResponseInterface $response |
|
55
|
|
|
* @param callable $next |
|
56
|
|
|
* |
|
57
|
|
|
* @return ResponseInterface |
|
58
|
|
|
*/ |
|
59
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
|
60
|
|
|
{ |
|
61
|
|
|
$parsableMethods = ['POST', 'PUT', 'PATCH', 'DELETE', 'COPY', 'LOCK', 'UNLOCK']; |
|
62
|
|
|
|
|
63
|
|
|
if ( |
|
64
|
|
|
($this->override || !$request->getParsedBody()) && |
|
65
|
|
|
in_array($request->getMethod(), $parsableMethods, true) |
|
66
|
|
|
) { |
|
67
|
|
|
$resolver = $this->resolver ?: new Transformers\BodyParser($this->options); |
|
68
|
|
|
$transformer = $resolver->resolve(trim($request->getHeaderLine('Content-Type'))); |
|
69
|
|
|
if ($transformer) { |
|
70
|
|
|
try { |
|
71
|
|
|
$request = $request->withParsedBody($transformer($request->getBody())); |
|
72
|
|
|
} catch (\Exception $exception) { |
|
73
|
|
|
return $response->withStatus(400); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return $next($request, $response); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.