Passed
Pull Request — master (#490)
by
unknown
02:47
created

TrueValueHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 27 5
A getCommonResultParameters() 0 5 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
/**
13
 * A handler for {@see TrueValue} rule.
14
 */
15
final class TrueValueHandler implements RuleHandlerInterface
16
{
17
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
18
    {
19
        if (!$rule instanceof TrueValue) {
20
            throw new UnexpectedRuleException(TrueValue::class, $rule);
21
        }
22
23
        if (!is_scalar($value)) {
24
            $parameters = $this->getCommonResultParameters($rule, $context);
25
            $parameters['type'] = get_debug_type($value);
26
27
            return (new Result())->addError($rule->getIncorrectInputMessage(), $parameters);
28
        }
29
30
        if ($rule->isStrict()) {
31
            $valid = $value === $rule->getTrueValue();
32
        } else {
33
            $valid = $value == $rule->getTrueValue();
34
        }
35
36
        if ($valid) {
37
            return new Result();
38
        }
39
40
        $parameters = $this->getCommonResultParameters($rule, $context);
41
        $parameters['value'] = $value;
42
43
        return (new Result())->addError($rule->getMessage(), $parameters);
44
    }
45
46
    /**
47
     * @param TrueValue $rule A rule instance.
48
     * @param ValidationContext $context Validation context.
49
     *
50
     * @return array A mapping between attribute names and their values.
51
     * @psalm-return array<string,scalar|null>
52
     */
53
    private function getCommonResultParameters(TrueValue $rule, ValidationContext $context): array
54
    {
55
        return [
56
            'attribute' => $context->getTranslatedAttribute(),
57
            'true' => $rule->getTrueValue() === true ? 'true' : $rule->getTrueValue(),
58
        ];
59
    }
60
}
61