Passed
Pull Request — master (#222)
by Alexander
04:54 queued 02:26
created

JsonHandler::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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