|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Attribute; |
|
8
|
|
|
use Yiisoft\Validator\FormatterInterface; |
|
9
|
|
|
use Yiisoft\Validator\Result; |
|
10
|
|
|
use Yiisoft\Validator\Rule; |
|
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
12
|
|
|
|
|
13
|
|
|
use function is_string; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Validates that the value is a valid json. |
|
17
|
|
|
*/ |
|
18
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY)] |
|
19
|
|
|
final class Json extends Rule |
|
20
|
|
|
{ |
|
21
|
|
|
public function __construct( |
|
22
|
|
|
private string $message = 'The value is not JSON.', |
|
23
|
6 |
|
?FormatterInterface $formatter = null, |
|
24
|
|
|
bool $skipOnEmpty = false, |
|
25
|
6 |
|
bool $skipOnError = false, |
|
26
|
|
|
$when = null, |
|
27
|
|
|
) { |
|
28
|
5 |
|
parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when); |
|
29
|
|
|
} |
|
30
|
5 |
|
|
|
31
|
|
|
protected function validateValue($value, ?ValidationContext $context = null): Result |
|
32
|
5 |
|
{ |
|
33
|
4 |
|
$result = new Result(); |
|
34
|
|
|
|
|
35
|
|
|
if (!$this->isValidJson($value)) { |
|
36
|
5 |
|
$result->addError($this->formatMessage($this->message)); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
5 |
|
return $result; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
private function isValidJson($value): bool |
|
43
|
5 |
|
{ |
|
44
|
|
|
// Regular expression is built based on JSON grammar specified at |
|
45
|
|
|
// https://tools.ietf.org/html/rfc8259 |
|
46
|
|
|
$regex = <<<'REGEX' |
|
47
|
|
|
/ |
|
48
|
|
|
(?(DEFINE) |
|
49
|
|
|
(?<json>(?>\s*(?&object)\s*|\s*(?&array)\s*)) |
|
50
|
|
|
(?<object>(?>\{\s*(?>(?&member)(?>\s*,\s*(?&member))*)?\s*\})) |
|
51
|
|
|
(?<member>(?>(?&string)\s*:\s*(?&value))) |
|
52
|
|
|
(?<array>(?>\[\s*(?>(?&value)(?>\s*,\s*(?&value))*)?\s*\])) |
|
53
|
|
|
(?<value>(?>)false|null|true|(?&object)|(?&array)|(?&number)|(?&string)) |
|
54
|
|
|
(?<number>(?>-?(?>0|[1-9]\d*)(?>\.\d+)?(?>[eE][-+]?\d+)?)) |
|
55
|
|
|
(?<string>(?>"(?>\\(?>["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\0-\x1F\x7F]+)*")) |
|
56
|
|
|
) |
|
57
|
|
|
\A(?&json)\z |
|
58
|
5 |
|
/x |
|
59
|
|
|
REGEX; |
|
60
|
|
|
|
|
61
|
1 |
|
return is_string($value) && preg_match($regex, $value) === 1; |
|
62
|
|
|
} |
|
63
|
1 |
|
|
|
64
|
1 |
|
public function getOptions(): array |
|
65
|
|
|
{ |
|
66
|
1 |
|
return array_merge(parent::getOptions(), [ |
|
67
|
|
|
'message' => $this->formatMessage($this->message), |
|
68
|
|
|
]); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|