Passed
Pull Request — master (#222)
by Dmitriy
02:35
created

JsonHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 21
dl 0
loc 37
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 13 3
A isValidJson() 0 20 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\ValidationContext;
9
use function is_string;
10
use Yiisoft\Validator\Exception\UnexpectedRuleException;
11
12
/**
13
 * Validates that the value is a valid json.
14
 */
15
final class JsonHandler implements RuleHandlerInterface
16
{
17 10
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
18
    {
19 10
        if (!$rule instanceof Json) {
20 1
            throw new UnexpectedRuleException(Json::class, $rule);
21
        }
22
23 9
        $result = new Result();
24
25 9
        if (!$this->isValidJson($value)) {
26 6
            $result->addError($rule->message);
27
        }
28
29 9
        return $result;
30
    }
31
32 9
    private function isValidJson($value): bool
33
    {
34
        // Regular expression is built based on JSON grammar specified at
35
        // https://tools.ietf.org/html/rfc8259
36 9
        $regex = <<<'REGEX'
37
        /
38
        (?(DEFINE)
39
            (?<json>(?>\s*(?&object)\s*|\s*(?&array)\s*))
40
            (?<object>(?>\{\s*(?>(?&member)(?>\s*,\s*(?&member))*)?\s*\}))
41
            (?<member>(?>(?&string)\s*:\s*(?&value)))
42
            (?<array>(?>\[\s*(?>(?&value)(?>\s*,\s*(?&value))*)?\s*\]))
43
            (?<value>(?>)false|null|true|(?&object)|(?&array)|(?&number)|(?&string))
44
            (?<number>(?>-?(?>0|[1-9]\d*)(?>\.\d+)?(?>[eE][-+]?\d+)?))
45
            (?<string>(?>"(?>\\(?>["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\0-\x1F\x7F]+)*"))
46
        )
47
        \A(?&json)\z
48
        /x
49
        REGEX;
50
51 9
        return is_string($value) && preg_match($regex, $value) === 1;
52
    }
53
}
54