Passed
Push — master ( beb5fc...4d9ea0 )
by Anton
02:12
created

JsonPayloadMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 9
c 1
b 0
f 1
dl 0
loc 29
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 11 3
A isJsonPayload() 0 5 1
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
declare(strict_types=1);
9
10
namespace Spiral\Http\Middleware;
11
12
use Psr\Http\Message\ResponseInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
use Psr\Http\Server\MiddlewareInterface;
15
use Psr\Http\Server\RequestHandlerInterface;
16
use Spiral\Http\Exception\ClientException;
17
18
/**
19
 * Automatically parse application/json payloads.
20
 */
21
final class JsonPayloadMiddleware implements MiddlewareInterface
22
{
23
    /**
24
     * @param ServerRequestInterface  $request
25
     * @param RequestHandlerInterface $handler
26
     * @return ResponseInterface
27
     */
28
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
29
    {
30
        if ($this->isJsonPayload($request)) {
31
            try {
32
                $request = $request->withParsedBody(json_decode($request->getBody()->getContents(), true));
33
            } catch (\Throwable $exception) {
34
                throw new ClientException(400, 'invalid json payload');
35
            }
36
        }
37
38
        return $handler->handle($request);
39
    }
40
41
    /**
42
     * @param ServerRequestInterface $request
43
     * @return bool
44
     */
45
    private function isJsonPayload(ServerRequestInterface $request): bool
46
    {
47
        $contentType = $request->getHeaderLine('Content-Type');
48
49
        return stripos($contentType, 'application/json') === 0;
50
    }
51
}