123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337 |
- <?php
- namespace yii\validators;
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\base\Model;
- use yii\db\ActiveQuery;
- use yii\db\ActiveRecord;
- use yii\db\QueryInterface;
- class ExistValidator extends Validator
- {
-
- public $targetClass;
-
- public $targetAttribute;
-
- public $targetRelation;
-
- public $filter;
-
- public $allowArray = false;
-
- public $targetAttributeJunction = 'and';
-
- public $forceMasterDb = true;
-
- public function init()
- {
- parent::init();
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} is invalid.');
- }
- }
-
- public function validateAttribute($model, $attribute)
- {
- if (!empty($this->targetRelation)) {
- $this->checkTargetRelationExistence($model, $attribute);
- } else {
- $this->checkTargetAttributeExistence($model, $attribute);
- }
- }
-
- private function checkTargetRelationExistence($model, $attribute)
- {
- $exists = false;
-
- $relationQuery = $model->{'get' . ucfirst($this->targetRelation)}();
- if ($this->filter instanceof \Closure) {
- call_user_func($this->filter, $relationQuery);
- } elseif ($this->filter !== null) {
- $relationQuery->andWhere($this->filter);
- }
- if ($this->forceMasterDb && method_exists($model::getDb(), 'useMaster')) {
- $model::getDb()->useMaster(function() use ($relationQuery, &$exists) {
- $exists = $relationQuery->exists();
- });
- } else {
- $exists = $relationQuery->exists();
- }
- if (!$exists) {
- $this->addError($model, $attribute, $this->message);
- }
- }
-
- private function checkTargetAttributeExistence($model, $attribute)
- {
- $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
- $params = $this->prepareConditions($targetAttribute, $model, $attribute);
- $conditions = [$this->targetAttributeJunction == 'or' ? 'or' : 'and'];
- if (!$this->allowArray) {
- foreach ($params as $key => $value) {
- if (is_array($value)) {
- $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
- return;
- }
- $conditions[] = [$key => $value];
- }
- } else {
- $conditions[] = $params;
- }
- $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
- $query = $this->createQuery($targetClass, $conditions);
- if (!$this->valueExists($targetClass, $query, $model->$attribute)) {
- $this->addError($model, $attribute, $this->message);
- }
- }
-
- private function prepareConditions($targetAttribute, $model, $attribute)
- {
- if (is_array($targetAttribute)) {
- if ($this->allowArray) {
- throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
- }
- $conditions = [];
- foreach ($targetAttribute as $k => $v) {
- $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
- }
- } else {
- $conditions = [$targetAttribute => $model->$attribute];
- }
- $targetModelClass = $this->getTargetClass($model);
- if (!is_subclass_of($targetModelClass, 'yii\db\ActiveRecord')) {
- return $conditions;
- }
-
- return $this->applyTableAlias($targetModelClass::find(), $conditions);
- }
-
- private function getTargetClass($model)
- {
- return $this->targetClass === null ? get_class($model) : $this->targetClass;
- }
-
- 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.');
- }
- if (is_array($value) && !$this->allowArray) {
- return [$this->message, []];
- }
- $query = $this->createQuery($this->targetClass, [$this->targetAttribute => $value]);
- return $this->valueExists($this->targetClass, $query, $value) ? null : [$this->message, []];
- }
-
- private function valueExists($targetClass, $query, $value)
- {
- $db = $targetClass::getDb();
- $exists = false;
- if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
- $db->useMaster(function ($db) use ($query, $value, &$exists) {
- $exists = $this->queryValueExists($query, $value);
- });
- } else {
- $exists = $this->queryValueExists($query, $value);
- }
- return $exists;
- }
-
- private function queryValueExists($query, $value)
- {
- if (is_array($value)) {
- return $query->count("DISTINCT [[$this->targetAttribute]]") == count($value) ;
- }
- return $query->exists();
- }
-
- 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;
- }
-
- private function applyTableAlias($query, $conditions, $alias = null)
- {
- if ($alias === null) {
- $alias = array_keys($query->getTablesUsedInFrom())[0];
- }
- $prefixedConditions = [];
- foreach ($conditions as $columnName => $columnValue) {
- if (strpos($columnName, '(') === false) {
- $prefixedColumn = "{$alias}.[[" . preg_replace(
- '/^' . preg_quote($alias) . '\.(.*)$/',
- '$1',
- $columnName) . ']]';
- } else {
-
- $prefixedColumn = $columnName;
- }
- $prefixedConditions[$prefixedColumn] = $columnValue;
- }
- return $prefixedConditions;
- }
- }
|