You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 line
7.0KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\db\ActiveRecordInterface;
  10. use yii\helpers\Inflector;
  11. /**
  12. * UniqueValidator validates that the attribute value is unique in the specified database table.
  13. *
  14. * UniqueValidator checks if the value being validated is unique in the table column specified by
  15. * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
  16. *
  17. * The following are examples of validation rules using this validator:
  18. *
  19. * ```php
  20. * // a1 needs to be unique
  21. * ['a1', 'unique']
  22. * // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
  23. * ['a1', 'unique', 'targetAttribute' => 'a2']
  24. * // a1 and a2 need to be unique together, and they both will receive error message
  25. * [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
  26. * // a1 and a2 need to be unique together, only a1 will receive error message
  27. * ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
  28. * // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
  29. * ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
  30. * ```
  31. *
  32. * @author Qiang Xue <qiang.xue@gmail.com>
  33. * @since 2.0
  34. */
  35. class UniqueValidator extends Validator
  36. {
  37. /**
  38. * @var string the name of the ActiveRecord class that should be used to validate the uniqueness
  39. * of the current attribute value. If not set, it will use the ActiveRecord class of the attribute being validated.
  40. * @see targetAttribute
  41. */
  42. public $targetClass;
  43. /**
  44. * @var string|array the name of the ActiveRecord attribute that should be used to
  45. * validate the uniqueness of the current attribute value. If not set, it will use the name
  46. * of the attribute currently being validated. You may use an array to validate the uniqueness
  47. * of multiple columns at the same time. The array values are the attributes that will be
  48. * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
  49. * If the key and the value are the same, you can just specify the value.
  50. */
  51. public $targetAttribute;
  52. /**
  53. * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
  54. * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
  55. * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
  56. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
  57. */
  58. public $filter;
  59. /**
  60. * @var string the user-defined error message used when [[targetAttribute]] is an array. It may contain the following placeholders:
  61. *
  62. * - `{attributes}`: the labels of the attributes being validated.
  63. * - `{values}`: the values of the attributes being validated.
  64. *
  65. * @since 2.0.9
  66. */
  67. public $comboNotUnique;
  68. /**
  69. * @inheritdoc
  70. */
  71. public function init()
  72. {
  73. parent::init();
  74. if ($this->message === null) {
  75. $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
  76. }
  77. if ($this->comboNotUnique === null) {
  78. $this->comboNotUnique = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
  79. }
  80. }
  81. /**
  82. * @inheritdoc
  83. */
  84. public function validateAttribute($model, $attribute)
  85. {
  86. /* @var $targetClass ActiveRecordInterface */
  87. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  88. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  89. if (is_array($targetAttribute)) {
  90. $params = [];
  91. foreach ($targetAttribute as $k => $v) {
  92. $params[$v] = is_int($k) ? $model->$v : $model->$k;
  93. }
  94. } else {
  95. $params = [$targetAttribute => $model->$attribute];
  96. }
  97. foreach ($params as $value) {
  98. if (is_array($value)) {
  99. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  100. return;
  101. }
  102. }
  103. $query = $targetClass::find();
  104. $query->andWhere($params);
  105. if ($this->filter instanceof \Closure) {
  106. call_user_func($this->filter, $query);
  107. } elseif ($this->filter !== null) {
  108. $query->andWhere($this->filter);
  109. }
  110. if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
  111. // if current $model isn't in the database yet then it's OK just to call exists()
  112. // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
  113. $exists = $query->exists();
  114. } else {
  115. // if current $model is in the database already we can't use exists()
  116. /* @var $models ActiveRecordInterface[] */
  117. $models = $query->limit(2)->all();
  118. $n = count($models);
  119. if ($n === 1) {
  120. $keys = array_keys($params);
  121. $pks = $targetClass::primaryKey();
  122. sort($keys);
  123. sort($pks);
  124. if ($keys === $pks) {
  125. // primary key is modified and not unique
  126. $exists = $model->getOldPrimaryKey() != $model->getPrimaryKey();
  127. } else {
  128. // non-primary key, need to exclude the current record based on PK
  129. $exists = $models[0]->getPrimaryKey() != $model->getOldPrimaryKey();
  130. }
  131. } else {
  132. $exists = $n > 1;
  133. }
  134. }
  135. if ($exists) {
  136. if (count($targetAttribute) > 1) {
  137. $this->addComboNotUniqueError($model, $attribute);
  138. } else {
  139. $this->addError($model, $attribute, $this->message);
  140. }
  141. }
  142. }
  143. /**
  144. * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
  145. * @param \yii\base\Model $model the data model.
  146. * @param string $attribute the name of the attribute.
  147. */
  148. private function addComboNotUniqueError($model, $attribute)
  149. {
  150. $attributeCombo = [];
  151. $valueCombo = [];
  152. foreach ($this->targetAttribute as $key => $value) {
  153. if(is_int($key)) {
  154. $attributeCombo[] = $model->getAttributeLabel($value);
  155. $valueCombo[] = '"' . $model->$value . '"';
  156. } else {
  157. $attributeCombo[] = $model->getAttributeLabel($key);
  158. $valueCombo[] = '"' . $model->$key . '"';
  159. }
  160. }
  161. $this->addError($model, $attribute, $this->comboNotUnique, [
  162. 'attributes' => Inflector::sentence($attributeCombo),
  163. 'values' => implode('-', $valueCombo)
  164. ]);
  165. }
  166. }