ExistValidator.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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\InvalidConfigException;
  10. /**
  11. * ExistValidator validates that the attribute value exists in a table.
  12. *
  13. * ExistValidator checks if the value being validated can be found in the table column specified by
  14. * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
  15. *
  16. * This validator is often used to verify that a foreign key contains a value
  17. * that can be found in the foreign table.
  18. *
  19. * The following are examples of validation rules using this validator:
  20. *
  21. * ```php
  22. * // a1 needs to exist
  23. * ['a1', 'exist']
  24. * // a1 needs to exist, but its value will use a2 to check for the existence
  25. * ['a1', 'exist', 'targetAttribute' => 'a2']
  26. * // a1 and a2 need to exist together, and they both will receive error message
  27. * [['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']]
  28. * // a1 and a2 need to exist together, only a1 will receive error message
  29. * ['a1', 'exist', 'targetAttribute' => ['a1', 'a2']]
  30. * // a1 needs to exist by checking the existence of both a2 and a3 (using a1 value)
  31. * ['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']]
  32. * ```
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class ExistValidator extends Validator
  38. {
  39. /**
  40. * @var string the name of the ActiveRecord class that should be used to validate the existence
  41. * of the current attribute value. It not set, it will use the ActiveRecord class of the attribute being validated.
  42. * @see targetAttribute
  43. */
  44. public $targetClass;
  45. /**
  46. * @var string|array the name of the ActiveRecord attribute that should be used to
  47. * validate the existence of the current attribute value. If not set, it will use the name
  48. * of the attribute currently being validated. You may use an array to validate the existence
  49. * of multiple columns at the same time. The array key is the name of the attribute with the value to validate,
  50. * the array value is the name of the database field to search.
  51. */
  52. public $targetAttribute;
  53. /**
  54. * @var string|array|\Closure additional filter to be applied to the DB query used to check the existence of the attribute value.
  55. * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
  56. * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
  57. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
  58. */
  59. public $filter;
  60. /**
  61. * @var bool whether to allow array type attribute.
  62. */
  63. public $allowArray = false;
  64. /**
  65. * @var string and|or define how target attributes are related
  66. * @since 2.0.11
  67. */
  68. public $targetAttributeJunction = 'and';
  69. /**
  70. * @inheritdoc
  71. */
  72. public function init()
  73. {
  74. parent::init();
  75. if ($this->message === null) {
  76. $this->message = Yii::t('yii', '{attribute} is invalid.');
  77. }
  78. }
  79. /**
  80. * @inheritdoc
  81. */
  82. public function validateAttribute($model, $attribute)
  83. {
  84. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  85. $params = $this->prepareConditions($targetAttribute, $model, $attribute);
  86. $conditions[] = $this->targetAttributeJunction == 'or' ? 'or' : 'and';
  87. if (!$this->allowArray) {
  88. foreach ($params as $key => $value) {
  89. if (is_array($value)) {
  90. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  91. return;
  92. }
  93. $conditions[] = [$key => $value];
  94. }
  95. } else {
  96. $conditions[] = $params;
  97. }
  98. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  99. $query = $this->createQuery($targetClass, $conditions);
  100. if (is_array($model->$attribute)) {
  101. if ($query->count("DISTINCT [[$targetAttribute]]") != count($model->$attribute)) {
  102. $this->addError($model, $attribute, $this->message);
  103. }
  104. } elseif (!$query->exists()) {
  105. $this->addError($model, $attribute, $this->message);
  106. }
  107. }
  108. /**
  109. * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
  110. * [[\yii\db\Query::where()|Query::where()]] key-value format.
  111. *
  112. * @param $targetAttribute array|string $attribute the name of the ActiveRecord attribute that should be used to
  113. * validate the existence of the current attribute value. If not set, it will use the name
  114. * of the attribute currently being validated. You may use an array to validate the existence
  115. * of multiple columns at the same time. The array key is the name of the attribute with the value to validate,
  116. * the array value is the name of the database field to search.
  117. * @param \yii\base\Model $model the data model to be validated
  118. * @param string $attribute the name of the attribute to be validated in the $model
  119. * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
  120. * @throws InvalidConfigException
  121. */
  122. private function prepareConditions($targetAttribute, $model, $attribute)
  123. {
  124. if (is_array($targetAttribute)) {
  125. if ($this->allowArray) {
  126. throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
  127. }
  128. $params = [];
  129. foreach ($targetAttribute as $k => $v) {
  130. $params[$v] = is_int($k) ? $model->$attribute : $model->$k;
  131. }
  132. } else {
  133. $params = [$targetAttribute => $model->$attribute];
  134. }
  135. return $params;
  136. }
  137. /**
  138. * @inheritdoc
  139. */
  140. protected function validateValue($value)
  141. {
  142. if ($this->targetClass === null) {
  143. throw new InvalidConfigException('The "targetClass" property must be set.');
  144. }
  145. if (!is_string($this->targetAttribute)) {
  146. throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
  147. }
  148. $query = $this->createQuery($this->targetClass, [$this->targetAttribute => $value]);
  149. if (is_array($value)) {
  150. if (!$this->allowArray) {
  151. return [$this->message, []];
  152. }
  153. return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ? null : [$this->message, []];
  154. } else {
  155. return $query->exists() ? null : [$this->message, []];
  156. }
  157. }
  158. /**
  159. * Creates a query instance with the given condition.
  160. * @param string $targetClass the target AR class
  161. * @param mixed $condition query condition
  162. * @return \yii\db\ActiveQueryInterface the query instance
  163. */
  164. protected function createQuery($targetClass, $condition)
  165. {
  166. /* @var $targetClass \yii\db\ActiveRecordInterface */
  167. $query = $targetClass::find()->andWhere($condition);
  168. if ($this->filter instanceof \Closure) {
  169. call_user_func($this->filter, $query);
  170. } elseif ($this->filter !== null) {
  171. $query->andWhere($this->filter);
  172. }
  173. return $query;
  174. }
  175. }