Completed
Push — 2.1 ( b44a46...4c2160 )
by
unknown
12:30
created

UniqueValidator   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 294
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 98.99%

Importance

Changes 0
Metric Value
wmc 39
lcom 1
cbo 8
dl 0
loc 294
ccs 98
cts 99
cp 0.9899
rs 8.2857
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getTargetClass() 0 4 2
B prepareConditions() 0 19 5
B init() 0 17 5
D validateAttribute() 0 36 10
C modelExists() 0 41 7
A prepareQuery() 0 12 3
A addComboNotUniqueError() 0 18 3
B applyTableAlias() 0 22 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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 the name of the ActiveRecord class that should be used to validate the uniqueness
46
     * of the current attribute value.
47
     * This must be a fully qualified class name.
48
     *
49
     * If not set, it will use the ActiveRecord class of the attribute being validated.
50
     *
51
     * @see targetAttribute
52
     */
53
    public $targetClass;
54
    /**
55
     * @var string|array the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that should be used to
56
     * validate the uniqueness of the current attribute value. If not set, it will use the name
57
     * of the attribute currently being validated. You may use an array to validate the uniqueness
58
     * of multiple columns at the same time. The array values are the attributes that will be
59
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
60
     */
61
    public $targetAttribute;
62
    /**
63
     * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
64
     * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
65
     * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
66
     * is the [[\yii\db\Query|Query]] object that you can modify in the function.
67
     */
68
    public $filter;
69
    /**
70
     * @var string the user-defined error message.
71
     *
72
     * When validating single attribute, it may contain
73
     * the following placeholders which will be replaced accordingly by the validator:
74
     *
75
     * - `{attribute}`: the label of the attribute being validated
76
     * - `{value}`: the value of the attribute being validated
77
     *
78
     * When validating mutliple attributes, it may contain the following placeholders:
79
     *
80
     * - `{attributes}`: the labels of the attributes being validated.
81
     * - `{values}`: the values of the attributes being validated.
82
     */
83
    public $message;
84
    /**
85
     * @var string
86
     * @since 2.0.9
87
     * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
88
     * to setup custom message for multiple target attributes.
89
     */
90
    public $comboNotUnique;
91
    /**
92
     * @var string and|or define how target attributes are related
93
     * @since 2.0.11
94
     */
95
    public $targetAttributeJunction = 'and';
96
    /**
97
     * @var bool whether this validator is forced to always use master DB
98
     * @since 2.0.14
99
     */
100
    public $forceMasterDb =  true;
101
102
103
    /**
104
     * {@inheritdoc}
105
     */
106 67
    public function init()
107
    {
108 67
        parent::init();
109 67
        if ($this->message !== null) {
110 3
            return;
111
        }
112 67
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
113
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
114 12
            if ($this->comboNotUnique === null) {
0 ignored issues
show
Deprecated Code introduced by
The property yii\validators\UniqueValidator::$comboNotUnique has been deprecated with message: since version 2.0.10, to be removed in 2.1. Use [[message]] property
to setup custom message for multiple target attributes.

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...
115 9
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
116
            } else {
117 12
                $this->message = $this->comboNotUnique;
0 ignored issues
show
Deprecated Code introduced by
The property yii\validators\UniqueValidator::$comboNotUnique has been deprecated with message: since version 2.0.10, to be removed in 2.1. Use [[message]] property
to setup custom message for multiple target attributes.

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...
118
            }
119
        } else {
120 58
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
121
        }
122 67
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127 52
    public function validateAttribute($model, $attribute)
128
    {
129
        /* @var $targetClass ActiveRecordInterface */
130 52
        $targetClass = $this->getTargetClass($model);
131 52
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
132 52
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
133 52
        $conditions = [$this->targetAttributeJunction === 'or' ? 'or' : 'and'];
134
135 52
        foreach ($rawConditions as $key => $value) {
136 52
            if (is_array($value)) {
137 6
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
138 6
                return;
139
            }
140 49
            $conditions[] = [$key => $value];
141
        }
142
143 49
        $db = $targetClass::getDb();
144
145 49
        $modelExists = false;
146
147 49
        if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
148 49
            $db->useMaster(function () use ($targetClass, $conditions, $model, &$modelExists) {
149 49
                $modelExists = $this->modelExists($targetClass, $conditions, $model);
0 ignored issues
show
Documentation introduced by
$targetClass is of type object<yii\db\ActiveRecordInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
150 49
            });
151
        } else {
152 3
            $modelExists = $this->modelExists($targetClass, $conditions, $model);
0 ignored issues
show
Documentation introduced by
$targetClass is of type object<yii\db\ActiveRecordInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
153
        }
154
155 46
        if ($modelExists) {
156 29
            if (is_array($targetAttribute) && count($targetAttribute) > 1) {
157 6
                $this->addComboNotUniqueError($model, $attribute);
158
            } else {
159 29
                $this->addError($model, $attribute, $this->message);
160
            }
161
        }
162 46
    }
163
164
    /**
165
     * @param Model $model the data model to be validated
166
     * @return string Target class name
167
     */
168 61
    private function getTargetClass($model)
169
    {
170 61
        return $this->targetClass === null ? get_class($model) : $this->targetClass;
171
    }
172
173
    /**
174
     * Checks whether the $model exists in the database.
175
     *
176
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
177
     * of the current attribute value.
178
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
179
     * @param Model $model the data model to be validated
180
     *
181
     * @return bool whether the model already exists
182
     */
183 49
    private function modelExists($targetClass, $conditions, $model)
184
    {
185
        /** @var ActiveRecordInterface $targetClass $query */
186 49
        $query = $this->prepareQuery($targetClass, $conditions);
187
188 49
        if (!$model instanceof ActiveRecordInterface
189 46
            || $model->getIsNewRecord()
190 49
            || get_class($model) !== $targetClass
191
        ) {
192
            // if current $model isn't in the database yet then it's OK just to call exists()
193
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
194 34
            $exists = $query->exists();
195
        } else {
196
            // if current $model is in the database already we can't use exists()
197 26
            if ($query instanceof \yii\db\ActiveQuery) {
198
                // only select primary key to optimize query
199 26
                $columnsCondition = array_flip($targetClass::primaryKey());
200 26
                $query->select(array_flip($this->applyTableAlias($query, $columnsCondition)));
201
                
202
                // any with relation can't be loaded because related fields are not selected
203 26
                $query->with = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $with.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
204
            }
205 26
            $models = $query->limit(2)->asArray()->all();
206 26
            $n = count($models);
207 26
            if ($n === 1) {
208
                // if there is one record, check if it is the currently validated model
209 23
                $dbModel = reset($models);
210 23
                $pks = $targetClass::primaryKey();
211 23
                $pk = [];
212 23
                foreach ($pks as $pkAttribute) {
213 23
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
214
                }
215 23
                $exists = ($pk != $model->getOldPrimaryKey(true));
216
            } else {
217
                // if there is more than one record, the value is not unique
218 6
                $exists = $n > 1;
219
            }
220
        }
221
222 46
        return $exists;
223
    }
224
225
    /**
226
     * Prepares a query by applying filtering conditions defined in $conditions method property
227
     * and [[filter]] class property.
228
     *
229
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
230
     * the uniqueness of the current attribute value.
231
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
232
     *
233
     * @return ActiveQueryInterface|ActiveQuery
234
     */
235 52
    private function prepareQuery($targetClass, $conditions)
236
    {
237 52
        $query = $targetClass::find();
238 52
        $query->andWhere($conditions);
239 52
        if ($this->filter instanceof \Closure) {
240 6
            call_user_func($this->filter, $query);
241 49
        } elseif ($this->filter !== null) {
242 3
            $query->andWhere($this->filter);
243
        }
244
245 52
        return $query;
246
    }
247
248
    /**
249
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
250
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
251
     *
252
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
253
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
254
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
255
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
256
     * If the key and the value are the same, you can just specify the value.
257
     * @param Model $model the data model to be validated
258
     * @param string $attribute the name of the attribute to be validated in the $model
259
     *
260
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
261
     */
262 55
    private function prepareConditions($targetAttribute, $model, $attribute)
263
    {
264 55
        if (is_array($targetAttribute)) {
265 24
            $conditions = [];
266 24
            foreach ($targetAttribute as $k => $v) {
267 24
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
268
            }
269
        } else {
270 40
            $conditions = [$targetAttribute => $model->$attribute];
271
        }
272
273 55
        $targetModelClass = $this->getTargetClass($model);
274 55
        if (!is_subclass_of($targetModelClass, 'yii\db\ActiveRecord')) {
275 6
            return $conditions;
276
        }
277
278
        /** @var ActiveRecord $targetModelClass */
279 55
        return $this->applyTableAlias($targetModelClass::find(), $conditions);
280
    }
281
282
    /**
283
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
284
     * @param \yii\base\Model $model the data model.
285
     * @param string $attribute the name of the attribute.
286
     */
287 6
    private function addComboNotUniqueError($model, $attribute)
288
    {
289 6
        $attributeCombo = [];
290 6
        $valueCombo = [];
291 6
        foreach ($this->targetAttribute as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $this->targetAttribute of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
292 6
            if (is_int($key)) {
293 6
                $attributeCombo[] = $model->getAttributeLabel($value);
294 6
                $valueCombo[] = '"' . $model->$value . '"';
295
            } else {
296
                $attributeCombo[] = $model->getAttributeLabel($key);
297 6
                $valueCombo[] = '"' . $model->$key . '"';
298
            }
299
        }
300 6
        $this->addError($model, $attribute, $this->message, [
301 6
            'attributes' => Inflector::sentence($attributeCombo),
302 6
            'values' => implode('-', $valueCombo),
303
        ]);
304 6
    }
305
306
    /**
307
     * Returns conditions with alias.
308
     * @param ActiveQuery $query
309
     * @param array $conditions array of condition, keys to be modified
310
     * @param null|string $alias set empty string for no apply alias. Set null for apply primary table alias
311
     * @return array
312
     */
313 55
    private function applyTableAlias($query, $conditions, $alias = null)
314
    {
315 55
        if ($alias === null) {
316 55
            $alias = array_keys($query->getTablesUsedInFrom())[0];
317
        }
318 55
        $prefixedConditions = [];
319 55
        foreach ($conditions as $columnName => $columnValue) {
320 55
            if (strpos($columnName, '(') === false) {
321 55
                $prefixedColumn = "{$alias}.[[" . preg_replace(
322 55
                    '/^' . preg_quote($alias) . '\.(.*)$/',
323 55
                    '$1',
324 55
                    $columnName) . ']]';
325
            } else {
326
                // there is an expression, can't prefix it reliably
327 3
                $prefixedColumn = $columnName;
328
            }
329
330 55
            $prefixedConditions[$prefixedColumn] = $columnValue;
331
        }
332
333 55
        return $prefixedConditions;
334
    }
335
}
336