Passed
Push — master ( b43541...841b5a )
by Alexander
28:36 queued 27:17
created

Json   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidJson() 0 13 3
A validateValue() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\HasValidationMessage;
8
use Yiisoft\Validator\Rule;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\DataSetInterface;
11
use JsonException;
12
13
/**
14
 * JsonValidator validates that the attribute value is a valid json
15
 */
16
class Json extends Rule
17
{
18
    use HasValidationMessage;
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($this->translateMessage($this->message));
28
        }
29
30 5
        return $result;
31
    }
32
33 5
    private function isValidJson($value): bool
34
    {
35 5
        if (!is_string($value)) {
36 1
            return false;
37
        }
38
39
        try {
40 4
            json_decode($value, false, 512, JSON_THROW_ON_ERROR);
41 3
        } catch (JsonException $e) {
42 3
            return false;
43
        }
44
45 1
        return true;
46
    }
47
}
48