Completed
Push — master ( fb95ee...b3e448 )
by Oscar
9s
created

Payload::__construct()   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 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
     * Payload constructor.
22
     * @param mixed[] $options
23
     */
24
    public function __construct(array $options = [])
25
    {
26
        $this->options = $options;
27
    }
28
29
    /**
30
     * Execute the middleware.
31
     *
32
     * @param ServerRequestInterface $request
33
     * @param ResponseInterface      $response
34
     * @param callable               $next
35
     *
36
     * @return ResponseInterface
37
     */
38
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
39
    {
40
        if (!$request->getParsedBody() && in_array($request->getMethod(), ['POST', 'PUT', 'PATCH', 'DELETE', 'COPY', 'LOCK', 'UNLOCK'], true)) {
41
            $resolver = $this->resolver ?: new Transformers\BodyParser($this->options);
42
            $transformer = $resolver->resolve(trim($request->getHeaderLine('Content-Type')));
43
44
            if ($transformer) {
45
                try {
46
                    $request = $request->withParsedBody($transformer($request->getBody()));
47
                } catch (\Exception $exception) {
48
                    return $response->withStatus(400);
49
                }
50
            }
51
        }
52
53
        return $next($request, $response);
54
    }
55
}
56