Completed
Pull Request — master (#175)
by
unknown
02:25 queued 02:25
created

Json::isValidJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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