Error::jsonSerialize()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
1
<?php declare(strict_types=1);
2
3
namespace JSKOS;
4
5
use JSKOS\PrettyJsonSerializable;
6
7
/**
8
 * A JSKOS API Error response.
9
 *
10
 * @see https://gbv.github.io/jskos-api/jskos-api.html#error-responses
11
 */
12
class Error extends \Error implements \JsonSerializable
13
{
14
    protected $error;
15
    protected $description;
16
    protected $uri;
17
18
    /**
19
     * Create a JSKOS API error.
20
     *
21
     * @param integer $code HTTP status code
22
     * @param string  $message
23
     * @param string  $description
24
     * @param string  $uri
25
     */
26
    public function __construct(int $code, string $message=null, string $description=null, string $uri=null)
27
    {
28
        $this->code        = $code;
29
        $this->message     = $message;
30
        $this->description = $description;
31
        $this->uri         = $uri;
32
    }
33
34
35
    /**
36
     * Only include non-null fields in JSON.
37
     */
38
    public function jsonSerialize()
39
    {
40
        $json = [];
41
42
        foreach (['code', 'message', 'description', 'uri'] as $field) {
43
            if ($this->$field !== null) {
44
                $json[$field] = $this->$field;
45
            }
46
        }
47
48
        return $json;
49
    }
50
}
51