UniqueValidator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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\base\Model;
  10. use yii\db\ActiveQuery;
  11. use yii\db\ActiveQueryInterface;
  12. use yii\db\ActiveRecordInterface;
  13. use yii\db\Query;
  14. use yii\helpers\Inflector;
  15. /**
  16. * UniqueValidator validates that the attribute value is unique in the specified database table.
  17. *
  18. * UniqueValidator checks if the value being validated is unique in the table column specified by
  19. * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
  20. *
  21. * The following are examples of validation rules using this validator:
  22. *
  23. * ```php
  24. * // a1 needs to be unique
  25. * ['a1', 'unique']
  26. * // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
  27. * ['a1', 'unique', 'targetAttribute' => 'a2']
  28. * // a1 and a2 need to be unique together, and they both will receive error message
  29. * [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
  30. * // a1 and a2 need to be unique together, only a1 will receive error message
  31. * ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
  32. * // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
  33. * ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
  34. * ```
  35. *
  36. * @author Qiang Xue <qiang.xue@gmail.com>
  37. * @since 2.0
  38. */
  39. class UniqueValidator extends Validator
  40. {
  41. /**
  42. * @var string the name of the ActiveRecord class that should be used to validate the uniqueness
  43. * of the current attribute value. If not set, it will use the ActiveRecord class of the attribute being validated.
  44. * @see targetAttribute
  45. */
  46. public $targetClass;
  47. /**
  48. * @var string|array the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that should be used to
  49. * validate the uniqueness of the current attribute value. If not set, it will use the name
  50. * of the attribute currently being validated. You may use an array to validate the uniqueness
  51. * of multiple columns at the same time. The array values are the attributes that will be
  52. * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
  53. */
  54. public $targetAttribute;
  55. /**
  56. * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
  57. * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
  58. * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
  59. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
  60. */
  61. public $filter;
  62. /**
  63. * @var string the user-defined error message. When validating single attribute, it may contain
  64. * the following placeholders which will be replaced accordingly by the validator:
  65. *
  66. * - `{attribute}`: the label of the attribute being validated
  67. * - `{value}`: the value of the attribute being validated
  68. *
  69. * When validating mutliple attributes, it may contain the following placeholders:
  70. *
  71. * - `{attributes}`: the labels of the attributes being validated.
  72. * - `{values}`: the values of the attributes being validated.
  73. *
  74. */
  75. public $message;
  76. /**
  77. * @var string
  78. * @since 2.0.9
  79. * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
  80. * to setup custom message for multiple target attributes.
  81. */
  82. public $comboNotUnique;
  83. /**
  84. * @var string and|or define how target attributes are related
  85. * @since 2.0.11
  86. */
  87. public $targetAttributeJunction = 'and';
  88. /**
  89. * @inheritdoc
  90. */
  91. public function init()
  92. {
  93. parent::init();
  94. if ($this->message !== null) {
  95. return;
  96. }
  97. if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
  98. // fallback for deprecated `comboNotUnique` property - use it as message if is set
  99. if ($this->comboNotUnique === null) {
  100. $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
  101. } else {
  102. $this->message = $this->comboNotUnique;
  103. }
  104. } else {
  105. $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
  106. }
  107. }
  108. /**
  109. * @inheritdoc
  110. */
  111. public function validateAttribute($model, $attribute)
  112. {
  113. /* @var $targetClass ActiveRecordInterface */
  114. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  115. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  116. $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
  117. $conditions[] = $this->targetAttributeJunction === 'or' ? 'or' : 'and';
  118. foreach ($rawConditions as $key => $value) {
  119. if (is_array($value)) {
  120. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  121. return;
  122. }
  123. $conditions[] = [$key => $value];
  124. }
  125. if ($this->modelExists($targetClass, $conditions, $model)) {
  126. if (count($targetAttribute) > 1) {
  127. $this->addComboNotUniqueError($model, $attribute);
  128. } else {
  129. $this->addError($model, $attribute, $this->message);
  130. }
  131. }
  132. }
  133. /**
  134. * Checks whether the $model exists in the database.
  135. *
  136. * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
  137. * of the current attribute value.
  138. * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
  139. * @param Model $model the data model to be validated
  140. *
  141. * @return bool whether the model already exists
  142. */
  143. private function modelExists($targetClass, $conditions, $model)
  144. {
  145. /** @var ActiveRecordInterface $targetClass $query */
  146. $query = $this->prepareQuery($targetClass, $conditions);
  147. if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
  148. // if current $model isn't in the database yet then it's OK just to call exists()
  149. // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
  150. $exists = $query->exists();
  151. } else {
  152. // if current $model is in the database already we can't use exists()
  153. if ($query instanceof \yii\db\ActiveQuery) {
  154. // only select primary key to optimize query
  155. $query->select($targetClass::primaryKey());
  156. }
  157. $models = $query->limit(2)->asArray()->all();
  158. $n = count($models);
  159. if ($n === 1) {
  160. // if there is one record, check if it is the currently validated model
  161. $dbModel = reset($models);
  162. $pks = $targetClass::primaryKey();
  163. $pk = [];
  164. foreach($pks as $pkAttribute) {
  165. $pk[$pkAttribute] = $dbModel[$pkAttribute];
  166. }
  167. $exists = ($pk != $model->getOldPrimaryKey(true));
  168. } else {
  169. // if there is more than one record, the value is not unique
  170. $exists = $n > 1;
  171. }
  172. }
  173. return $exists;
  174. }
  175. /**
  176. * Prepares a query by applying filtering conditions defined in $conditions method property
  177. * and [[filter]] class property.
  178. *
  179. * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
  180. * the uniqueness of the current attribute value.
  181. * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
  182. *
  183. * @return ActiveQueryInterface|ActiveQuery
  184. */
  185. private function prepareQuery($targetClass, $conditions)
  186. {
  187. $query = $targetClass::find();
  188. $query->andWhere($conditions);
  189. if ($this->filter instanceof \Closure) {
  190. call_user_func($this->filter, $query);
  191. } elseif ($this->filter !== null) {
  192. $query->andWhere($this->filter);
  193. }
  194. return $query;
  195. }
  196. /**
  197. * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
  198. * [[\yii\db\Query::where()|Query::where()]] key-value format.
  199. *
  200. * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
  201. * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
  202. * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
  203. * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
  204. * If the key and the value are the same, you can just specify the value.
  205. * @param Model $model the data model to be validated
  206. * @param string $attribute the name of the attribute to be validated in the $model
  207. *
  208. * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
  209. */
  210. private function prepareConditions($targetAttribute, $model, $attribute)
  211. {
  212. if (is_array($targetAttribute)) {
  213. $conditions = [];
  214. foreach ($targetAttribute as $k => $v) {
  215. $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
  216. }
  217. } else {
  218. $conditions = [$targetAttribute => $model->$attribute];
  219. }
  220. return $conditions;
  221. }
  222. /**
  223. * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
  224. * @param \yii\base\Model $model the data model.
  225. * @param string $attribute the name of the attribute.
  226. */
  227. private function addComboNotUniqueError($model, $attribute)
  228. {
  229. $attributeCombo = [];
  230. $valueCombo = [];
  231. foreach ($this->targetAttribute as $key => $value) {
  232. if(is_int($key)) {
  233. $attributeCombo[] = $model->getAttributeLabel($value);
  234. $valueCombo[] = '"' . $model->$value . '"';
  235. } else {
  236. $attributeCombo[] = $model->getAttributeLabel($key);
  237. $valueCombo[] = '"' . $model->$key . '"';
  238. }
  239. }
  240. $this->addError($model, $attribute, $this->message, [
  241. 'attributes' => Inflector::sentence($attributeCombo),
  242. 'values' => implode('-', $valueCombo)
  243. ]);
  244. }
  245. }