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.

165 lines
5.9KB

  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 values are the attributes that will be
  50. * used to validate the existence, while the array keys are the attributes whose values are to be validated.
  51. * If the key and the value are the same, you can just specify the value.
  52. */
  53. public $targetAttribute;
  54. /**
  55. * @var string|array|\Closure additional filter to be applied to the DB query used to check the existence of the attribute value.
  56. * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
  57. * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
  58. * is the [[\yii\db\Query|Query]] object that you can modify in the function.
  59. */
  60. public $filter;
  61. /**
  62. * @var boolean whether to allow array type attribute.
  63. */
  64. public $allowArray = false;
  65. /**
  66. * @inheritdoc
  67. */
  68. public function init()
  69. {
  70. parent::init();
  71. if ($this->message === null) {
  72. $this->message = Yii::t('yii', '{attribute} is invalid.');
  73. }
  74. }
  75. /**
  76. * @inheritdoc
  77. */
  78. public function validateAttribute($model, $attribute)
  79. {
  80. $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
  81. if (is_array($targetAttribute)) {
  82. if ($this->allowArray) {
  83. throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
  84. }
  85. $params = [];
  86. foreach ($targetAttribute as $k => $v) {
  87. $params[$v] = is_int($k) ? $model->$v : $model->$k;
  88. }
  89. } else {
  90. $params = [$targetAttribute => $model->$attribute];
  91. }
  92. if (!$this->allowArray) {
  93. foreach ($params as $value) {
  94. if (is_array($value)) {
  95. $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
  96. return;
  97. }
  98. }
  99. }
  100. $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
  101. $query = $this->createQuery($targetClass, $params);
  102. if (is_array($model->$attribute)) {
  103. if ($query->count("DISTINCT [[$targetAttribute]]") != count($model->$attribute)) {
  104. $this->addError($model, $attribute, $this->message);
  105. }
  106. } elseif (!$query->exists()) {
  107. $this->addError($model, $attribute, $this->message);
  108. }
  109. }
  110. /**
  111. * @inheritdoc
  112. */
  113. protected function validateValue($value)
  114. {
  115. if ($this->targetClass === null) {
  116. throw new InvalidConfigException('The "targetClass" property must be set.');
  117. }
  118. if (!is_string($this->targetAttribute)) {
  119. throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
  120. }
  121. $query = $this->createQuery($this->targetClass, [$this->targetAttribute => $value]);
  122. if (is_array($value)) {
  123. if (!$this->allowArray) {
  124. return [$this->message, []];
  125. }
  126. return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ? null : [$this->message, []];
  127. } else {
  128. return $query->exists() ? null : [$this->message, []];
  129. }
  130. }
  131. /**
  132. * Creates a query instance with the given condition.
  133. * @param string $targetClass the target AR class
  134. * @param mixed $condition query condition
  135. * @return \yii\db\ActiveQueryInterface the query instance
  136. */
  137. protected function createQuery($targetClass, $condition)
  138. {
  139. /* @var $targetClass \yii\db\ActiveRecordInterface */
  140. $query = $targetClass::find()->andWhere($condition);
  141. if ($this->filter instanceof \Closure) {
  142. call_user_func($this->filter, $query);
  143. } elseif ($this->filter !== null) {
  144. $query->andWhere($this->filter);
  145. }
  146. return $query;
  147. }
  148. }