Passed
Pull Request — master (#222)
by Dmitriy
02:23
created

BooleanHandler::validate()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 27
ccs 13
cts 13
cp 1
rs 9.2222
cc 6
nc 9
nop 3
crap 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\ValidatorInterface;
10
use Yiisoft\Validator\Exception\UnexpectedRuleException;
11
12
/**
13
 * Checks if the value is a boolean value or a value corresponding to it.
14
 */
15
final class BooleanHandler implements RuleHandlerInterface
16
{
17 22
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
18
    {
19 22
        if (!$rule instanceof Boolean) {
20 1
            throw new UnexpectedRuleException(Boolean::class, $rule);
21
        }
22
23 21
        if ($rule->strict) {
24 8
            $valid = $value === $rule->trueValue || $value === $rule->falseValue;
25
        } else {
26 13
            $valid = $value == $rule->trueValue || $value == $rule->falseValue;
27
        }
28
29 21
        $result = new Result();
30
31 21
        if ($valid) {
32 13
            return $result;
33
        }
34
35 8
        $result->addError($rule->message, [
36
            // TODO: get reasons to do like this
37
            //            'true' => $config->trueValue === true ? 'true' : $config->trueValue,
38
            //            'false' => $config->falseValue === false ? 'false' : $config->falseValue,
39 8
            'true' => $rule->trueValue,
40 8
            'false' => $rule->falseValue,
41
        ]);
42
43 8
        return $result;
44
    }
45
}
46