Completed
Push — master ( 72a690...72cd84 )
by Carsten
18s
created

UniqueValidator   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 220
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 97.65%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 30
c 3
b 0
f 0
lcom 1
cbo 7
dl 0
loc 220
ccs 83
cts 85
cp 0.9765
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareQuery() 0 12 3
A prepareConditions() 0 13 4
B init() 0 17 5
C validateAttribute() 0 24 8
C modelExists() 0 34 7
A addComboNotUniqueError() 0 18 3
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\ActiveRecordInterface;
15
use yii\db\Query;
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. When validating single attribute, it may contain
67
     * the following placeholders which will be replaced accordingly by the validator:
68
     *
69
     * - `{attribute}`: the label of the attribute being validated
70
     * - `{value}`: the value of the attribute being validated
71
     *
72
     * When validating mutliple attributes, it may contain the following placeholders:
73
     *
74
     * - `{attributes}`: the labels of the attributes being validated.
75
     * - `{values}`: the values of the attributes being validated.
76
     *
77
     */
78
    public $message;
79
    /**
80
     * @var string
81
     * @since 2.0.9
82
     * @deprecated since version 2.0.10, to be removed in 2.1. Use [[message]] property
83
     * to setup custom message for multiple target attributes.
84
     */
85
    public $comboNotUnique;
86
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
     * @inheritdoc
95
     */
96 48
    public function init()
97
    {
98 48
        parent::init();
99 48
        if ($this->message !== null) {
100 3
            return;
101
        }
102 48
        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
103
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
104 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...
105 3
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
106 3
            } else {
107 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...
108
            }
109 6
        } else {
110 45
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
111
        }
112 48
    }
113
114
    /**
115
     * @inheritdoc
116
     */
117 39
    public function validateAttribute($model, $attribute)
118
    {
119
        /* @var $targetClass ActiveRecordInterface */
120 39
        $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
121 39
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
122 39
        $rawConditions = $this->prepareConditions($targetAttribute, $model, $attribute);
123 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...
124
125 39
        foreach ($rawConditions as $key => $value) {
126 39
            if (is_array($value)) {
127 6
                $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
128 6
                return;
129
            }
130 36
            $conditions[] = [$key => $value];
131 36
        }
132
133 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...
134 29
            if (count($targetAttribute) > 1) {
135 6
                $this->addComboNotUniqueError($model, $attribute);
136 6
            } else {
137 29
                $this->addError($model, $attribute, $this->message);
138
            }
139 29
        }
140 33
    }
141
142
    /**
143
     * Checks whether the $model exists in the database.
144
     *
145
     * @param string $targetClass the name of the ActiveRecord class that should be used to validate the uniqueness
146
     * of the current attribute value.
147
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
148
     * @param Model $model the data model to be validated
149
     *
150
     * @return bool whether the model already exists
151
     */
152 36
    private function modelExists($targetClass, $conditions, $model)
153
    {
154
        /** @var ActiveRecordInterface $targetClass $query */
155 36
        $query = $this->prepareQuery($targetClass, $conditions);
156
157 36
        if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
158
            // if current $model isn't in the database yet then it's OK just to call exists()
159
            // also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
160 33
            $exists = $query->exists();
161 30
        } else {
162
            // if current $model is in the database already we can't use exists()
163 13
            if ($query instanceof \yii\db\ActiveQuery) {
164
                // only select primary key to optimize query
165 13
                $query->select($targetClass::primaryKey());
166 13
            }
167 13
            $models = $query->limit(2)->asArray()->all();
168 13
            $n = count($models);
169 13
            if ($n === 1) {
170
                // if there is one record, check if it is the currently validated model
171 13
                $dbModel = reset($models);
172 13
                $pks = $targetClass::primaryKey();
173 13
                $pk = [];
174 13
                foreach($pks as $pkAttribute) {
175 13
                    $pk[$pkAttribute] = $dbModel[$pkAttribute];
176 13
                }
177 13
                $exists = ($pk != $model->getOldPrimaryKey(true));
178 13
            } else {
179
                // if there is more than one record, the value is not unique
180 3
                $exists = $n > 1;
181
            }
182
        }
183
184 33
        return $exists;
185
    }
186
187
    /**
188
     * Prepares a query by applying filtering conditions defined in $conditions method property
189
     * and [[filter]] class property.
190
     *
191
     * @param ActiveRecordInterface $targetClass the name of the ActiveRecord class that should be used to validate
192
     * the uniqueness of the current attribute value.
193
     * @param array $conditions conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format
194
     *
195
     * @return ActiveQueryInterface|ActiveQuery
196
     */
197 39
    private function prepareQuery($targetClass, $conditions)
198
    {
199 39
        $query = $targetClass::find();
200 39
        $query->andWhere($conditions);
201 39
        if ($this->filter instanceof \Closure) {
202 3
            call_user_func($this->filter, $query);
203 39
        } elseif ($this->filter !== null) {
204 3
            $query->andWhere($this->filter);
205 3
        }
206
207 39
        return $query;
208
    }
209
210
    /**
211
     * Processes attributes' relations described in $targetAttribute parameter into conditions, compatible with
212
     * [[\yii\db\Query::where()|Query::where()]] key-value format.
213
     *
214
     * @param string|array $targetAttribute the name of the [[\yii\db\ActiveRecord|ActiveRecord]] attribute that
215
     * should be used to validate the uniqueness of the current attribute value. You may use an array to validate
216
     * the uniqueness of multiple columns at the same time. The array values are the attributes that will be
217
     * used to validate the uniqueness, while the array keys are the attributes whose values are to be validated.
218
     * If the key and the value are the same, you can just specify the value.
219
     * @param Model $model the data model to be validated
220
     * @param string $attribute the name of the attribute to be validated in the $model
221
222
     * @return array conditions, compatible with [[\yii\db\Query::where()|Query::where()]] key-value format.
223
     */
224 42
    private function prepareConditions($targetAttribute, $model, $attribute)
225
    {
226 42
        if (is_array($targetAttribute)) {
227 15
            $conditions = [];
228 15
            foreach ($targetAttribute as $k => $v) {
229 15
                $conditions[$v] = is_int($k) ? $model->$v : $model->$k;
230 15
            }
231 15
        } else {
232 36
            $conditions = [$targetAttribute => $model->$attribute];
233
        }
234
235 42
        return $conditions;
236
    }
237
238
    /**
239
     * Builds and adds [[comboNotUnique]] error message to the specified model attribute.
240
     * @param \yii\base\Model $model the data model.
241
     * @param string $attribute the name of the attribute.
242
     */
243 6
    private function addComboNotUniqueError($model, $attribute)
244
    {
245 6
        $attributeCombo = [];
246 6
        $valueCombo = [];
247 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...
248 6
            if(is_int($key)) {
249 6
                $attributeCombo[] = $model->getAttributeLabel($value);
250 6
                $valueCombo[] = '"' . $model->$value . '"';
251 6
            } else {
252
                $attributeCombo[] = $model->getAttributeLabel($key);
253
                $valueCombo[] = '"' . $model->$key . '"';
254
            }
255 6
        }
256 6
        $this->addError($model, $attribute, $this->message, [
257 6
            'attributes' => Inflector::sentence($attributeCombo),
258 6
            'values' => implode('-', $valueCombo)
259 6
        ]);
260 6
    }
261
}
262