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

JsonParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
}