您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UniqueValidator.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. When validating single attribute, it may contain
  61. * the following placeholders which will be replaced accordingly by the validator:
  62. *
  63. * - `{attribute}`: the label of the attribute being validated
  64. * - `{value}`: the value of the attribute being validated
  65. *
  66. * When validating mutliple attributes, it may contain the following placeholders:
  67. *
  68. * - `{attributes}`: the labels of the attributes being validated.
  69. * - `{values}`: the values of the attributes being validated.
  70. *
  71. */
  72. public $message;
  73. /**
  74. * @var string
  75. * @since 2.0.9
  76. * @deprecated Deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
  77. * to setup custom message for multiple target attributes.
  78. */
  79. public $comboNotUnique;
  80. /**
  81. * @inheritdoc
  82. */
  83. public function init()
  84. {
  85. parent::init();
  86. if ($this->message !== null) {
  87. return;
  88. }
  89. if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
  90. // fallback for deprecated `comboNotUnique` property - use it as message if is set
  91. if ($this->comboNotUnique === null) {
  92. $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
  93. } else {
  94. $this->message = $this->comboNotUnique;
  95. }
  96. } else {
  97. $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
  98. }
  99. }
  100. /**
  101. * @inheritdoc
  102. */
  103. public function validateAttribute($model, $attribute)
  104. {
  105. /* @var $targetClass ActiveRecordInterface */
  106. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  107. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  108. if (is_array($targetAttribute)) {
  109. $params = [];
  110. foreach ($targetAttribute as $k => $v) {
  111. $params[$v] = is_int($k) ? $model->$v : $model->$k;
  112. }
  113. } else {
  114. $params = [$targetAttribute => $model->$attribute];
  115. }
  116. foreach ($params as $value) {
  117. if (is_array($value)) {
  118. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  119. return;
  120. }
  121. }
  122. $query = $targetClass::find();
  123. $query->andWhere($params);
  124. if ($this->filter instanceof \Closure) {
  125. call_user_func($this->filter, $query);
  126. } elseif ($this->filter !== null) {
  127. $query->andWhere($this->filter);
  128. }
  129. if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
  130. // if current $model isn't in the database yet then it's OK just to call exists()
  131. // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
  132. $exists = $query->exists();
  133. } else {
  134. // if current $model is in the database already we can't use exists()
  135. /* @var $models ActiveRecordInterface[] */
  136. $models = $query->limit(2)->all();
  137. $n = count($models);
  138. if ($n === 1) {
  139. $keys = array_keys($params);
  140. $pks = $targetClass::primaryKey();
  141. sort($keys);
  142. sort($pks);
  143. if ($keys === $pks) {
  144. // primary key is modified and not unique
  145. $exists = $model->getOldPrimaryKey() != $model->getPrimaryKey();
  146. } else {
  147. // non-primary key, need to exclude the current record based on PK
  148. $exists = reset($models)->getPrimaryKey() != $model->getOldPrimaryKey();
  149. }
  150. } else {
  151. $exists = $n > 1;
  152. }
  153. }
  154. if ($exists) {
  155. if (count($targetAttribute) > 1) {
  156. $this->addComboNotUniqueError($model, $attribute);
  157. } else {
  158. $this->addError($model, $attribute, $this->message);
  159. }
  160. }
  161. }
  162. /**
  163. * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
  164. * @param \yii\base\Model $model the data model.
  165. * @param string $attribute the name of the attribute.
  166. */
  167. private function addComboNotUniqueError($model, $attribute)
  168. {
  169. $attributeCombo = [];
  170. $valueCombo = [];
  171. foreach ($this->targetAttribute as $key => $value) {
  172. if(is_int($key)) {
  173. $attributeCombo[] = $model->getAttributeLabel($value);
  174. $valueCombo[] = '"' . $model->$value . '"';
  175. } else {
  176. $attributeCombo[] = $model->getAttributeLabel($key);
  177. $valueCombo[] = '"' . $model->$key . '"';
  178. }
  179. }
  180. $this->addError($model, $attribute, $this->message, [
  181. 'attributes' => Inflector::sentence($attributeCombo),
  182. 'values' => implode('-', $valueCombo)
  183. ]);
  184. }
  185. }