|
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 Assert\Assertion; |
|
18
|
|
|
use Exception; |
|
19
|
|
|
use UnexpectedValueException; |
|
20
|
|
|
|
|
21
|
|
|
final class JsonValidationException extends UnexpectedValueException |
|
22
|
|
|
{ |
|
23
|
|
|
private $validatedFile; |
|
24
|
|
|
private $errors; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* {@inheritdoc} |
|
28
|
|
|
* |
|
29
|
|
|
* @param string[] $errors |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __construct(string $message, string $file = null, $errors = [], Exception $previous = null) |
|
32
|
|
|
{ |
|
33
|
|
|
Assertion::file($file); |
|
34
|
|
|
Assertion::allString($errors); |
|
35
|
|
|
|
|
36
|
|
|
$this->validatedFile = $file; |
|
37
|
|
|
$this->errors = $errors; |
|
38
|
|
|
|
|
39
|
|
|
parent::__construct($message, 0, $previous); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Creates an exception according to a given code with a customized message. |
|
44
|
|
|
* |
|
45
|
|
|
* @param int $code return code of json_last_error function |
|
46
|
|
|
* |
|
47
|
|
|
* @return static |
|
48
|
|
|
*/ |
|
49
|
|
|
public static function createDecodeException(int $code): self |
|
50
|
|
|
{ |
|
51
|
|
|
switch ($code) { |
|
52
|
|
|
case JSON_ERROR_CTRL_CHAR: |
|
53
|
|
|
$msg = 'Control character error, possibly incorrectly encoded.'; |
|
54
|
|
|
break; |
|
55
|
|
|
case JSON_ERROR_DEPTH: |
|
56
|
|
|
$msg = 'The maximum stack depth has been exceeded.'; |
|
57
|
|
|
break; |
|
58
|
|
|
case JSON_ERROR_STATE_MISMATCH: |
|
59
|
|
|
$msg = 'Invalid or malformed JSON.'; |
|
60
|
|
|
break; |
|
61
|
|
|
case JSON_ERROR_SYNTAX: |
|
62
|
|
|
$msg = 'Syntax error.'; |
|
63
|
|
|
break; |
|
64
|
|
|
case JSON_ERROR_UTF8: |
|
65
|
|
|
$msg = 'Malformed UTF-8 characters, possibly incorrectly encoded.'; |
|
66
|
|
|
break; |
|
67
|
|
|
default: |
|
68
|
|
|
$msg = 'Unknown error'; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return new self('JSON decoding failed: '.$msg); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
public function getValidatedFile(): ?string |
|
75
|
|
|
{ |
|
76
|
|
|
return $this->validatedFile; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* @return string[] |
|
81
|
|
|
*/ |
|
82
|
|
|
public function getErrors(): array |
|
83
|
|
|
{ |
|
84
|
|
|
return $this->errors; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|