CompareValidator.php 7.06 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
/**
w  
Qiang Xue committed
15
 * CompareValidator compares the specified attribute value with another value and validates if they are equal.
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
{
	/**
Qiang Xue committed
33 34 35 36 37 38
	 * @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
w  
Qiang Xue committed
39 40 41
	 */
	public $compareAttribute;
	/**
Qiang Xue committed
42
	 * @var mixed the constant value to be compared with. When both this property
Qiang Xue committed
43 44
	 * and [[compareAttribute]] are set, this property takes precedence.
	 * @see compareAttribute
w  
Qiang Xue committed
45 46 47
	 */
	public $compareValue;
	/**
Qiang Xue committed
48 49 50 51 52 53
	 * @var string the operator for comparison. The following operators are supported:
	 *
	 * - '==': validates to see if the two values are equal. The comparison is done is non-strict mode.
	 * - '===': validates to see if the two values are equal. The comparison is done is strict mode.
	 * - '!=': validates to see if the two values are NOT equal. The comparison is done is non-strict mode.
	 * - '!==': validates to see if the two values are NOT equal. The comparison is done is strict mode.
Qiang Xue committed
54 55 56 57
	 * - `>`: validates to see if the value being validated is greater than the value being compared with.
	 * - `>=`: validates to see if the value being validated is greater than or equal to the value being compared with.
	 * - `<`: validates to see if the value being validated is less than the value being compared with.
	 * - `<=`: validates to see if the value being validated is less than or equal to the value being compared with.
w  
Qiang Xue committed
58
	 */
gsd committed
59
	public $operator = '==';
60 61 62 63 64 65 66
	/**
	 * @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
Qiang Xue committed
67
	 * - `{compareAttribute}`: the label of the attribute to be compared with
68 69
	 */
	public $message;
w  
Qiang Xue committed
70

Qiang Xue committed
71 72

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

w  
Qiang Xue committed
110
	/**
Qiang Xue committed
111
	 * @inheritdoc
w  
Qiang Xue committed
112
	 */
w  
Qiang Xue committed
113
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
114 115
	{
		$value = $object->$attribute;
Qiang Xue committed
116
		if (is_array($value)) {
117
			$this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
Qiang Xue committed
118 119
			return;
		}
w  
Qiang Xue committed
120
		if ($this->compareValue !== null) {
Qiang Xue committed
121
			$compareLabel = $compareValue = $this->compareValue;
Qiang Xue committed
122
		} else {
Qiang Xue committed
123
			$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
w  
Qiang Xue committed
124
			$compareValue = $object->$compareAttribute;
Qiang Xue committed
125
			$compareLabel = $object->getAttributeLabel($compareAttribute);
w  
Qiang Xue committed
126 127
		}

Qiang Xue committed
128
		if (!$this->compareValues($this->operator, $value, $compareValue)) {
Alexander Makarov committed
129
			$this->addError($object, $attribute, $this->message, [
130 131
				'compareAttribute' => $compareLabel,
				'compareValue' => $compareValue,
Alexander Makarov committed
132
			]);
w  
Qiang Xue committed
133 134 135
		}
	}

Qiang Xue committed
136
	/**
Qiang Xue committed
137
	 * @inheritdoc
Qiang Xue committed
138
	 */
Qiang Xue committed
139
	protected function validateValue($value)
Qiang Xue committed
140 141 142 143
	{
		if ($this->compareValue === null) {
			throw new InvalidConfigException('CompareValidator::compareValue must be set.');
		}
Qiang Xue committed
144 145 146 147 148 149 150 151 152
		if (!$this->compareValues($this->operator, $value, $this->compareValue)) {
			return [$this->message, [
				'compareAttribute' => $this->compareValue,
				'compareValue' => $this->compareValue,
			]];
		} else {
			return null;
		}
	}
Qiang Xue committed
153

Qiang Xue committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
	/**
	 * Compares two values with the specified operator.
	 * @param string $operator the comparison operator
	 * @param mixed $value the value being compared
	 * @param mixed $compareValue another value being compared
	 * @return boolean whether the comparison using the specified operator is true.
	 */
	protected function compareValues($operator, $value, $compareValue)
	{
		switch ($operator) {
			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;
172
			default: return false;
Qiang Xue committed
173 174 175
		}
	}

w  
Qiang Xue committed
176
	/**
Qiang Xue committed
177
	 * @inheritdoc
w  
Qiang Xue committed
178
	 */
179
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
180
	{
Alexander Makarov committed
181
		$options = ['operator' => $this->operator];
182

w  
Qiang Xue committed
183
		if ($this->compareValue !== null) {
184 185
			$options['compareValue'] = $this->compareValue;
			$compareValue = $this->compareValue;
Qiang Xue committed
186
		} else {
Qiang Xue committed
187
			$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
188 189
			$compareValue = $object->getAttributeLabel($compareAttribute);
			$options['compareAttribute'] = Html::getInputId($object, $compareAttribute);
w  
Qiang Xue committed
190
		}
191 192 193 194 195

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

196
		$options['message'] = Yii::$app->getI18n()->format($this->message, [
197 198 199
			'attribute' => $object->getAttributeLabel($attribute),
			'compareAttribute' => $compareValue,
			'compareValue' => $compareValue,
200
		], Yii::$app->language);
w  
Qiang Xue committed
201

202
		ValidationAsset::register($view);
203
		return 'yii.validation.compare(value, messages, ' . json_encode($options) . ');';
w  
Qiang Xue committed
204 205
	}
}