UniqueValidator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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\ActiveRecord;
  12. use yii\db\ActiveQueryInterface;
  13. use yii\db\ActiveRecordInterface;
  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.
  64. *
  65. * When validating single attribute, it may contain
  66. * the following placeholders which will be replaced accordingly by the validator:
  67. *
  68. * - `{attribute}`: the label of the attribute being validated
  69. * - `{value}`: the value of the attribute being validated
  70. *
  71. * When validating mutliple attributes, it may contain the following placeholders:
  72. *
  73. * - `{attributes}`: the labels of the attributes being validated.
  74. * - `{values}`: the values of the attributes being validated.
  75. *
  76. */
  77. public $message;
  78. /**
  79. * @var string
  80. * @since 2.0.9
  81. * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
  82. * to setup custom message for multiple target attributes.
  83. */
  84. public $comboNotUnique;
  85. /**
  86. * @var string and|or define how target attributes are related
  87. * @since 2.0.11
  88. */
  89. public $targetAttributeJunction = 'and';
  90. /**
  91. * @inheritdoc
  92. */
  93. public function init()
  94. {
  95. parent::init();
  96. if ($this->message !== null) {
  97. return;
  98. }
  99. if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
  100. // fallback for deprecated `comboNotUnique` property - use it as message if is set
  101. if ($this->comboNotUnique === null) {
  102. $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
  103. } else {
  104. $this->message = $this->comboNotUnique;
  105. }
  106. } else {
  107. $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
  108. }
  109. }
  110. /**
  111. * @inheritdoc
  112. */
  113. public function validateAttribute($model, $attribute)
  114. {
  115. /* @var $targetClass ActiveRecordInterface */
  116. $targetClass = $this->getTargetClass($model);
  117. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  118. $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
  119. $conditions[] = $this->targetAttributeJunction === 'or' ? 'or' : 'and';
  120. foreach ($rawConditions as $key => $value) {
  121. if (is_array($value)) {
  122. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  123. return;
  124. }
  125. $conditions[] = [$key => $value];
  126. }
  127. if ($this->modelExists($targetClass, $conditions, $model)) {
  128. if (count($targetAttribute) > 1) {
  129. $this->addComboNotUniqueError($model, $attribute);
  130. } else {
  131. $this->addError($model, $attribute, $this->message);
  132. }
  133. }
  134. }
  135. /**
  136. * @param Model $model the data model to be validated
  137. * @return string Target class name
  138. */
  139. private function getTargetClass($model)
  140. {
  141. return $this->targetClass === null ? get_class($model) : $this->targetClass;
  142. }
  143. /**
  144. * Checks whether the $model exists in the database.
  145. *
  146. * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
  147. * of the current attribute value.
  148. * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
  149. * @param Model $model the data model to be validated
  150. *
  151. * @return bool whether the model already exists
  152. */
  153. private function modelExists($targetClass, $conditions, $model)
  154. {
  155. /** @var ActiveRecordInterface $targetClass $query */
  156. $query = $this->prepareQuery($targetClass, $conditions);
  157. if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
  158. // if current $model isn't in the database yet then it's OK just to call exists()
  159. // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
  160. $exists = $query->exists();
  161. } else {
  162. // if current $model is in the database already we can't use exists()
  163. if ($query instanceof \yii\db\ActiveQuery) {
  164. // only select primary key to optimize query
  165. $columnsCondition = array_flip($targetClass::primaryKey());
  166. $query->select(array_flip($this->applyTableAlias($query, $columnsCondition)));
  167. }
  168. $models = $query->limit(2)->asArray()->all();
  169. $n = count($models);
  170. if ($n === 1) {
  171. // if there is one record, check if it is the currently validated model
  172. $dbModel = reset($models);
  173. $pks = $targetClass::primaryKey();
  174. $pk = [];
  175. foreach ($pks as $pkAttribute) {
  176. $pk[$pkAttribute] = $dbModel[$pkAttribute];
  177. }
  178. $exists = ($pk != $model->getOldPrimaryKey(true));
  179. } else {
  180. // if there is more than one record, the value is not unique
  181. $exists = $n > 1;
  182. }
  183. }
  184. return $exists;
  185. }
  186. /**
  187. * Prepares a query by applying filtering conditions defined in $conditions method property
  188. * and [[filter]] class property.
  189. *
  190. * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
  191. * the uniqueness of the current attribute value.
  192. * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
  193. *
  194. * @return ActiveQueryInterface|ActiveQuery
  195. */
  196. private function prepareQuery($targetClass, $conditions)
  197. {
  198. $query = $targetClass::find();
  199. $query->andWhere($conditions);
  200. if ($this->filter instanceof \Closure) {
  201. call_user_func($this->filter, $query);
  202. } elseif ($this->filter !== null) {
  203. $query->andWhere($this->filter);
  204. }
  205. return $query;
  206. }
  207. /**
  208. * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
  209. * [[\yii\db\Query::where()|Query::where()]] key-value format.
  210. *
  211. * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
  212. * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
  213. * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
  214. * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
  215. * If the key and the value are the same, you can just specify the value.
  216. * @param Model $model the data model to be validated
  217. * @param string $attribute the name of the attribute to be validated in the $model
  218. *
  219. * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
  220. */
  221. private function prepareConditions($targetAttribute, $model, $attribute)
  222. {
  223. if (is_array($targetAttribute)) {
  224. $conditions = [];
  225. foreach ($targetAttribute as $k => $v) {
  226. $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
  227. }
  228. } else {
  229. $conditions = [$targetAttribute => $model->$attribute];
  230. }
  231. if (!$model instanceof ActiveRecord) {
  232. return $conditions;
  233. }
  234. return $this->prefixConditions($model, $conditions);
  235. }
  236. /**
  237. * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
  238. * @param \yii\base\Model $model the data model.
  239. * @param string $attribute the name of the attribute.
  240. */
  241. private function addComboNotUniqueError($model, $attribute)
  242. {
  243. $attributeCombo = [];
  244. $valueCombo = [];
  245. foreach ($this->targetAttribute as $key => $value) {
  246. if (is_int($key)) {
  247. $attributeCombo[] = $model->getAttributeLabel($value);
  248. $valueCombo[] = '"' . $model->$value . '"';
  249. } else {
  250. $attributeCombo[] = $model->getAttributeLabel($key);
  251. $valueCombo[] = '"' . $model->$key . '"';
  252. }
  253. }
  254. $this->addError($model, $attribute, $this->message, [
  255. 'attributes' => Inflector::sentence($attributeCombo),
  256. 'values' => implode('-', $valueCombo)
  257. ]);
  258. }
  259. /**
  260. * Returns conditions with alias
  261. * @param ActiveQuery $query
  262. * @param array $conditions array of condition, keys to be modified
  263. * @param null|string $alias set empty string for no apply alias. Set null for apply primary table alias
  264. * @return array
  265. */
  266. private function applyTableAlias($query, $conditions, $alias = null)
  267. {
  268. if ($alias === null) {
  269. $alias = array_keys($query->getTablesUsedInFrom())[0];
  270. }
  271. $prefixedConditions = [];
  272. foreach ($conditions as $columnName => $columnValue) {
  273. $prefixedColumn = "{$alias}.[[" . preg_replace(
  274. '/^' . preg_quote($alias) . '\.(.*)$/',
  275. "$1",
  276. $columnName) . "]]";
  277. $prefixedConditions[$prefixedColumn] = $columnValue;
  278. }
  279. return $prefixedConditions;
  280. }
  281. /**
  282. * Prefix conditions with aliases
  283. *
  284. * @param ActiveRecord $model
  285. * @param array $conditions
  286. * @return array
  287. */
  288. private function prefixConditions($model, $conditions)
  289. {
  290. $targetModelClass = $this->getTargetClass($model);
  291. /** @var ActiveRecord $targetModelClass */
  292. return $this->applyTableAlias($targetModelClass::find(), $conditions);
  293. }
  294. }