Passed
Pull Request — master (#99)
by Def
02:08
created

Json   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 45
ccs 12
cts 12
cp 1
rs 10
c 1
b 0
f 0
wmc 5

3 Methods

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