Completed
Push — unique-validator-fix ( 9828bd...963824 )
by Alexander
11:50
created

UniqueValidator::prefixConditions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
crap 2
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\ActiveRecord;
14
use yii\db\ActiveQueryInterface;
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
     */
80
    public $message;
81
    /**
82
     * @var string
83
     * @since 2.0.9
84
     * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
85
     * to setup custom message for multiple target attributes.
86
     */
87
    public $comboNotUnique;
88
    /**
89
     * @var string and|or define how target attributes are related
90
     * @since 2.0.11
91
     */
92
    public $targetAttributeJunction = 'and';
93
94
95
    /**
96
     * @inheritdoc
97
     */
98 57
    public function init()
99
    {
100 57
        parent::init();
101 57
        if ($this->message !== null) {
102 3
            return;
103
        }
104 57
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
105
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
106 6
            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...
107 3
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
108
            } else {
109 3
                $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...
110
            }
111
        } else {
112 54
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
113
        }
114 57
    }
115
116
    /**
117
     * @inheritdoc
118
     */
119 42
    public function validateAttribute($model, $attribute)
120
    {
121
        /* @var $targetClass ActiveRecordInterface */
122 42
        $targetClass = $this->getTargetClass($model);
123 42
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
124 42
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
125 42
        $conditions[] = $this->targetAttributeJunction === 'or' ? 'or' : 'and';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$conditions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $conditions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
126
127 42
        foreach ($rawConditions as $key => $value) {
128 42
            if (is_array($value)) {
129 6
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
130 6
                return;
131
            }
132 39
            $conditions[] = [$key => $value];
133
        }
134
135 39
        if ($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...
136 29
            if (count($targetAttribute) > 1) {
137 6
                $this->addComboNotUniqueError($model, $attribute);
138
            } else {
139 29
                $this->addError($model, $attribute, $this->message);
140
            }
141
        }
142 36
    }
143
144
    /**
145
     * @param Model $model the data model to be validated
146
     * @return string Target class name
147
     */
148 51
    private function getTargetClass($model)
149
    {
150 51
        return $this->targetClass === null ? get_class($model) : $this->targetClass;
151
    }
152
153
    /**
154
     * Checks whether the $model exists in the database.
155
     *
156
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
157
     * of the current attribute value.
158
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
159
     * @param Model $model the data model to be validated
160
     *
161
     * @return bool whether the model already exists
162
     */
163 39
    private function modelExists($targetClass, $conditions, $model)
164
    {
165
        /** @var ActiveRecordInterface $targetClass $query */
166 39
        $query = $this->prepareQuery($targetClass, $conditions);
167
168 39
        if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
169
            // if current $model isn't in the database yet then it's OK just to call exists()
170
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
171 33
            $exists = $query->exists();
172
        } else {
173
            // if current $model is in the database already we can't use exists()
174 16
            if ($query instanceof \yii\db\ActiveQuery) {
175
                // only select primary key to optimize query
176 16
                $primaryAlias = array_keys($query->getTablesUsedInFrom())[0];
177 16
                $columns = $targetClass::primaryKey();
178 16
                foreach($columns as $c => $column) {
179 16
                    $columns[$c] = "{{{$primaryAlias}}}.[[$column]]";
180
                }
181 16
                $query->select($columns);
182
            }
183 16
            $models = $query->limit(2)->asArray()->all();
184 16
            $n = count($models);
185 16
            if ($n === 1) {
186
                // if there is one record, check if it is the currently validated model
187 16
                $dbModel = reset($models);
188 16
                $pks = $targetClass::primaryKey();
189 16
                $pk = [];
190 16
                foreach ($pks as $pkAttribute) {
191 16
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
192
                }
193 16
                $exists = ($pk != $model->getOldPrimaryKey(true));
194
            } else {
195
                // if there is more than one record, the value is not unique
196 3
                $exists = $n > 1;
197
            }
198
        }
199
200 36
        return $exists;
201
    }
202
203
    /**
204
     * Prepares a query by applying filtering conditions defined in $conditions method property
205
     * and [[filter]] class property.
206
     *
207
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
208
     * the uniqueness of the current attribute value.
209
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
210
     *
211
     * @return ActiveQueryInterface|ActiveQuery
212
     */
213 42
    private function prepareQuery($targetClass, $conditions)
214
    {
215 42
        $query = $targetClass::find();
216 42
        $query->andWhere($conditions);
217 42
        if ($this->filter instanceof \Closure) {
218 6
            call_user_func($this->filter, $query);
219 39
        } elseif ($this->filter !== null) {
220 3
            $query->andWhere($this->filter);
221
        }
222
223 42
        return $query;
224
    }
225
226
    /**
227
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
228
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
229
     *
230
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
231
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
232
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
233
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
234
     * If the key and the value are the same, you can just specify the value.
235
     * @param Model $model the data model to be validated
236
     * @param string $attribute the name of the attribute to be validated in the $model
237
     *
238
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
239
     */
240 45
    private function prepareConditions($targetAttribute, $model, $attribute)
241
    {
242 45
        if (is_array($targetAttribute)) {
243 15
            $conditions = [];
244 15
            foreach ($targetAttribute as $k => $v) {
245 15
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
246
            }
247
        } else {
248 39
            $conditions = [$targetAttribute => $model->$attribute];
249
        }
250
251 45
        if (!$model instanceof ActiveRecord) {
252 9
            return $conditions;
253
        }
254
255 42
        return $this->prefixConditions($model, $conditions);
256
    }
257
258
    /**
259
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
260
     * @param \yii\base\Model $model the data model.
261
     * @param string $attribute the name of the attribute.
262
     */
263 6
    private function addComboNotUniqueError($model, $attribute)
264
    {
265 6
        $attributeCombo = [];
266 6
        $valueCombo = [];
267 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...
268 6
            if (is_int($key)) {
269 6
                $attributeCombo[] = $model->getAttributeLabel($value);
270 6
                $valueCombo[] = '"' . $model->$value . '"';
271
            } else {
272
                $attributeCombo[] = $model->getAttributeLabel($key);
273
                $valueCombo[] = '"' . $model->$key . '"';
274
            }
275
        }
276 6
        $this->addError($model, $attribute, $this->message, [
277 6
            'attributes' => Inflector::sentence($attributeCombo),
278 6
            'values' => implode('-', $valueCombo)
279
        ]);
280 6
    }
281
282
    /**
283
     * Prefix conditions with aliases
284
     *
285
     * @param ActiveRecord $model
286
     * @param array $conditions
287
     * @return array
288
     */
289 42
    private function prefixConditions($model, $conditions)
290
    {
291 42
        $targetModelClass = $this->getTargetClass($model);
292
293
        /** @var ActiveRecord $targetModelClass */
294 42
        $query = $targetModelClass::find();
295 42
        $tableAliases = array_keys($query->getTablesUsedInFrom());
296 42
        $primaryTableAlias = $tableAliases[0];
297 42
        $prefixedConditions = [];
298 42
        foreach ($conditions as $columnName => $columnValue) {
299 42
            $prefixedColumn = "{{{$primaryTableAlias}}}.[[{$columnName}]]";
300 42
            $prefixedConditions[$prefixedColumn] = $columnValue;
301
        }
302
303 42
        return $prefixedConditions;
304
    }
305
}
306