UniqueValidator.php 3.46 KB
Newer Older
w  
Qiang Xue committed
1 2
<?php
/**
Alexander Makarov committed
3
 * UniqueValidator class file.
w  
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
w  
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
10 11
namespace yii\validators;

w  
Qiang Xue committed
12 13 14 15
/**
 * CUniqueValidator validates that the attribute value is unique in the corresponding database table.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Alexander Makarov committed
16
 * @since 2.0
w  
Qiang Xue committed
17
 */
Alexander Makarov committed
18
class UniqueValidator extends Validator
w  
Qiang Xue committed
19 20 21 22 23 24 25
{
	/**
	 * @var boolean whether the attribute value can be null or empty. Defaults to true,
	 * meaning that if the attribute is empty, it is considered valid.
	 */
	public $allowEmpty = true;
	/**
Qiang Xue committed
26
	 * @var string the yii\db\ActiveRecord class name or alias of the class
Alexander Makarov committed
27
	 * that should be used to look for the attribute value being validated.
Qiang Xue committed
28 29
	 * Defaults to null, meaning using the yii\db\ActiveRecord class of
	 * the attribute being validated.
w  
Qiang Xue committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	 * @see attributeName
	 */
	public $className;
	/**
	 * @var string the ActiveRecord class attribute name that should be
	 * used to look for the attribute value being validated. Defaults to null,
	 * meaning using the name of the attribute being validated.
	 */
	public $attributeName;
	/**
	 * @var string the user-defined error message. The placeholders "{attribute}" and "{value}"
	 * are recognized, which will be replaced with the actual attribute name and value, respectively.
	 */
	public $message;
	/**
	 * @var boolean whether this validation rule should be skipped if when there is already a validation
	 * error for the current attribute. Defaults to true.
	 */
	public $skipOnError = true;

	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
Qiang Xue committed
53
	 * @param \yii\db\ActiveRecord $object the object being validated
w  
Qiang Xue committed
54
	 * @param string $attribute the attribute being validated
Alexander Makarov committed
55
	 * @throws \yii\base\Exception if table doesn't have column specified
w  
Qiang Xue committed
56
	 */
w  
Qiang Xue committed
57
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
58 59
	{
		$value = $object->$attribute;
Alexander Makarov committed
60
		if ($this->allowEmpty && $this->isEmpty($value)) {
w  
Qiang Xue committed
61
			return;
Alexander Makarov committed
62 63
		}

Qiang Xue committed
64
		/** @var $className \yii\db\ActiveRecord */
Alexander Makarov committed
65 66
		$className = ($this->className === null) ? get_class($object) : \Yii::import($this->className);
		$attributeName = ($this->attributeName === null) ? $attribute : $this->attributeName;
w  
Qiang Xue committed
67

Qiang Xue committed
68
		$table = $className::getTableSchema();
Alexander Makarov committed
69 70 71
		if (($column = $table->getColumn($attributeName)) === null) {
			throw new \yii\base\Exception('Table "' . $table->name . '" does not have a column named "' . $attributeName . '"');
		}
w  
Qiang Xue committed
72

Qiang Xue committed
73
		$query = $className::find();
Qiang Xue committed
74
		$query->where(array($column->name => $value));
Alexander Makarov committed
75 76 77 78

		if ($object->getIsNewRecord()) {
			// if current $object isn't in the database yet then it's OK just
			// to call exists()
Qiang Xue committed
79
			$exists = $query->exists();
Alexander Makarov committed
80 81
		} else {
			// if current $object is in the database already we can't use exists()
Qiang Xue committed
82 83
			$query->limit(2);
			$objects = $query->all();
w  
Qiang Xue committed
84 85

			$n = count($objects);
Alexander Makarov committed
86 87 88
			if ($n === 1) {
				if ($column->isPrimaryKey) {
					// primary key is modified and not unique
w  
Qiang Xue committed
89
					$exists = $object->getOldPrimaryKey() != $object->getPrimaryKey();
Alexander Makarov committed
90
				} else {
w  
Qiang Xue committed
91 92 93
					// non-primary key, need to exclude the current record based on PK
					$exists = array_shift($objects)->getPrimaryKey() != $object->getOldPrimaryKey();
				}
Alexander Makarov committed
94
			} else {
w  
Qiang Xue committed
95
				$exists = $n > 1;
Alexander Makarov committed
96
			}
w  
Qiang Xue committed
97 98
		}

Alexander Makarov committed
99 100
		if ($exists) {
			$message = ($this->message !== null) ? $this->message : \Yii::t('yii', '{attribute} "{value}" has already been taken.');
w  
Qiang Xue committed
101 102 103
			$this->addError($object, $attribute, $message, array('{value}' => $value));
		}
	}
Alexander Makarov committed
104
}