Passed
Push — master ( 9d8a75...f0a095 )
by Alexander
01:39
created

Boolean::validateValue()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 8
nop 2
dl 0
loc 23
ccs 12
cts 12
cp 1
crap 7
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Rule;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\DataSetInterface;
10
11
/**
12
 * BooleanValidator checks if the attribute value is a boolean value or a value corresponding to it.
13
 */
14
class Boolean extends Rule
15
{
16
    /**
17
     * @var mixed the value representing true status. Defaults to '1'.
18
     */
19
    private $trueValue = '1';
20
    /**
21
     * @var mixed the value representing false status. Defaults to '0'.
22
     */
23
    private $falseValue = '0';
24
    /**
25
     * @var bool whether the comparison to [[trueValue]] and [[falseValue]] is strict.
26
     * When this is true, the attribute value and type must both match those of [[trueValue]] or [[falseValue]].
27
     * Defaults to false, meaning only the value needs to be matched.
28
     */
29
    private bool $strict = false;
30
31
    private string $message = 'The value must be either "{true}" or "{false}".';
32
33
    public function message(string $message): self
34
    {
35
        $this->message = $message;
36
        return $this;
37
    }
38
39
    public function trueValue($value): self
40
    {
41
        $this->trueValue = $value;
42
        return $this;
43
    }
44
45
    public function falseValue($value): self
46
    {
47
        $this->falseValue = $value;
48
        return $this;
49
    }
50
51
    public function strict(bool $value): self
52
    {
53
        $this->strict = $value;
54
        return $this;
55
    }
56
57 17
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
58
    {
59 17
        if ($this->strict) {
60 8
            $valid = $value === $this->trueValue || $value === $this->falseValue;
61
        } else {
62 9
            $valid = $value == $this->trueValue || $value == $this->falseValue;
63
        }
64
65 17
        $result = new Result();
66
67 17
        if (!$valid) {
68 7
            $result->addError(
69 7
                $this->translateMessage(
70 7
                    $this->message,
71
                    [
72 7
                        'true' => $this->trueValue === true ? 'true' : $this->trueValue,
73 7
                        'false' => $this->falseValue === false ? 'false' : $this->falseValue,
74
                    ]
75
                )
76
            );
77
        }
78
79 17
        return $result;
80
    }
81
}
82