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

BooleanHandler::validate()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 30
ccs 16
cts 16
cp 1
rs 8.4444
c 0
b 0
f 0
cc 8
nc 9
nop 3
crap 8
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\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\ValidationContext;
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
    private FormatterInterface $formatter;
19
20 22
    public function __construct(?FormatterInterface $formatter = null)
21
    {
22 22
        $this->formatter = $formatter ?? new Formatter();
23
    }
24
25 22
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
26
    {
27 22
        if (!$rule instanceof Boolean) {
28 1
            throw new UnexpectedRuleException(Boolean::class, $rule);
29
        }
30
31 21
        if ($rule->isStrict()) {
32 8
            $valid = $value === $rule->getTrueValue() || $value === $rule->getFalseValue();
33
        } else {
34 13
            $valid = $value == $rule->getTrueValue() || $value == $rule->getFalseValue();
35
        }
36
37 21
        $result = new Result();
38
39 21
        if ($valid) {
40 13
            return $result;
41
        }
42
43 8
        $formattedMessage = $this->formatter->format(
44 8
            $rule->getMessage(),
45
            [
46 8
                'true' => $rule->getTrueValue() === true ? '1' : $rule->getTrueValue(),
47 8
                'false' => $rule->getFalseValue() === false ? '0' : $rule->getFalseValue(),
48 8
                'attribute' => $context?->getAttribute(),
49
                'value' => $value,
50
            ]
51
        );
52 8
        $result->addError($formattedMessage);
53
54 8
        return $result;
55
    }
56
}
57