JsonHandler   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 45
rs 10
c 2
b 0
f 0
ccs 14
cts 14
cp 1
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 23 4
A isValidJson() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function function_exists;
13
use function is_string;
14
15
/**
16
 * A handler for {@see Json} rule. Validates that the value is a valid JSON string.
17
 *
18
 * @see https://en.wikipedia.org/wiki/JSON
19 15
 * @see https://tools.ietf.org/html/rfc8259
20
 */
21 15
final class JsonHandler implements RuleHandlerInterface
22 1
{
23
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
24
    {
25 14
        if (!$rule instanceof Json) {
26 14
            throw new UnexpectedRuleException(Json::class, $rule);
27 6
        }
28 6
29 6
        $result = new Result();
30
        if (!is_string($value)) {
31
            return $result->addError($rule->getIncorrectInputMessage(), [
32
                'attribute' => $context->getTranslatedAttribute(),
33
                'type' => get_debug_type($value),
34 8
            ]);
35 5
        }
36 5
37
38
        if (!$this->isValidJson($value)) {
39
            return $result->addError($rule->getMessage(), [
40
                'attribute' => $context->getTranslatedAttribute(),
41 3
                'value' => $value,
42
            ]);
43
        }
44 8
45
        return $result;
46
    }
47
48 8
    /**
49
     * Checks if the given value is a valid JSON.
50
     *
51
     * @param string $value Any string.
52
     *
53
     * @return bool Whether the given value is a valid JSON: `true` - valid JSON, `false` - invalid JSON with errors /
54
     * not a JSON at all.
55
     */
56
    private function isValidJson(string $value): bool
57
    {
58
        if (function_exists('json_validate')) {
59
            /** @var bool Can be removed after upgrading to PHP 8.3 */
60
            return json_validate($value);
61
        }
62
63 8
        json_decode($value);
64
65
        return json_last_error() === JSON_ERROR_NONE;
66
    }
67
}
68