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

Json   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 50
ccs 14
cts 14
cp 1
rs 10
c 1
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A rule() 0 3 1
A isValidJson() 0 20 2
A getOptions() 0 6 1
A validateValue() 0 9 2
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