Passed
Push — master ( 745402...3d5cea )
by Marcel
43s
created

Input::data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UMA\JsonRpc\Internal;
6
7
class Input
8
{
9
    /**
10
     * This is the minimal schema that all incoming payloads must
11
     * conform to in order to be considered actual JSON-RPC requests.
12
     */
13
    private const INPUT_SCHEMA = <<<'JSON'
14
{
15
  "$schema": "https://json-schema.org/draft-07/schema#",
16
  "description": "JSON-RPC 2.0 single request schema",
17
18
  "type": "object",
19
  "required": ["jsonrpc", "method"],
20
  "additionalProperties": false,
21
  "properties": {
22
    "jsonrpc": {
23
      "type": "string",
24
      "enum": ["2.0"]
25
    },
26
    "method": {
27
      "type": "string"
28
    },
29
    "params": {
30
      "type": ["array", "object"]
31
    },
32
    "id": {
33
      "type": ["integer", "string"]
34
    }
35
  }
36
}
37
JSON;
38
39
    /**
40
     * @var \stdClass
41
     */
42
    private static $schema;
43
44
    /**
45
     * @var mixed
46
     */
47
    private $data;
48
49
    /**
50
     * @var int
51
     */
52
    private $error;
53
54 49
    private function __construct($data, int $error)
55
    {
56 49
        $this->data = $data;
57 49
        $this->error = $error;
58 49
    }
59
60 49
    public static function fromString(string $raw): Input
61
    {
62 49
        return new self(\json_decode($raw), \json_last_error());
63
    }
64
65 4
    public static function fromSafeData($data): Input
66
    {
67 4
        \assert(false !== \json_encode($data));
68
69 4
        return new self($data, JSON_ERROR_NONE);
70
    }
71
72 41
    public function data()
73
    {
74 41
        return $this->data;
75
    }
76
77 49
    public function parsable(): bool
78
    {
79 49
        return JSON_ERROR_NONE === $this->error;
80
    }
81
82 45
    public function isArray(): bool
83
    {
84 45
        return \is_array($this->data) && !empty($this->data);
85
    }
86
87 26
    public function isRpcRequest(): bool
88
    {
89 26
        if (!self::$schema instanceof \stdClass) {
90 1
            self::$schema = \json_decode(self::INPUT_SCHEMA);
91
        }
92
93 26
        return Validator::validate(self::$schema, $this->data);
94
    }
95
}
96