Completed
Push — master ( 1501c6...5a8c3d )
by Carsten
12:28
created

UniqueValidator::prepareConditions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

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