CompareValidator.php 8.9 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8
namespace yii\validators;
Qiang Xue committed
9

Qiang Xue committed
10 11
use Yii;
use yii\base\InvalidConfigException;
12
use yii\helpers\Html;
w  
Qiang Xue committed
13

w  
Qiang Xue committed
14
/**
Qiang Xue committed
15
 * CompareValidator compares the specified attribute value with another value.
w  
Qiang Xue committed
16 17
 *
 * The value being compared with can be another attribute value
w  
Qiang Xue committed
18 19
 * (specified via [[compareAttribute]]) or a constant (specified via
 * [[compareValue]]. When both are specified, the latter takes
w  
Qiang Xue committed
20 21 22 23
 * precedence. If neither is specified, the attribute will be compared
 * with another attribute whose name is by appending "_repeat" to the source
 * attribute name.
 *
w  
Qiang Xue committed
24 25
 * CompareValidator supports different comparison operators, specified
 * via the [[operator]] property.
w  
Qiang Xue committed
26 27
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
28
 * @since 2.0
w  
Qiang Xue committed
29
 */
w  
Qiang Xue committed
30
class CompareValidator extends Validator
w  
Qiang Xue committed
31
{
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    /**
     * @var string the name of the attribute to be compared with. When both this property
     * and [[compareValue]] are set, the latter takes precedence. If neither is set,
     * it assumes the comparison is against another attribute whose name is formed by
     * appending '_repeat' to the attribute being validated. For example, if 'password' is
     * being validated, then the attribute to be compared would be 'password_repeat'.
     * @see compareValue
     */
    public $compareAttribute;
    /**
     * @var mixed the constant value to be compared with. When both this property
     * and [[compareAttribute]] are set, this property takes precedence.
     * @see compareAttribute
     */
    public $compareValue;
47 48 49 50 51 52 53
    /**
     * @var string the type of the values being compared. The follow types are supported:
     *
     * - string: the values are being compared as strings. No conversion will be done before comparison.
     * - number: the values are being compared as numbers. String values will be converted into numbers before comparison.
     */
    public $type = 'string';
54 55 56
    /**
     * @var string the operator for comparison. The following operators are supported:
     *
Qiang Xue committed
57 58 59 60 61 62 63 64
     * - `==`: check if two values are equal. The comparison is done is non-strict mode.
     * - `===`: check if two values are equal. The comparison is done is strict mode.
     * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
     * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
     * - `>`: check if value being validated is greater than the value being compared with.
     * - `>=`: check if value being validated is greater than or equal to the value being compared with.
     * - `<`: check if value being validated is less than the value being compared with.
     * - `<=`: check if value being validated is less than or equal to the value being compared with.
65 66 67 68 69 70 71 72 73 74 75 76
     */
    public $operator = '==';
    /**
     * @var string the user-defined error message. It may contain the following placeholders which
     * will be replaced accordingly by the validator:
     *
     * - `{attribute}`: the label of the attribute being validated
     * - `{value}`: the value of the attribute being validated
     * - `{compareValue}`: the value or the attribute label to be compared with
     * - `{compareAttribute}`: the label of the attribute to be compared with
     */
    public $message;
w  
Qiang Xue committed
77

78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if ($this->message === null) {
            switch ($this->operator) {
                case '==':
                    $this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
                    break;
                case '===':
                    $this->message = Yii::t('yii', '{attribute} must be repeated exactly.');
                    break;
                case '!=':
                    $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
                    break;
                case '!==':
                    $this->message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
                    break;
                case '>':
                    $this->message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
                    break;
                case '>=':
                    $this->message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".');
                    break;
                case '<':
                    $this->message = Yii::t('yii', '{attribute} must be less than "{compareValue}".');
                    break;
                case '<=':
                    $this->message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".');
                    break;
                default:
                    throw new InvalidConfigException("Unknown operator: {$this->operator}");
            }
        }
    }
Qiang Xue committed
116

117 118 119
    /**
     * @inheritdoc
     */
Qiang Xue committed
120
    public function validateAttribute($model, $attribute)
121
    {
Qiang Xue committed
122
        $value = $model->$attribute;
123
        if (is_array($value)) {
Qiang Xue committed
124
            $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
Qiang Xue committed
125

126 127 128 129 130 131
            return;
        }
        if ($this->compareValue !== null) {
            $compareLabel = $compareValue = $this->compareValue;
        } else {
            $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
Qiang Xue committed
132 133
            $compareValue = $model->$compareAttribute;
            $compareLabel = $model->getAttributeLabel($compareAttribute);
134
        }
w  
Qiang Xue committed
135

136
        if (!$this->compareValues($this->operator, $this->type, $value, $compareValue)) {
Qiang Xue committed
137
            $this->addError($model, $attribute, $this->message, [
138 139 140 141 142
                'compareAttribute' => $compareLabel,
                'compareValue' => $compareValue,
            ]);
        }
    }
w  
Qiang Xue committed
143

144 145 146 147 148 149 150 151
    /**
     * @inheritdoc
     */
    protected function validateValue($value)
    {
        if ($this->compareValue === null) {
            throw new InvalidConfigException('CompareValidator::compareValue must be set.');
        }
152
        if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
153 154 155 156 157 158 159 160
            return [$this->message, [
                'compareAttribute' => $this->compareValue,
                'compareValue' => $this->compareValue,
            ]];
        } else {
            return null;
        }
    }
Qiang Xue committed
161

162 163
    /**
     * Compares two values with the specified operator.
164
     * @param string $operator the comparison operator
165
     * @param string $type the type of the values being compared
166 167
     * @param mixed $value the value being compared
     * @param mixed $compareValue another value being compared
168 169
     * @return boolean whether the comparison using the specified operator is true.
     */
170
    protected function compareValues($operator, $type, $value, $compareValue)
171
    {
172
        if ($type === 'number') {
173 174
            $value = (float) $value;
            $compareValue = (float) $compareValue;
175 176 177 178
        } else {
            $value = (string) $value;
            $compareValue = (string) $compareValue;
        }
179
        switch ($operator) {
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
            case '==':
                return $value == $compareValue;
            case '===':
                return $value === $compareValue;
            case '!=':
                return $value != $compareValue;
            case '!==':
                return $value !== $compareValue;
            case '>':
                return $value > $compareValue;
            case '>=':
                return $value >= $compareValue;
            case '<':
                return $value < $compareValue;
            case '<=':
                return $value <= $compareValue;
            default:
                return false;
198 199
        }
    }
Qiang Xue committed
200

201 202 203
    /**
     * @inheritdoc
     */
Qiang Xue committed
204
    public function clientValidateAttribute($model, $attribute, $view)
205
    {
206 207 208 209
        $options = [
            'operator' => $this->operator,
            'type' => $this->type,
        ];
210

211 212 213 214 215
        if ($this->compareValue !== null) {
            $options['compareValue'] = $this->compareValue;
            $compareValue = $this->compareValue;
        } else {
            $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
Qiang Xue committed
216 217
            $compareValue = $model->getAttributeLabel($compareAttribute);
            $options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
218
        }
219

220 221 222
        if ($this->skipOnEmpty) {
            $options['skipOnEmpty'] = 1;
        }
223

224
        $options['message'] = Yii::$app->getI18n()->format($this->message, [
Qiang Xue committed
225
            'attribute' => $model->getAttributeLabel($attribute),
226 227 228
            'compareAttribute' => $compareValue,
            'compareValue' => $compareValue,
        ], Yii::$app->language);
w  
Qiang Xue committed
229

230 231
        ValidationAsset::register($view);

232
        return 'yii.validation.compare(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
233
    }
w  
Qiang Xue committed
234
}