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

Json::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 5
dl 0
loc 8
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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