123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- <?php
- namespace yii\validators;
- use Yii;
- use yii\base\Model;
- use yii\db\ActiveQuery;
- use yii\db\ActiveQueryInterface;
- use yii\db\ActiveRecord;
- use yii\db\ActiveRecordInterface;
- use yii\helpers\Inflector;
- class UniqueValidator extends Validator
- {
-
- public $targetClass;
-
- public $targetAttribute;
-
- public $filter;
-
- public $message;
-
- public $comboNotUnique;
-
- public $targetAttributeJunction = 'and';
-
- public $forceMasterDb = true;
-
- public function init()
- {
- parent::init();
- if ($this->message !== null) {
- return;
- }
- if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
-
- if ($this->comboNotUnique === null) {
- $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
- } else {
- $this->message = $this->comboNotUnique;
- }
- } else {
- $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
- }
- }
-
- public function validateAttribute($model, $attribute)
- {
-
- $targetClass = $this->getTargetClass($model);
- $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
- $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
- $conditions = [$this->targetAttributeJunction === 'or' ? 'or' : 'and'];
- foreach ($rawConditions as $key => $value) {
- if (is_array($value)) {
- $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
- return;
- }
- $conditions[] = [$key => $value];
- }
- $db = $targetClass::getDb();
- $modelExists = false;
- if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
- $db->useMaster(function () use ($targetClass, $conditions, $model, &$modelExists) {
- $modelExists = $this->modelExists($targetClass, $conditions, $model);
- });
- } else {
- $modelExists = $this->modelExists($targetClass, $conditions, $model);
- }
- if ($modelExists) {
- if (is_array($targetAttribute) && count($targetAttribute) > 1) {
- $this->addComboNotUniqueError($model, $attribute);
- } else {
- $this->addError($model, $attribute, $this->message);
- }
- }
- }
-
- private function getTargetClass($model)
- {
- return $this->targetClass === null ? get_class($model) : $this->targetClass;
- }
-
- private function modelExists($targetClass, $conditions, $model)
- {
-
- $query = $this->prepareQuery($targetClass, $conditions);
- if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
-
-
- $exists = $query->exists();
- } else {
-
- if ($query instanceof \yii\db\ActiveQuery) {
-
- $columnsCondition = array_flip($targetClass::primaryKey());
- $query->select(array_flip($this->applyTableAlias($query, $columnsCondition)));
-
-
- $query->with = null;
-
- if (is_array($query->joinWith)) {
-
- foreach ($query->joinWith as &$joinWith) {
-
- $joinWith[1] = false;
- }
- unset($joinWith);
- }
- }
- $models = $query->limit(2)->asArray()->all();
- $n = count($models);
- if ($n === 1) {
-
- $dbModel = reset($models);
- $pks = $targetClass::primaryKey();
- $pk = [];
- foreach ($pks as $pkAttribute) {
- $pk[$pkAttribute] = $dbModel[$pkAttribute];
- }
- $exists = ($pk != $model->getOldPrimaryKey(true));
- } else {
-
- $exists = $n > 1;
- }
- }
- return $exists;
- }
-
- private function prepareQuery($targetClass, $conditions)
- {
- $query = $targetClass::find();
- $query->andWhere($conditions);
- if ($this->filter instanceof \Closure) {
- call_user_func($this->filter, $query);
- } elseif ($this->filter !== null) {
- $query->andWhere($this->filter);
- }
- return $query;
- }
-
- private function prepareConditions($targetAttribute, $model, $attribute)
- {
- if (is_array($targetAttribute)) {
- $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 addComboNotUniqueError($model, $attribute)
- {
- $attributeCombo = [];
- $valueCombo = [];
- foreach ($this->targetAttribute as $key => $value) {
- if (is_int($key)) {
- $attributeCombo[] = $model->getAttributeLabel($value);
- $valueCombo[] = '"' . $model->$value . '"';
- } else {
- $attributeCombo[] = $model->getAttributeLabel($key);
- $valueCombo[] = '"' . $model->$key . '"';
- }
- }
- $this->addError($model, $attribute, $this->message, [
- 'attributes' => Inflector::sentence($attributeCombo),
- 'values' => implode('-', $valueCombo),
- ]);
- }
-
- 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) {
- $columnName = preg_replace('/^' . preg_quote($alias) . '\.(.*)$/', '$1', $columnName);
- if (strpos($columnName, '[[') === 0) {
- $prefixedColumn = "{$alias}.{$columnName}";
- } else {
- $prefixedColumn = "{$alias}.[[{$columnName}]]";
- }
- } else {
-
- $prefixedColumn = $columnName;
- }
- $prefixedConditions[$prefixedColumn] = $columnValue;
- }
- return $prefixedConditions;
- }
- }
|