Completed
Push — 2.1-master-merge ( 240673 )
by Alexander
13:45
created

UniqueValidator::applyTableAlias()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

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