Passed
Pull Request — master (#41)
by Alexander
09:27
created

Boolean::getMessage()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 4
nop 0
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Yiisoft\Validator\Rule;
3
4
use Yiisoft\Validator\DataSetInterface;
5
use Yiisoft\Validator\Result;
6
use Yiisoft\Validator\Rule;
7
8
/**
9
 * BooleanValidator checks if the attribute value is a boolean value or a value corresponding to it.
10
 */
11
class Boolean extends Rule
12
{
13
    /**
14
     * @var mixed the value representing true status. Defaults to '1'.
15
     */
16
    private $trueValue = '1';
17
    /**
18
     * @var mixed the value representing false status. Defaults to '0'.
19
     */
20
    private $falseValue = '0';
21
    /**
22
     * @var bool whether the comparison to [[trueValue]] and [[falseValue]] is strict.
23
     * When this is true, the attribute value and type must both match those of [[trueValue]] or [[falseValue]].
24
     * Defaults to false, meaning only the value needs to be matched.
25
     */
26
    private bool $strict = false;
27
28
    /**
29
     * @var string
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($this->getMessage());
69
        }
70
71 17
        return $result;
72
    }
73
74 7
    private function getMessage(): string
75
    {
76
        $arguments = [
77 7
            'true' => $this->trueValue === true ? 'true' : $this->trueValue,
78 7
            'false' => $this->falseValue === false ? 'false' : $this->falseValue,
79
        ];
80
81 7
        return $this->formatMessage($this->message, $arguments);
82
    }
83
}
84