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

Json::getRawOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
ccs 4
cts 4
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 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