Completed
Push — master ( bc7d7f...7a9596 )
by Théo
02:46
created

JsonValidationException::getErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Json;
16
17
use Exception;
18
use UnexpectedValueException;
19
20
final class JsonValidationException extends UnexpectedValueException
21
{
22
    private $errors;
23
24
    public function __construct(string $message, $errors = [], Exception $previous = null)
25
    {
26
        $this->errors = $errors;
27
28
        parent::__construct($message, 0, $previous);
29
    }
30
31
    /**
32
     * Creates an exception according to a given code with a customized message.
33
     *
34
     * @param int $code return code of json_last_error function
35
     *
36
     * @return static
37
     */
38
    public static function createDecodeException(int $code): self
39
    {
40
        switch ($code) {
41
            case JSON_ERROR_CTRL_CHAR:
42
                $msg = 'Control character error, possibly incorrectly encoded.';
43
                break;
44
            case JSON_ERROR_DEPTH:
45
                $msg = 'The maximum stack depth has been exceeded.';
46
                break;
47
            case JSON_ERROR_STATE_MISMATCH:
48
                $msg = 'Invalid or malformed JSON.';
49
                break;
50
            case JSON_ERROR_SYNTAX:
51
                $msg = 'Syntax error.';
52
                break;
53
            case JSON_ERROR_UTF8:
54
                $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
55
                break;
56
            default:
57
                $msg = 'Unknown error';
58
        }
59
60
        return new self('JSON decoding failed: '.$msg);
61
    }
62
63
    public function getErrors()
64
    {
65
        return $this->errors;
66
    }
67
}
68