Passed
Pull Request — master (#287)
by Alexander
02:26
created

IsTrueHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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