|
- <?php
-
-
- namespace yii\validators;
-
- use Yii;
- use yii\db\ActiveRecordInterface;
- use yii\helpers\Inflector;
-
-
- class UniqueValidator extends Validator
- {
-
-
- public $targetClass;
-
-
- public $targetAttribute;
-
-
- public $filter;
-
-
- public $message;
-
-
- public $comboNotUnique;
-
-
-
-
- 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->targetClass === null ? get_class($model) : $this->targetClass;
- $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
-
- if (is_array($targetAttribute)) {
- $params = [];
- foreach ($targetAttribute as $k => $v) {
- $params[$v] = is_int($k) ? $model->$v : $model->$k;
- }
- } else {
- $params = [$targetAttribute => $model->$attribute];
- }
-
- foreach ($params as $value) {
- if (is_array($value)) {
- $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
-
- return;
- }
- }
-
- $query = $targetClass::find();
- $query->andWhere($params);
-
- if ($this->filter instanceof \Closure) {
- call_user_func($this->filter, $query);
- } elseif ($this->filter !== null) {
- $query->andWhere($this->filter);
- }
-
- if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
-
-
- $exists = $query->exists();
- } else {
-
-
- $models = $query->limit(2)->all();
- $n = count($models);
- if ($n === 1) {
- $keys = array_keys($params);
- $pks = $targetClass::primaryKey();
- sort($keys);
- sort($pks);
- if ($keys === $pks) {
-
- $exists = $model->getOldPrimaryKey() != $model->getPrimaryKey();
- } else {
-
- $exists = reset($models)->getPrimaryKey() != $model->getOldPrimaryKey();
- }
- } else {
- $exists = $n > 1;
- }
- }
-
- if ($exists) {
- if (count($targetAttribute) > 1) {
- $this->addComboNotUniqueError($model, $attribute);
- } else {
- $this->addError($model, $attribute, $this->message);
- }
- }
- }
-
-
-
- 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)
- ]);
- }
- }
|