|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- <?php
-
-
- namespace yii\validators;
-
- use Yii;
- use yii\base\InvalidConfigException;
-
-
- class ExistValidator extends Validator
- {
-
-
- public $targetClass;
-
-
- public $targetAttribute;
-
-
- public $filter;
-
-
- public $allowArray = false;
-
-
-
-
- public function init()
- {
- parent::init();
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} is invalid.');
- }
- }
-
-
-
- public function validateAttribute($model, $attribute)
- {
- $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
-
- if (is_array($targetAttribute)) {
- if ($this->allowArray) {
- throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
- }
- $params = [];
- foreach ($targetAttribute as $k => $v) {
- $params[$v] = is_int($k) ? $model->$v : $model->$k;
- }
- } else {
- $params = [$targetAttribute => $model->$attribute];
- }
-
- if (!$this->allowArray) {
- foreach ($params as $value) {
- if (is_array($value)) {
- $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
-
- return;
- }
- }
- }
-
- $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
- $query = $this->createQuery($targetClass, $params);
-
- if (is_array($model->$attribute)) {
- if ($query->count("DISTINCT [[$targetAttribute]]") != count($model->$attribute)) {
- $this->addError($model, $attribute, $this->message);
- }
- } elseif (!$query->exists()) {
- $this->addError($model, $attribute, $this->message);
- }
- }
-
-
-
- protected function validateValue($value)
- {
- if ($this->targetClass === null) {
- throw new InvalidConfigException('The "targetClass" property must be set.');
- }
- if (!is_string($this->targetAttribute)) {
- throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
- }
-
- $query = $this->createQuery($this->targetClass, [$this->targetAttribute => $value]);
-
- if (is_array($value)) {
- if (!$this->allowArray) {
- return [$this->message, []];
- }
- return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ? null : [$this->message, []];
- } else {
- return $query->exists() ? null : [$this->message, []];
- }
- }
-
-
-
- protected function createQuery($targetClass, $condition)
- {
-
- $query = $targetClass::find()->andWhere($condition);
- if ($this->filter instanceof \Closure) {
- call_user_func($this->filter, $query);
- } elseif ($this->filter !== null) {
- $query->andWhere($this->filter);
- }
-
- return $query;
- }
- }
|