Completed
Branch 09branch (946dde)
by Anton
05:16
created

JsonParser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __invoke() 0 14 3
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Http\Middlewares;
10
11
use Psr\Http\Message\ResponseInterface as Response;
12
use Psr\Http\Message\ServerRequestInterface as Request;
13
use Spiral\Http\MiddlewareInterface;
14
15
/**
16
 * Populates parsedBody data of request with decoded json content if appropriate request header
17
 * set. Check alternative from ps7-middlewares to find alternative solution with more format
18
 * options.
19
 *
20
 * Incoming JSON parsed into array!
21
 */
22
class JsonParser implements MiddlewareInterface
23
{
24
    /**
25
     * @var bool
26
     */
27
    private $asArray;
28
29
    /**
30
     * @param bool $asArray
31
     */
32
    public function __construct(bool $asArray = true)
33
    {
34
        $this->asArray = $asArray;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function __invoke(Request $request, Response $response, callable $next)
41
    {
42
        if (strpos($request->getHeaderLine('Content-Type'), 'application/json') !== false) {
43
            $data = json_decode($request->getBody()->__toString(), $this->asArray);
44
            if (!empty(json_last_error())) {
45
                //Mailformed request
46
                return $response->withStatus(400);
47
            }
48
49
            $request = $request->withParsedBody($data);
50
        }
51
52
        return $next($request);
53
    }
54
}