Passed
Push — master ( 4d49b1...530588 )
by Valentin
03:01 queued 11s
created

JsonPayloadMiddleware::process()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 5
c 1
b 0
f 1
dl 0
loc 10
rs 10
cc 3
nc 3
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Http\Middleware;
13
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use Psr\Http\Server\MiddlewareInterface;
17
use Psr\Http\Server\RequestHandlerInterface;
18
use Spiral\Config\JsonPayloadConfig;
19
use Spiral\Http\Exception\ClientException;
20
21
/**
22
 * Automatically parse application/json payloads.
23
 */
24
final class JsonPayloadMiddleware implements MiddlewareInterface
25
{
26
    /** @var JsonPayloadConfig */
27
    private $config;
28
29
    /**
30
     * JsonPayloadMiddleware constructor.
31
     *
32
     * @param JsonPayloadConfig $config
33
     */
34
    public function __construct(JsonPayloadConfig $config)
35
    {
36
        $this->config = $config;
37
    }
38
39
    /**
40
     * @param ServerRequestInterface  $request
41
     * @param RequestHandlerInterface $handler
42
     * @return ResponseInterface
43
     */
44
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
45
    {
46
        if ($this->isJsonPayload($request)) {
47
            $request = $request->withParsedBody(json_decode((string)$request->getBody(), true));
48
            if (json_last_error() !== 0) {
49
                throw new ClientException(400, 'invalid json payload');
50
            }
51
        }
52
53
        return $handler->handle($request);
54
    }
55
56
    /**
57
     * @param ServerRequestInterface $request
58
     * @return bool
59
     */
60
    private function isJsonPayload(ServerRequestInterface $request): bool
61
    {
62
        $contentType = $request->getHeaderLine('Content-Type');
63
64
        foreach ($this->config->getContentTypes() as $allowedType) {
65
            if (stripos($contentType, $allowedType) === 0) {
66
                return true;
67
            }
68
        }
69
70
        return false;
71
    }
72
}
73