Passed
Push — master ( 081b04...39be92 )
by Marcel
01:57
created

Error::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 8
cts 8
cp 1
rs 9.7
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UMA\JsonRpc;
6
7
class Error extends Response
8
{
9
    /**
10
     * @var int
11
     */
12
    private $code;
13
14
    /**
15
     * @var string
16
     */
17
    private $message;
18
19
    /**
20
     * @var mixed
21
     */
22
    private $data;
23
24
    /**
25
     * @param int             $code
26
     * @param string          $message
27
     * @param mixed           $data
28
     * @param int|string|null $id
29
     */
30 14
    public function __construct(int $code, string $message, $data = null, $id = null)
31
    {
32 14
        $this->code = $code;
33 14
        $this->message = $message;
34 14
        $this->data = $data;
35 14
        $this->id = $id;
36 14
    }
37
38 3
    public static function parsing(): Error
39
    {
40 3
        return new static(-32700, 'Parse error');
41
    }
42
43 6
    public static function invalidRequest(): Error
44
    {
45 6
        return new static(-32600, 'Invalid Request');
46
    }
47
48 4
    public static function unknownMethod($id): Error
49
    {
50 4
        return new static(-32601, 'Method not found', null, $id);
51
    }
52
53 2
    public static function invalidParams($id): Error
54
    {
55 2
        return new static(-32602, 'Invalid params', null, $id);
56
    }
57
58 3
    public static function internal($id): Error
59
    {
60 3
        return new static(-32603, 'Internal error', null, $id);
61
    }
62
63 2
    public static function tooManyBatchRequests(int $limit): Error
64
    {
65 2
        return new static(-32000, 'Too many batch requests sent to server', ['limit' => $limit]);
66
    }
67
68 13
    public function jsonSerialize(): array
69
    {
70
        $payload = [
71 13
            'jsonrpc' => '2.0',
72
            'error' => [
73 13
                'code' => $this->code,
74 13
                'message' => $this->message
75
            ],
76 13
            'id' => $this->id
77
        ];
78
79 13
        if (null !== $this->data) {
80 2
            $payload['error']['data'] = $this->data;
81
        }
82
83 13
        return $payload;
84
    }
85
}
86