Test Failed
Pull Request — master (#175)
by
unknown
12:57
created

Json::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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