Passed
Push — master ( ddc766...cecfbc )
by Alexander
01:30
created

Boolean::trueValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
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
        $new = clone $this;
36
        $new->message = $message;
37
        return $new;
38
    }
39
40
    public function trueValue($value): self
41
    {
42
        $new = clone $this;
43
        $new->trueValue = $value;
44
        return $new;
45
    }
46
47
    public function falseValue($value): self
48
    {
49
        $new = clone $this;
50
        $new->falseValue = $value;
51
        return $new;
52
    }
53
54
    public function strict(bool $value): self
55
    {
56
        $new = clone $this;
57
        $new->strict = $value;
58
        return $new;
59
    }
60
61 17
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
62
    {
63 17
        if ($this->strict) {
64 8
            $valid = $value === $this->trueValue || $value === $this->falseValue;
65
        } else {
66 9
            $valid = $value == $this->trueValue || $value == $this->falseValue;
67
        }
68
69 17
        $result = new Result();
70
71 17
        if (!$valid) {
72 7
            $result->addError(
73 7
                $this->translateMessage(
74 7
                    $this->message,
75
                    [
76 7
                        'true' => $this->trueValue === true ? 'true' : $this->trueValue,
77 7
                        'false' => $this->falseValue === false ? 'false' : $this->falseValue,
78
                    ]
79
                )
80
            );
81
        }
82
83 17
        return $result;
84
    }
85
}
86