Completed
Push — master ( c8bd89...4e56b6 )
by Oscar
02:27
created

Payload::override()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
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)
0 ignored issues
show
Unused Code introduced by
The parameter $override is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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