RequestParser::guard()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace Tonic\Component\ApiLayer\JsonRpc\Request;
4
5
use Tonic\Component\ApiLayer\JsonRpc\Request\Exception\InvalidRequestException;
6
use Tonic\Component\ApiLayer\JsonRpc\Request\Exception\ParseException;
7
8
/**
9
 * Turns JSON into request object.
10
 */
11
class RequestParser implements RequestParserInterface
12
{
13
    /**
14
     * {@inheritdoc}
15
     */
16
    public function parse($content)
17
    {
18
        $data = json_decode($content, true);
19
        if (0 !== json_last_error()) {
20
            throw new ParseException(sprintf('Invalid JSON syntax: "%s"', json_last_error_msg()));
21
        }
22
23
        if (!is_array($data)) {
24
            throw new InvalidRequestException('Request is not valid JSON');
25
        }
26
27
        $this->guard($data);
28
29
        return new Request($data['jsonrpc'], $data['id'], $data['method'], $data['params']);
30
    }
31
32
    /**
33
     * @param array $data
34
     *
35
     * @throws InvalidRequestException
36
     */
37
    private function guard(array $data)
38
    {
39
        $difference = array_diff(['jsonrpc', 'method', 'id', 'params'], array_keys($data));
40
41
        if (0 < count($difference)) {
42
            throw new InvalidRequestException(sprintf('Request attributes are missed: %s', implode(', ', $difference)));
43
        }
44
45
        if (!is_array($data['params'])) {
46
            throw new InvalidRequestException('Parameters should have an object structure');
47
        }
48
    }
49
}
50