Completed
Push — unique-validator-fix ( 7db93f )
by Alexander
42:42 queued 39:29
created

UniqueValidator::addComboNotUniqueError()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0327

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 13
cp 0.8462
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 2
crap 3.0327
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
use yii\helpers\ActiveQueryHelper;
18
19
/**
20
 * UniqueValidator validates that the attribute value is unique in the specified database table.
21
 *
22
 * UniqueValidator checks if the value being validated is unique in the table column specified by
23
 * the ActiveRecord class [[targetClass]] and the attribute [[targetAttribute]].
24
 *
25
 * The following are examples of validation rules using this validator:
26
 *
27
 * ```php
28
 * // a1 needs to be unique
29
 * ['a1', 'unique']
30
 * // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
31
 * ['a1', 'unique', 'targetAttribute' => 'a2']
32
 * // a1 and a2 need to be unique together, and they both will receive error message
33
 * [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
34
 * // a1 and a2 need to be unique together, only a1 will receive error message
35
 * ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
36
 * // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
37
 * ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
38
 * ```
39
 *
40
 * @author Qiang Xue <[email protected]>
41
 * @since 2.0
42
 */
43
class UniqueValidator extends Validator
44
{
45
    /**
46
     * @var string the name of the ActiveRecord class that should be used to validate the uniqueness
47
     * of the current attribute value. If not set, it will use the ActiveRecord class of the attribute being validated.
48
     * @see targetAttribute
49
     */
50
    public $targetClass;
51
    /**
52
     * @var string|array the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that should be used to
53
     * validate the uniqueness of the current attribute value. If not set, it will use the name
54
     * of the attribute currently being validated. You may use an array to validate the uniqueness
55
     * of multiple columns at the same time. The array values are the attributes that will be
56
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
57
     */
58
    public $targetAttribute;
59
    /**
60
     * @var string|array|\Closure additional filter to be applied to the DB query used to check the uniqueness of the attribute value.
61
     * This can be a string or an array representing the additional query condition (refer to [[\yii\db\Query::where()]]
62
     * on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
63
     * is the [[\yii\db\Query|Query]] object that you can modify in the function.
64
     */
65
    public $filter;
66
    /**
67
     * @var string the user-defined error message.
68
     *
69
     * When validating single attribute, it may contain
70
     * the following placeholders which will be replaced accordingly by the validator:
71
     *
72
     * - `{attribute}`: the label of the attribute being validated
73
     * - `{value}`: the value of the attribute being validated
74
     *
75
     * When validating mutliple attributes, it may contain the following placeholders:
76
     *
77
     * - `{attributes}`: the labels of the attributes being validated.
78
     * - `{values}`: the values of the attributes being validated.
79
     *
80
     */
81
    public $message;
82
    /**
83
     * @var string
84
     * @since 2.0.9
85
     * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
86
     * to setup custom message for multiple target attributes.
87
     */
88
    public $comboNotUnique;
89
    /**
90
     * @var string and|or define how target attributes are related
91
     * @since 2.0.11
92
     */
93
    public $targetAttributeJunction = 'and';
94
95
96
    /**
97
     * @inheritdoc
98
     */
99 54
    public function init()
100
    {
101 54
        parent::init();
102 54
        if ($this->message !== null) {
103 3
            return;
104
        }
105 54
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
106
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
107 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...
108 3
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
109
            } else {
110 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...
111
            }
112
        } else {
113 51
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
114
        }
115 54
    }
116
117
    /**
118
     * @inheritdoc
119
     */
120 39
    public function validateAttribute($model, $attribute)
121
    {
122
        /* @var $targetClass ActiveRecordInterface */
123 39
        $targetClass = $this->getTargetClass($model);
124 39
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
125 39
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
126 39
        $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...
127
128 39
        foreach ($rawConditions as $key => $value) {
129 39
            if (is_array($value)) {
130 6
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
131 6
                return;
132
            }
133 36
            $conditions[] = [$key => $value];
134
        }
135
136 36
        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...
137 29
            if (count($targetAttribute) > 1) {
138 6
                $this->addComboNotUniqueError($model, $attribute);
139
            } else {
140 29
                $this->addError($model, $attribute, $this->message);
141
            }
142
        }
143 33
    }
144
145
    /**
146
     * @param Model $model the data model to be validated
147
     * @return string Target class name
148
     */
149 48
    private function getTargetClass($model)
150
    {
151 48
        return $this->targetClass === null ? get_class($model) : $this->targetClass;
152
    }
153
154
    /**
155
     * Checks whether the $model exists in the database.
156
     *
157
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
158
     * of the current attribute value.
159
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
160
     * @param Model $model the data model to be validated
161
     *
162
     * @return bool whether the model already exists
163
     */
164 36
    private function modelExists($targetClass, $conditions, $model)
165
    {
166
        /** @var ActiveRecordInterface $targetClass $query */
167 36
        $query = $this->prepareQuery($targetClass, $conditions);
168
169 36
        if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
170
            // if current $model isn't in the database yet then it's OK just to call exists()
171
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
172 33
            $exists = $query->exists();
173
        } else {
174
            // if current $model is in the database already we can't use exists()
175 13
            if ($query instanceof \yii\db\ActiveQuery) {
176
                // only select primary key to optimize query
177 13
                $query->select($targetClass::primaryKey());
178
            }
179 13
            $models = $query->limit(2)->asArray()->all();
180 13
            $n = count($models);
181 13
            if ($n === 1) {
182
                // if there is one record, check if it is the currently validated model
183 13
                $dbModel = reset($models);
184 13
                $pks = $targetClass::primaryKey();
185 13
                $pk = [];
186 13
                foreach ($pks as $pkAttribute) {
187 13
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
188
                }
189 13
                $exists = ($pk != $model->getOldPrimaryKey(true));
190
            } else {
191
                // if there is more than one record, the value is not unique
192 3
                $exists = $n > 1;
193
            }
194
        }
195
196 33
        return $exists;
197
    }
198
199
    /**
200
     * Prepares a query by applying filtering conditions defined in $conditions method property
201
     * and [[filter]] class property.
202
     *
203
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
204
     * the uniqueness of the current attribute value.
205
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
206
     *
207
     * @return ActiveQueryInterface|ActiveQuery
208
     */
209 39
    private function prepareQuery($targetClass, $conditions)
210
    {
211 39
        $query = $targetClass::find();
212 39
        $query->andWhere($conditions);
213 39
        if ($this->filter instanceof \Closure) {
214 3
            call_user_func($this->filter, $query);
215 39
        } elseif ($this->filter !== null) {
216 3
            $query->andWhere($this->filter);
217
        }
218
219 39
        return $query;
220
    }
221
222
    /**
223
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
224
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
225
     *
226
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
227
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
228
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
229
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
230
     * If the key and the value are the same, you can just specify the value.
231
     * @param Model $model the data model to be validated
232
     * @param string $attribute the name of the attribute to be validated in the $model
233
     *
234
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
235
     */
236 42
    private function prepareConditions($targetAttribute, $model, $attribute)
237
    {
238 42
        if (is_array($targetAttribute)) {
239 15
            $conditions = [];
240 15
            foreach ($targetAttribute as $k => $v) {
241 15
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
242
            }
243
        } else {
244 36
            $conditions = [$targetAttribute => $model->$attribute];
245
        }
246
247 42
        if (!$model instanceof ActiveRecord) {
248 9
            return $conditions;
249
        }
250
251
        // Add table prefix for column
252 39
        $targetClass = $this->getTargetClass($model);
253
254
        /** @var ActiveRecord $targetClass */
255 39
        $query = $targetClass::find();
256 39
        $tableAliases = $query->getFromAliases();
257 39
        $primaryTableAlias = $tableAliases[0];
258 39
        $prefixedConditions = [];
259 39
        foreach ($conditions as $columnName => $columnValue) {
260 39
            $prefixedColumn = "{$primaryTableAlias}.{$columnName}";
261 39
            $prefixedConditions[$prefixedColumn] = $columnValue;
262
        }
263
264 39
        return $prefixedConditions;
265
    }
266
267
    /**
268
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
269
     * @param \yii\base\Model $model the data model.
270
     * @param string $attribute the name of the attribute.
271
     */
272 6
    private function addComboNotUniqueError($model, $attribute)
273
    {
274 6
        $attributeCombo = [];
275 6
        $valueCombo = [];
276 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...
277 6
            if (is_int($key)) {
278 6
                $attributeCombo[] = $model->getAttributeLabel($value);
279 6
                $valueCombo[] = '"' . $model->$value . '"';
280
            } else {
281
                $attributeCombo[] = $model->getAttributeLabel($key);
282
                $valueCombo[] = '"' . $model->$key . '"';
283
            }
284
        }
285 6
        $this->addError($model, $attribute, $this->message, [
286 6
            'attributes' => Inflector::sentence($attributeCombo),
287 6
            'values' => implode('-', $valueCombo)
288
        ]);
289 6
    }
290
}
291