CUniqueValidator.php 5.2 KB

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