Passed
Pull Request — master (#81)
by Def
04:12 queued 02:54
created

Json::getName()   A

Complexity

Conditions 1
Paths 1

Size

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