Passed
Push — master ( 99ab46...a20a6f )
by Alexander
02:59
created

Json::rule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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