Completed
Push — master ( bdc372...c54ead )
by Dmitry
19:44 queued 16:30
created

UniqueValidator::validateAttribute()   D

Complexity

Conditions 10
Paths 52

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 10

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 22
cts 22
cp 1
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 22
nc 52
nop 2
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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. 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 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
94
    /**
95
     * @var bool whether this validator is forced to always use master DB
96
     * @since 2.0.14
97
     */
98
    public $forceMasterDb =  true;
99
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 67
    public function init()
105
    {
106 67
        parent::init();
107 67
        if ($this->message !== null) {
108 3
            return;
109
        }
110 67
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
111
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
112 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...
113 9
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
114
            } else {
115 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...
116
            }
117
        } else {
118 58
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
119
        }
120 67
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125 52
    public function validateAttribute($model, $attribute)
126
    {
127
        /* @var $targetClass ActiveRecordInterface */
128 52
        $targetClass = $this->getTargetClass($model);
129 52
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
130 52
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
131 52
        $conditions = [$this->targetAttributeJunction === 'or' ? 'or' : 'and'];
132
133 52
        foreach ($rawConditions as $key => $value) {
134 52
            if (is_array($value)) {
135 6
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
136 6
                return;
137
            }
138 49
            $conditions[] = [$key => $value];
139
        }
140
141 49
        $db = $targetClass::getDb();
142
143 49
        $modelExists = false;
144
145 49
        if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
146 49
            $db->useMaster(function () use ($targetClass, $conditions, $model, &$modelExists) {
147 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...
148 49
            });
149
        } else {
150 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...
151
        }
152
153 46
        if ($modelExists) {
154 29
            if (is_array($targetAttribute) && count($targetAttribute) > 1) {
155 6
                $this->addComboNotUniqueError($model, $attribute);
156
            } else {
157 29
                $this->addError($model, $attribute, $this->message);
158
            }
159
        }
160 46
    }
161
162
    /**
163
     * @param Model $model the data model to be validated
164
     * @return string Target class name
165
     */
166 61
    private function getTargetClass($model)
167
    {
168 61
        return $this->targetClass === null ? get_class($model) : $this->targetClass;
169
    }
170
171
    /**
172
     * Checks whether the $model exists in the database.
173
     *
174
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
175
     * of the current attribute value.
176
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
177
     * @param Model $model the data model to be validated
178
     *
179
     * @return bool whether the model already exists
180
     */
181 49
    private function modelExists($targetClass, $conditions, $model)
182
    {
183
        /** @var ActiveRecordInterface $targetClass $query */
184 49
        $query = $this->prepareQuery($targetClass, $conditions);
185
186 49
        if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
187
            // if current $model isn't in the database yet then it's OK just to call exists()
188
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
189 34
            $exists = $query->exists();
190
        } else {
191
            // if current $model is in the database already we can't use exists()
192 26
            if ($query instanceof \yii\db\ActiveQuery) {
193
                // only select primary key to optimize query
194 26
                $columnsCondition = array_flip($targetClass::primaryKey());
195 26
                $query->select(array_flip($this->applyTableAlias($query, $columnsCondition)));
196
                
197
                // any with relation can't be loaded because related fields are not selected
198 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...
199
            }
200 26
            $models = $query->limit(2)->asArray()->all();
201 26
            $n = count($models);
202 26
            if ($n === 1) {
203
                // if there is one record, check if it is the currently validated model
204 23
                $dbModel = reset($models);
205 23
                $pks = $targetClass::primaryKey();
206 23
                $pk = [];
207 23
                foreach ($pks as $pkAttribute) {
208 23
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
209
                }
210 23
                $exists = ($pk != $model->getOldPrimaryKey(true));
211
            } else {
212
                // if there is more than one record, the value is not unique
213 6
                $exists = $n > 1;
214
            }
215
        }
216
217 46
        return $exists;
218
    }
219
220
    /**
221
     * Prepares a query by applying filtering conditions defined in $conditions method property
222
     * and [[filter]] class property.
223
     *
224
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
225
     * the uniqueness of the current attribute value.
226
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
227
     *
228
     * @return ActiveQueryInterface|ActiveQuery
229
     */
230 52
    private function prepareQuery($targetClass, $conditions)
231
    {
232 52
        $query = $targetClass::find();
233 52
        $query->andWhere($conditions);
234 52
        if ($this->filter instanceof \Closure) {
235 6
            call_user_func($this->filter, $query);
236 49
        } elseif ($this->filter !== null) {
237 3
            $query->andWhere($this->filter);
238
        }
239
240 52
        return $query;
241
    }
242
243
    /**
244
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
245
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
246
     *
247
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
248
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
249
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
250
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
251
     * If the key and the value are the same, you can just specify the value.
252
     * @param Model $model the data model to be validated
253
     * @param string $attribute the name of the attribute to be validated in the $model
254
     *
255
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
256
     */
257 55
    private function prepareConditions($targetAttribute, $model, $attribute)
258
    {
259 55
        if (is_array($targetAttribute)) {
260 24
            $conditions = [];
261 24
            foreach ($targetAttribute as $k => $v) {
262 24
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
263
            }
264
        } else {
265 40
            $conditions = [$targetAttribute => $model->$attribute];
266
        }
267
268 55
        $targetModelClass = $this->getTargetClass($model);
269 55
        if (!is_subclass_of($targetModelClass, 'yii\db\ActiveRecord')) {
270 6
            return $conditions;
271
        }
272
273
        /** @var ActiveRecord $targetModelClass */
274 55
        return $this->applyTableAlias($targetModelClass::find(), $conditions);
275
    }
276
277
    /**
278
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
279
     * @param \yii\base\Model $model the data model.
280
     * @param string $attribute the name of the attribute.
281
     */
282 6
    private function addComboNotUniqueError($model, $attribute)
283
    {
284 6
        $attributeCombo = [];
285 6
        $valueCombo = [];
286 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...
287 6
            if (is_int($key)) {
288 6
                $attributeCombo[] = $model->getAttributeLabel($value);
289 6
                $valueCombo[] = '"' . $model->$value . '"';
290
            } else {
291
                $attributeCombo[] = $model->getAttributeLabel($key);
292 6
                $valueCombo[] = '"' . $model->$key . '"';
293
            }
294
        }
295 6
        $this->addError($model, $attribute, $this->message, [
296 6
            'attributes' => Inflector::sentence($attributeCombo),
297 6
            'values' => implode('-', $valueCombo),
298
        ]);
299 6
    }
300
301
    /**
302
     * Returns conditions with alias.
303
     * @param ActiveQuery $query
304
     * @param array $conditions array of condition, keys to be modified
305
     * @param null|string $alias set empty string for no apply alias. Set null for apply primary table alias
306
     * @return array
307
     */
308 55
    private function applyTableAlias($query, $conditions, $alias = null)
309
    {
310 55
        if ($alias === null) {
311 55
            $alias = array_keys($query->getTablesUsedInFrom())[0];
312
        }
313 55
        $prefixedConditions = [];
314 55
        foreach ($conditions as $columnName => $columnValue) {
315 55
            if (strpos($columnName, '(') === false) {
316 55
                $prefixedColumn = "{$alias}.[[" . preg_replace(
317 55
                    '/^' . preg_quote($alias) . '\.(.*)$/',
318 55
                    '$1',
319 55
                    $columnName) . ']]';
320
            } else {
321
                // there is an expression, can't prefix it reliably
322 3
                $prefixedColumn = $columnName;
323
            }
324
325 55
            $prefixedConditions[$prefixedColumn] = $columnValue;
326
        }
327
328 55
        return $prefixedConditions;
329
    }
330
}
331