UniqueValidator.php 14 KB

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