1: <?php
2: /**
3: * CUniqueValidator class file.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CUniqueValidator validates that the attribute value is unique in the corresponding database table.
13: *
14: * When using the {@link message} property to define a custom error message, the message
15: * may contain additional placeholders that will be replaced with the actual content. In addition
16: * to the "{attribute}" placeholder, recognized by all validators (see {@link CValidator}),
17: * CUniqueValidator allows for the following placeholders to be specified:
18: * <ul>
19: * <li>{value}: replaced with current value of the attribute.</li>
20: * </ul>
21: *
22: * @author Qiang Xue <qiang.xue@gmail.com>
23: * @package system.validators
24: * @since 1.0
25: */
26: class CUniqueValidator extends CValidator
27: {
28: /**
29: * @var boolean whether the comparison is case sensitive. Defaults to true.
30: * Note, by setting it to false, you are assuming the attribute type is string.
31: */
32: public $caseSensitive=true;
33: /**
34: * @var boolean whether the attribute value can be null or empty. Defaults to true,
35: * meaning that if the attribute is empty, it is considered valid.
36: */
37: public $allowEmpty=true;
38: /**
39: * @var string the ActiveRecord class name that should be used to
40: * look for the attribute value being validated. Defaults to null, meaning using
41: * the class of the object currently being validated.
42: * You may use path alias to reference a class name here.
43: * @see attributeName
44: */
45: public $className;
46: /**
47: * @var string the ActiveRecord class attribute name that should be
48: * used to look for the attribute value being validated. Defaults to null,
49: * meaning using the name of the attribute being validated.
50: * @see className
51: */
52: public $attributeName;
53: /**
54: * @var mixed additional query criteria. Either an array or CDbCriteria.
55: * This will be combined with the condition that checks if the attribute
56: * value exists in the corresponding table column.
57: * This array will be used to instantiate a {@link CDbCriteria} object.
58: */
59: public $criteria=array();
60: /**
61: * @var string the user-defined error message. The placeholders "{attribute}" and "{value}"
62: * are recognized, which will be replaced with the actual attribute name and value, respectively.
63: */
64: public $message;
65: /**
66: * @var boolean whether this validation rule should be skipped if when there is already a validation
67: * error for the current attribute. Defaults to true.
68: * @since 1.1.1
69: */
70: public $skipOnError=true;
71:
72:
73: /**
74: * Validates the attribute of the object.
75: * If there is any error, the error message is added to the object.
76: * @param CModel $object the object being validated
77: * @param string $attribute the attribute being validated
78: * @throws CException if given table does not have specified column name
79: */
80: protected function validateAttribute($object,$attribute)
81: {
82: $value=$object->$attribute;
83: if($this->allowEmpty && $this->isEmpty($value))
84: return;
85:
86: if(is_array($value))
87: {
88: // https://github.com/yiisoft/yii/issues/1955
89: $this->addError($object,$attribute,Yii::t('yii','{attribute} is invalid.'));
90: return;
91: }
92:
93: $className=$this->className===null?get_class($object):Yii::import($this->className);
94: $attributeName=$this->attributeName===null?$attribute:$this->attributeName;
95: $finder=$this->getModel($className);
96: $table=$finder->getTableSchema();
97: if(($column=$table->getColumn($attributeName))===null)
98: throw new CException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
99: array('{column}'=>$attributeName,'{table}'=>$table->name)));
100:
101: $columnName=$column->rawName;
102: $criteria=new CDbCriteria();
103: if($this->criteria!==array())
104: $criteria->mergeWith($this->criteria);
105: $tableAlias = empty($criteria->alias) ? $finder->getTableAlias(true) : $criteria->alias;
106: $valueParamName = CDbCriteria::PARAM_PREFIX.CDbCriteria::$paramCount++;
107: $criteria->addCondition($this->caseSensitive ? "{$tableAlias}.{$columnName}={$valueParamName}" : "LOWER({$tableAlias}.{$columnName})=LOWER({$valueParamName})");
108: $criteria->params[$valueParamName] = $value;
109:
110: if(!$object instanceof CActiveRecord || $object->isNewRecord || $object->tableName()!==$finder->tableName())
111: $exists=$finder->exists($criteria);
112: else
113: {
114: $criteria->limit=2;
115: $objects=$finder->findAll($criteria);
116: $n=count($objects);
117: if($n===1)
118: {
119: if($column->isPrimaryKey) // primary key is modified and not unique
120: $exists=$object->getOldPrimaryKey()!=$object->getPrimaryKey();
121: else
122: {
123: // non-primary key, need to exclude the current record based on PK
124: $exists=array_shift($objects)->getPrimaryKey()!=$object->getOldPrimaryKey();
125: }
126: }
127: else
128: $exists=$n>1;
129: }
130:
131: if($exists)
132: {
133: $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} "{value}" has already been taken.');
134: $this->addError($object,$attribute,$message,array('{value}'=>CHtml::encode($value)));
135: }
136: }
137:
138: /**
139: * Given active record class name returns new model instance.
140: *
141: * @param string $className active record class name.
142: * @return CActiveRecord active record model instance.
143: *
144: * @since 1.1.14
145: */
146: protected function getModel($className)
147: {
148: return CActiveRecord::model($className);
149: }
150: }
151:
152: