Completed
Push — master ( 519e29...c8bd89 )
by Oscar
04:56 queued 02:21
created

Payload::overrideExistingParsedBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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 $overrideExistingParsedBody = 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
    public function overrideExistingParsedBody()
40
    {
41
        $this->overrideExistingParsedBody = true;
42
    }
43
44
    /**
45
     * Execute the middleware.
46
     *
47
     * @param ServerRequestInterface $request
48
     * @param ResponseInterface      $response
49
     * @param callable               $next
50
     *
51
     * @return ResponseInterface
52
     */
53
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
54
    {
55
        $parsableMethods = ['POST', 'PUT', 'PATCH', 'DELETE', 'COPY', 'LOCK', 'UNLOCK'];
56
57
        if (
58
            ($this->overrideExistingParsedBody || !$request->getParsedBody()) &&
59
            in_array($request->getMethod(), $parsableMethods, true)
60
        ) {
61
            $resolver = $this->resolver ?: new Transformers\BodyParser($this->options);
62
            $transformer = $resolver->resolve(trim($request->getHeaderLine('Content-Type')));
63
            if ($transformer) {
64
                try {
65
                    $request = $request->withParsedBody($transformer($request->getBody()));
66
                } catch (\Exception $exception) {
67
                    return $response->withStatus(400);
68
                }
69
            }
70
        }
71
72
        return $next($request, $response);
73
    }
74
}
75