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