Passed
Pull Request — master (#222)
by Rustam
02:39
created

JsonHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 26
dl 0
loc 48
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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