Passed
Pull Request — 2.2 (#19894)
by Wilmer
05:43
created

UniqueValidator::modelExists()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 50
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 9.1399

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 27
c 1
b 0
f 0
nc 7
nop 3
dl 0
loc 50
ccs 22
cts 25
cp 0.88
crap 9.1399
rs 8.0555
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\base\Model;
12
use yii\db\ActiveQuery;
13
use yii\db\ActiveQueryInterface;
14
use yii\db\ActiveRecord;
15
use yii\db\ActiveRecordInterface;
16
use yii\helpers\Inflector;
17
18
/**
19
 * UniqueValidator validates that the attribute value is unique in the specified database table.
20
 *
21
 * UniqueValidator checks if the value being validated is unique in the table column specified by
22
 * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
23
 *
24
 * The following are examples of validation rules using this validator:
25
 *
26
 * ```php
27
 * // a1 needs to be unique
28
 * ['a1', 'unique']
29
 * // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
30
 * ['a1', 'unique', 'targetAttribute' => 'a2']
31
 * // a1 and a2 need to be unique together, and they both will receive error message
32
 * [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
33
 * // a1 and a2 need to be unique together, only a1 will receive error message
34
 * ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
35
 * // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
36
 * ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
37
 * ```
38
 *
39
 * @author Qiang Xue <[email protected]>
40
 * @since 2.0
41
 */
42
class UniqueValidator extends Validator
43
{
44
    /**
45
     * @var string|null the name of the ActiveRecord class that should be used to validate the uniqueness
46
     * of the current attribute value. If not set, it will use the ActiveRecord class of the attribute being validated.
47
     * @see targetAttribute
48
     */
49
    public $targetClass;
50
    /**
51
     * @var string|array|null the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that should be used to
52
     * validate the uniqueness of the current attribute value. If not set, it will use the name
53
     * of the attribute currently being validated. You may use an array to validate the uniqueness
54
     * of multiple columns at the same time. The array values are the attributes that will be
55
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
56
     */
57
    public $targetAttribute;
58
    /**
59
     * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
60
     * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
61
     * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
62
     * is the [[\yii\db\Query|Query]] object that you can modify in the function.
63
     */
64
    public $filter;
65
    /**
66
     * @var string the user-defined error message.
67
     *
68
     * When validating single attribute, it may contain
69
     * the following placeholders which will be replaced accordingly by the validator:
70
     *
71
     * - `{attribute}`: the label of the attribute being validated
72
     * - `{value}`: the value of the attribute being validated
73
     *
74
     * When validating mutliple attributes, it may contain the following placeholders:
75
     *
76
     * - `{attributes}`: the labels of the attributes being validated.
77
     * - `{values}`: the values of the attributes being validated.
78
     */
79
    public $message;
80
    /**
81
     * @var string
82
     * @since 2.0.9
83
     * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
84
     * to setup custom message for multiple target attributes.
85
     */
86
    public $comboNotUnique;
87
    /**
88
     * @var string and|or define how target attributes are related
89
     * @since 2.0.11
90
     */
91
    public $targetAttributeJunction = 'and';
92
    /**
93
     * @var bool whether this validator is forced to always use master DB
94
     * @since 2.0.14
95
     */
96
    public $forceMasterDb =  true;
97
98
99
    /**
100
     * {@inheritdoc}
101
     */
102 4
    public function init()
103
    {
104 4
        parent::init();
105 4
        if ($this->message !== null) {
106
            return;
107
        }
108 4
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
109
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
110
            if ($this->comboNotUnique === null) {
0 ignored issues
show
Deprecated Code introduced by
The property yii\validators\UniqueValidator::$comboNotUnique has been deprecated: since version 2.0.10, to be removed in 2.1. Use [[message]] property to setup custom message for multiple target attributes. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

110
            if (/** @scrutinizer ignore-deprecated */ $this->comboNotUnique === null) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
111
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
112
            } else {
113
                $this->message = $this->comboNotUnique;
0 ignored issues
show
Deprecated Code introduced by
The property yii\validators\UniqueValidator::$comboNotUnique has been deprecated: since version 2.0.10, to be removed in 2.1. Use [[message]] property to setup custom message for multiple target attributes. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

113
                $this->message = /** @scrutinizer ignore-deprecated */ $this->comboNotUnique;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
114
            }
115
        } else {
116 4
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
117
        }
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 4
    public function validateAttribute($model, $attribute)
124
    {
125 4
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
126 4
        if ($this->skipOnError) {
127 4
            foreach ((array)$targetAttribute as $k => $v) {
128 4
                if ($model->hasErrors(is_int($k) ? $v : $k)) {
129
                    return;
130
                }
131
            }
132
        }
133
134 4
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
135 4
        $conditions = [$this->targetAttributeJunction === 'or' ? 'or' : 'and'];
136
137 4
        foreach ($rawConditions as $key => $value) {
138 4
            if (is_array($value)) {
139
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
140
                return;
141
            }
142 4
            $conditions[] = [$key => $value];
143
        }
144
145
        /* @var $targetClass ActiveRecordInterface */
146 4
        $targetClass = $this->getTargetClass($model);
147 4
        $db = $targetClass::getDb();
148
149 4
        $modelExists = false;
150
151 4
        if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
152 4
            $db->useMaster(function () use ($targetClass, $conditions, $model, &$modelExists) {
153 4
                $modelExists = $this->modelExists($targetClass, $conditions, $model);
0 ignored issues
show
Bug introduced by
$targetClass of type yii\db\ActiveRecordInterface is incompatible with the type string expected by parameter $targetClass of yii\validators\UniqueValidator::modelExists(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

153
                $modelExists = $this->modelExists(/** @scrutinizer ignore-type */ $targetClass, $conditions, $model);
Loading history...
154 4
            });
155
        } else {
156
            $modelExists = $this->modelExists($targetClass, $conditions, $model);
0 ignored issues
show
Bug introduced by
$targetClass of type yii\db\ActiveRecordInterface is incompatible with the type string expected by parameter $targetClass of yii\validators\UniqueValidator::modelExists(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

156
            $modelExists = $this->modelExists(/** @scrutinizer ignore-type */ $targetClass, $conditions, $model);
Loading history...
157
        }
158
159 4
        if ($modelExists) {
160 2
            if (is_array($targetAttribute) && count($targetAttribute) > 1) {
161
                $this->addComboNotUniqueError($model, $attribute);
162
            } else {
163 2
                $this->addError($model, $attribute, $this->message);
164
            }
165
        }
166
    }
167
168
    /**
169
     * @param Model $model the data model to be validated
170
     * @return string Target class name
171
     */
172 4
    private function getTargetClass($model)
173
    {
174 4
        return $this->targetClass === null ? get_class($model) : $this->targetClass;
175
    }
176
177
    /**
178
     * Checks whether the $model exists in the database.
179
     *
180
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
181
     * of the current attribute value.
182
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
183
     * @param Model $model the data model to be validated
184
     *
185
     * @return bool whether the model already exists
186
     */
187 4
    private function modelExists($targetClass, $conditions, $model)
188
    {
189
        /** @var ActiveRecordInterface|\yii\base\BaseObject $targetClass $query */
190 4
        $query = $this->prepareQuery($targetClass, $conditions);
0 ignored issues
show
Bug introduced by
It seems like $targetClass can also be of type yii\base\BaseObject; however, parameter $targetClass of yii\validators\UniqueValidator::prepareQuery() does only seem to accept yii\db\ActiveRecordInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

190
        $query = $this->prepareQuery(/** @scrutinizer ignore-type */ $targetClass, $conditions);
Loading history...
191
192
        if (
193 4
            !$model instanceof ActiveRecordInterface ||
194 4
            $model->getIsNewRecord() ||
0 ignored issues
show
Bug introduced by
The method getIsNewRecord() does not exist on yii\base\Model. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

194
            $model->/** @scrutinizer ignore-call */ 
195
                    getIsNewRecord() ||
Loading history...
195 4
            !$model instanceof $targetClass
196
        ) {
197
            // if current $model isn't in the database yet, then it's OK just to call exists()
198
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
199 4
            $exists = $query->exists();
200
        } else {
201
            // if current $model is in the database already we can't use exists()
202 2
            if ($query instanceof \yii\db\ActiveQuery) {
203
                // only select primary key to optimize query
204 2
                $columnsCondition = array_flip($targetClass::primaryKey());
0 ignored issues
show
introduced by
The method primaryKey() does not exist on yii\base\BaseObject. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

204
                $columnsCondition = array_flip($targetClass::/** @scrutinizer ignore-call */ primaryKey());
Loading history...
205 2
                $query->select(array_flip($this->applyTableAlias($query, $columnsCondition)));
206
207
                // any with relation can't be loaded because related fields are not selected
208 2
                $query->with = null;
209
210 2
                if (is_array($query->joinWith)) {
211
                    // any joinWiths need to have eagerLoading turned off to prevent related fields being loaded
212
                    foreach ($query->joinWith as &$joinWith) {
213
                        // \yii\db\ActiveQuery::joinWith adds eagerLoading at key 1
214
                        $joinWith[1] = false;
215
                    }
216
                    unset($joinWith);
217
                }
218
            }
219 2
            $models = $query->limit(2)->asArray()->all();
220 2
            $n = count($models);
221 2
            if ($n === 1) {
222
                // if there is one record, check if it is the currently validated model
223 1
                $dbModel = reset($models);
224 1
                $pks = $targetClass::primaryKey();
225 1
                $pk = [];
226 1
                foreach ($pks as $pkAttribute) {
227 1
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
228
                }
229 1
                $exists = ($pk != $model->getOldPrimaryKey(true));
0 ignored issues
show
Bug introduced by
The method getOldPrimaryKey() does not exist on yii\base\Model. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

229
                $exists = ($pk != $model->/** @scrutinizer ignore-call */ getOldPrimaryKey(true));
Loading history...
230
            } else {
231
                // if there is more than one record, the value is not unique
232 1
                $exists = $n > 1;
233
            }
234
        }
235
236 4
        return $exists;
237
    }
238
239
    /**
240
     * Prepares a query by applying filtering conditions defined in $conditions method property
241
     * and [[filter]] class property.
242
     *
243
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
244
     * the uniqueness of the current attribute value.
245
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
246
     *
247
     * @return ActiveQueryInterface|ActiveQuery
248
     */
249 4
    private function prepareQuery($targetClass, $conditions)
250
    {
251 4
        $query = $targetClass::find();
252 4
        $query->andWhere($conditions);
253 4
        if ($this->filter instanceof \Closure) {
254
            call_user_func($this->filter, $query);
255 4
        } elseif ($this->filter !== null) {
256
            $query->andWhere($this->filter);
0 ignored issues
show
Bug introduced by
It seems like $this->filter can also be of type string; however, parameter $condition of yii\db\QueryInterface::andWhere() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

256
            $query->andWhere(/** @scrutinizer ignore-type */ $this->filter);
Loading history...
257
        }
258
259 4
        return $query;
260
    }
261
262
    /**
263
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
264
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
265
     *
266
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
267
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
268
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
269
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
270
     * If the key and the value are the same, you can just specify the value.
271
     * @param Model $model the data model to be validated
272
     * @param string $attribute the name of the attribute to be validated in the $model
273
     *
274
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
275
     */
276 4
    private function prepareConditions($targetAttribute, $model, $attribute)
277
    {
278 4
        if (is_array($targetAttribute)) {
279
            $conditions = [];
280
            foreach ($targetAttribute as $k => $v) {
281
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
282
            }
283
        } else {
284 4
            $conditions = [$targetAttribute => $model->$attribute];
285
        }
286
287 4
        $targetModelClass = $this->getTargetClass($model);
288 4
        if (!is_subclass_of($targetModelClass, 'yii\db\ActiveRecord')) {
289
            return $conditions;
290
        }
291
292
        /** @var ActiveRecord $targetModelClass */
293 4
        return $this->applyTableAlias($targetModelClass::find(), $conditions);
294
    }
295
296
    /**
297
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
298
     * @param \yii\base\Model $model the data model.
299
     * @param string $attribute the name of the attribute.
300
     */
301
    private function addComboNotUniqueError($model, $attribute)
302
    {
303
        $attributeCombo = [];
304
        $valueCombo = [];
305
        foreach ($this->targetAttribute as $key => $value) {
306
            if (is_int($key)) {
307
                $attributeCombo[] = $model->getAttributeLabel($value);
308
                $valueCombo[] = '"' . $model->$value . '"';
309
            } else {
310
                $attributeCombo[] = $model->getAttributeLabel($key);
311
                $valueCombo[] = '"' . $model->$key . '"';
312
            }
313
        }
314
        $this->addError($model, $attribute, $this->message, [
315
            'attributes' => Inflector::sentence($attributeCombo),
316
            'values' => implode('-', $valueCombo),
317
        ]);
318
    }
319
320
    /**
321
     * Returns conditions with alias.
322
     * @param ActiveQuery $query
323
     * @param array $conditions array of condition, keys to be modified
324
     * @param string|null $alias set empty string for no apply alias. Set null for apply primary table alias
325
     * @return array
326
     */
327 4
    private function applyTableAlias($query, $conditions, $alias = null)
328
    {
329 4
        if ($alias === null) {
330 4
            $alias = array_keys($query->getTablesUsedInFrom())[0];
331
        }
332 4
        $prefixedConditions = [];
333 4
        foreach ($conditions as $columnName => $columnValue) {
334 4
            if (strpos($columnName, '(') === false) {
335 4
                $columnName = preg_replace('/^' . preg_quote($alias, '/') . '\.(.*)$/', '$1', $columnName);
336 4
                if (strncmp($columnName, '[[', 2) === 0) {
337
                    $prefixedColumn = "{$alias}.{$columnName}";
338
                } else {
339 4
                    $prefixedColumn = "{$alias}.[[{$columnName}]]";
340
                }
341
            } else {
342
                // there is an expression, can't prefix it reliably
343
                $prefixedColumn = $columnName;
344
            }
345
346 4
            $prefixedConditions[$prefixedColumn] = $columnValue;
347
        }
348
349 4
        return $prefixedConditions;
350
    }
351
}
352