Completed
Push — 2.1 ( 75349f...bf116e )
by Alexander
29:27
created

BooleanValidator::getClientOptions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 13
nc 4
nop 2
crap 5
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
12
/**
13
 * BooleanValidator checks if the attribute value is a boolean value.
14
 *
15
 * Possible boolean values can be configured via the [[trueValue]] and [[falseValue]] properties.
16
 * And the comparison can be either [[strict]] or not.
17
 *
18
 * @author Qiang Xue <[email protected]>
19
 * @since 2.0
20
 */
21
class BooleanValidator extends Validator
22
{
23
    /**
24
     * @var mixed the value representing true status. Defaults to '1'.
25
     */
26
    public $trueValue = '1';
27
    /**
28
     * @var mixed the value representing false status. Defaults to '0'.
29
     */
30
    public $falseValue = '0';
31
    /**
32
     * @var bool whether the comparison to [[trueValue]] and [[falseValue]] is strict.
33
     * When this is true, the attribute value and type must both match those of [[trueValue]] or [[falseValue]].
34
     * Defaults to false, meaning only the value needs to be matched.
35
     */
36
    public $strict = false;
37
38
39
    /**
40
     * @inheritdoc
41
     */
42 18
    public function init()
43
    {
44 18
        parent::init();
45 18
        if ($this->message === null) {
46 18
            $this->message = Yii::t('yii', '{attribute} must be either "{true}" or "{false}".');
47
        }
48 18
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53 3
    protected function validateValue($value)
54
    {
55 3
        if ($this->strict) {
56 3
            $valid = $value === $this->trueValue || $value === $this->falseValue;
57
        } else {
58 2
            $valid = $value == $this->trueValue || $value == $this->falseValue;
59
        }
60
61 3
        if (!$valid) {
62 3
            return [$this->message, [
63 3
                'true' => $this->trueValue === true ? 'true' : $this->trueValue,
64 3
                'false' => $this->falseValue === false ? 'false' : $this->falseValue,
65
            ]];
66
        }
67
68 2
        return null;
69
    }
70
}
71