Passed
Pull Request — master (#222)
by Rustam
02:21
created

BooleanHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 14
dl 0
loc 29
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 27 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\ValidationContext;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
11
/**
12
 * Checks if the value is a boolean value or a value corresponding to it.
13
 */
14
final class BooleanHandler implements RuleHandlerInterface
15
{
16 22
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
17
    {
18 22
        if (!$rule instanceof Boolean) {
19 1
            throw new UnexpectedRuleException(Boolean::class, $rule);
20
        }
21
22 21
        if ($rule->isStrict()) {
23 8
            $valid = $value === $rule->getTrueValue() || $value === $rule->getFalseValue();
24
        } else {
25 13
            $valid = $value == $rule->getTrueValue() || $value == $rule->getFalseValue();
26
        }
27
28 21
        $result = new Result();
29
30 21
        if ($valid) {
31 13
            return $result;
32
        }
33
34 8
        $result->addError($rule->getMessage(), [
35
            // TODO: get reasons to do like this
36
            //  'true' => $config->getTrueValue() === true ? 'true' : $config->getTrueValue(),
37
            //  'false' => $config->$this->getFalseValue() === false ? 'false' : $config->$this->getFalseValue(),
38 8
            'true' => $rule->getTrueValue(),
39 8
            'false' => $rule->getFalseValue(),
40
        ]);
41
42 8
        return $result;
43
    }
44
}
45