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.

139 line
5.2KB

  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. /**
  11. * UniqueValidator validates that the attribute value is unique in the specified database table.
  12. *
  13. * UniqueValidator checks if the value being validated is unique in the table column specified by
  14. * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
  15. *
  16. * The followings are examples of validation rules using this validator:
  17. *
  18. * ```php
  19. * // a1 needs to be unique
  20. * ['a1', 'unique']
  21. * // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
  22. * ['a1', 'unique', 'targetAttribute' => 'a2']
  23. * // a1 and a2 need to be unique together, and they both will receive error message
  24. * [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
  25. * // a1 and a2 need to be unique together, only a1 will receive error message
  26. * ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
  27. * // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
  28. * ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
  29. * ```
  30. *
  31. * @author Qiang Xue <qiang.xue@gmail.com>
  32. * @since 2.0
  33. */
  34. class UniqueValidator extends Validator
  35. {
  36. /**
  37. * @var string the name of the ActiveRecord class that should be used to validate the uniqueness
  38. * of the current attribute value. If not set, it will use the ActiveRecord class of the attribute being validated.
  39. * @see targetAttribute
  40. */
  41. public $targetClass;
  42. /**
  43. * @var string|array the name of the ActiveRecord attribute that should be used to
  44. * validate the uniqueness of the current attribute value. If not set, it will use the name
  45. * of the attribute currently being validated. You may use an array to validate the uniqueness
  46. * of multiple columns at the same time. The array values are the attributes that will be
  47. * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
  48. * If the key and the value are the same, you can just specify the value.
  49. */
  50. public $targetAttribute;
  51. /**
  52. * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
  53. * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
  54. * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
  55. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
  56. */
  57. public $filter;
  58. /**
  59. * @inheritdoc
  60. */
  61. public function init()
  62. {
  63. parent::init();
  64. if ($this->message === null) {
  65. $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
  66. }
  67. }
  68. /**
  69. * @inheritdoc
  70. */
  71. public function validateAttribute($model, $attribute)
  72. {
  73. /* @var $targetClass ActiveRecordInterface */
  74. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  75. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  76. if (is_array($targetAttribute)) {
  77. $params = [];
  78. foreach ($targetAttribute as $k => $v) {
  79. $params[$v] = is_integer($k) ? $model->$v : $model->$k;
  80. }
  81. } else {
  82. $params = [$targetAttribute => $model->$attribute];
  83. }
  84. foreach ($params as $value) {
  85. if (is_array($value)) {
  86. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  87. return;
  88. }
  89. }
  90. $query = $targetClass::find();
  91. $query->andWhere($params);
  92. if ($this->filter instanceof \Closure) {
  93. call_user_func($this->filter, $query);
  94. } elseif ($this->filter !== null) {
  95. $query->andWhere($this->filter);
  96. }
  97. if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord()) {
  98. // if current $model isn't in the database yet then it's OK just to call exists()
  99. $exists = $query->exists();
  100. } else {
  101. // if current $model is in the database already we can't use exists()
  102. /* @var $models ActiveRecordInterface[] */
  103. $models = $query->limit(2)->all();
  104. $n = count($models);
  105. if ($n === 1) {
  106. $keys = array_keys($params);
  107. $pks = $targetClass::primaryKey();
  108. sort($keys);
  109. sort($pks);
  110. if ($keys === $pks) {
  111. // primary key is modified and not unique
  112. $exists = $model->getOldPrimaryKey() != $model->getPrimaryKey();
  113. } else {
  114. // non-primary key, need to exclude the current record based on PK
  115. $exists = $models[0]->getPrimaryKey() != $model->getOldPrimaryKey();
  116. }
  117. } else {
  118. $exists = $n > 1;
  119. }
  120. }
  121. if ($exists) {
  122. $this->addError($model, $attribute, $this->message);
  123. }
  124. }
  125. }