Completed
Push — 2.0.15-dev ( 0af1c0 )
by Carsten
12:44
created

ActiveRecord   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 668
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Test Coverage

Coverage 72.94%

Importance

Changes 0
Metric Value
wmc 69
lcom 1
cbo 16
dl 0
loc 668
ccs 124
cts 170
cp 0.7294
rs 2.4452
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
B loadDefaultValues() 0 10 5
A getDb() 0 4 1
A findBySql() 0 7 1
C findByCondition() 0 23 7
B filterCondition() 0 17 5
A refresh() 0 15 2
A updateAll() 0 7 1
A updateAllCounters() 0 12 2
A deleteAll() 0 7 1
A find() 0 4 1
A tableName() 0 4 1
A getTableSchema() 0 12 2
A primaryKey() 0 4 1
A attributes() 0 4 1
A transactions() 0 4 1
A populateRecord() 0 10 3
C insert() 0 29 7
A insertInternal() 0 21 4
C update() 0 29 7
B delete() 0 24 5
B deleteInternal() 0 22 5
A equals() 0 8 4
A isTransactional() 0 7 2

How to fix   Complexity   

Complex Class

Complex classes like ActiveRecord often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ActiveRecord, and based on these observations, apply Extract Interface, too.

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\db;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\InvalidConfigException;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\Inflector;
15
use yii\helpers\StringHelper;
16
17
/**
18
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
19
 *
20
 * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
21
 * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
22
 * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
23
 * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
24
 *
25
 * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
26
 * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
27
 * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
28
 * the `name` column for the table row, you can use the expression `$customer->name`.
29
 * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
30
 * But Active Record provides much more functionality than this.
31
 *
32
 * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
33
 * implement the `tableName` method:
34
 *
35
 * ```php
36
 * <?php
37
 *
38
 * class Customer extends \yii\db\ActiveRecord
39
 * {
40
 *     public static function tableName()
41
 *     {
42
 *         return 'customer';
43
 *     }
44
 * }
45
 * ```
46
 *
47
 * The `tableName` method only has to return the name of the database table associated with the class.
48
 *
49
 * > Tip: You may also use the [Gii code generator](guide:start-gii) to generate ActiveRecord classes from your
50
 * > database tables.
51
 *
52
 * Class instances are obtained in one of two ways:
53
 *
54
 * * Using the `new` operator to create a new, empty object
55
 * * Using a method to fetch an existing record (or records) from the database
56
 *
57
 * Below is an example showing some typical usage of ActiveRecord:
58
 *
59
 * ```php
60
 * $user = new User();
61
 * $user->name = 'Qiang';
62
 * $user->save();  // a new row is inserted into user table
63
 *
64
 * // the following will retrieve the user 'CeBe' from the database
65
 * $user = User::find()->where(['name' => 'CeBe'])->one();
66
 *
67
 * // this will get related records from orders table when relation is defined
68
 * $orders = $user->orders;
69
 * ```
70
 *
71
 * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](guide:db-active-record).
72
 *
73
 * @method ActiveQuery hasMany($class, array $link) see [[BaseActiveRecord::hasMany()]] for more info
74
 * @method ActiveQuery hasOne($class, array $link) see [[BaseActiveRecord::hasOne()]] for more info
75
 *
76
 * @author Qiang Xue <[email protected]>
77
 * @author Carsten Brandt <[email protected]>
78
 * @since 2.0
79
 */
80
class ActiveRecord extends BaseActiveRecord
81
{
82
    /**
83
     * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
84
     */
85
    const OP_INSERT = 0x01;
86
    /**
87
     * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
88
     */
89
    const OP_UPDATE = 0x02;
90
    /**
91
     * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
92
     */
93
    const OP_DELETE = 0x04;
94
    /**
95
     * All three operations: insert, update, delete.
96
     * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
97
     */
98
    const OP_ALL = 0x07;
99
100
101
    /**
102
     * Loads default values from database table schema.
103
     *
104
     * You may call this method to load default values after creating a new instance:
105
     *
106
     * ```php
107
     * // class Customer extends \yii\db\ActiveRecord
108
     * $customer = new Customer();
109
     * $customer->loadDefaultValues();
110
     * ```
111
     *
112
     * @param bool $skipIfSet whether existing value should be preserved.
113
     * This will only set defaults for attributes that are `null`.
114
     * @return $this the model instance itself.
115
     */
116 4
    public function loadDefaultValues($skipIfSet = true)
117
    {
118 4
        foreach (static::getTableSchema()->columns as $column) {
119 4
            if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
120 4
                $this->{$column->name} = $column->defaultValue;
121
            }
122
        }
123
124 4
        return $this;
125
    }
126
127
    /**
128
     * Returns the database connection used by this AR class.
129
     * By default, the "db" application component is used as the database connection.
130
     * You may override this method if you want to use a different database connection.
131
     * @return Connection the database connection used by this AR class.
132
     */
133 44
    public static function getDb()
134
    {
135 44
        return Yii::$app->getDb();
136
    }
137
138
    /**
139
     * Creates an [[ActiveQuery]] instance with a given SQL statement.
140
     *
141
     * Note that because the SQL statement is already specified, calling additional
142
     * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
143
     * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
144
     * still fine.
145
     *
146
     * Below is an example:
147
     *
148
     * ```php
149
     * $customers = Customer::findBySql('SELECT * FROM customer')->all();
150
     * ```
151
     *
152
     * @param string $sql the SQL statement to be executed
153
     * @param array $params parameters to be bound to the SQL statement during execution.
154
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
155
     */
156 6
    public static function findBySql($sql, $params = [])
157
    {
158 6
        $query = static::find();
159 6
        $query->sql = $sql;
160
161 6
        return $query->params($params);
162
    }
163
164
    /**
165
     * Finds ActiveRecord instance(s) by the given condition.
166
     * This method is internally called by [[findOne()]] and [[findAll()]].
167
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
168
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
169
     * @throws InvalidConfigException if there is no primary key defined.
170
     * @internal
171
     */
172 202
    protected static function findByCondition($condition)
173
    {
174 202
        $query = static::find();
175
176 202
        if (!ArrayHelper::isAssociative($condition)) {
177
            // query by primary key
178 161
            $primaryKey = static::primaryKey();
179 161
            if (isset($primaryKey[0])) {
180 161
                $pk = $primaryKey[0];
181 161
                if (!empty($query->join) || !empty($query->joinWith)) {
182 3
                    $pk = static::tableName() . '.' . $pk;
183
                }
184
                // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
185 161
                $condition = [$pk => is_array($condition) ? array_values($condition) : $condition];
186
            } else {
187 161
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
188
            }
189 53
        } elseif (is_array($condition)) {
190 53
            $condition = static::filterCondition($condition);
191
        }
192
193 190
        return $query->andWhere($condition);
194
    }
195
196
    /**
197
     * Filters array condition before it is assiged to a Query filter.
198
     *
199
     * This method will ensure that an array condition only filters on existing table columns.
200
     *
201
     * @param array $condition condition to filter.
202
     * @return array filtered condition.
203
     * @throws InvalidArgumentException in case array contains unsafe values.
204
     * @since 2.0.15
205
     * @internal
206
     */
207 53
    protected static function filterCondition(array $condition)
208
    {
209 53
        $result = [];
210
        // valid column names are table column names or column names prefixed with table name
211 53
        $columnNames = static::getTableSchema()->getColumnNames();
212 53
        $columnNames = array_merge($columnNames, array_map(function($columnName) {
213 53
            return static::tableName() . ".$columnName";
214 53
        }, $columnNames));
215 53
        foreach ($condition as $key => $value) {
216 53
            if (is_string($key) && !in_array($key, $columnNames, true)) {
217 12
                throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
218
            }
219 41
            $result[$key] = is_array($value) ? array_values($value) : $value;
220
        }
221
222 41
        return $result;
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228 29
    public function refresh()
229
    {
230 29
        $query = static::find();
231 29
        $tableName = key($query->getTablesUsedInFrom());
232 29
        $pk = [];
233
        // disambiguate column names in case ActiveQuery adds a JOIN
234 29
        foreach ($this->getPrimaryKey(true) as $key => $value) {
235 29
            $pk[$tableName . '.' . $key] = $value;
236
        }
237 29
        $query->where($pk);
238
239
        /* @var $record BaseActiveRecord */
240 29
        $record = $query->one();
241 29
        return $this->refreshInternal($record);
242
    }
243
244
    /**
245
     * Updates the whole table using the provided attribute values and conditions.
246
     *
247
     * For example, to change the status to be 1 for all customers whose status is 2:
248
     *
249
     * ```php
250
     * Customer::updateAll(['status' => 1], 'status = 2');
251
     * ```
252
     *
253
     * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
254
     *
255
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
256
     * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
257
     * call [[update()]] on each of them. For example an equivalent of the example above would be:
258
     *
259
     * ```php
260
     * $models = Customer::find()->where('status = 2')->all();
261
     * foreach ($models as $model) {
262
     *     $model->status = 1;
263
     *     $model->update(false); // skipping validation as no user input is involved
264
     * }
265
     * ```
266
     *
267
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
268
     *
269
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
270
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
271
     * Please refer to [[Query::where()]] on how to specify this parameter.
272
     * @param array $params the parameters (name => value) to be bound to the query.
273
     * @return int the number of rows updated
274
     */
275 49
    public static function updateAll($attributes, $condition = '', $params = [])
276
    {
277 49
        $command = static::getDb()->createCommand();
278 49
        $command->update(static::tableName(), $attributes, $condition, $params);
279
280 49
        return $command->execute();
281
    }
282
283
    /**
284
     * Updates the whole table using the provided counter changes and conditions.
285
     *
286
     * For example, to increment all customers' age by 1,
287
     *
288
     * ```php
289
     * Customer::updateAllCounters(['age' => 1]);
290
     * ```
291
     *
292
     * Note that this method will not trigger any events.
293
     *
294
     * @param array $counters the counters to be updated (attribute name => increment value).
295
     * Use negative values if you want to decrement the counters.
296
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
297
     * Please refer to [[Query::where()]] on how to specify this parameter.
298
     * @param array $params the parameters (name => value) to be bound to the query.
299
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
300
     * @return int the number of rows updated
301
     */
302 6
    public static function updateAllCounters($counters, $condition = '', $params = [])
303
    {
304 6
        $n = 0;
305 6
        foreach ($counters as $name => $value) {
306 6
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
307 6
            $n++;
308
        }
309 6
        $command = static::getDb()->createCommand();
310 6
        $command->update(static::tableName(), $counters, $condition, $params);
311
312 6
        return $command->execute();
313
    }
314
315
    /**
316
     * Deletes rows in the table using the provided conditions.
317
     *
318
     * For example, to delete all customers whose status is 3:
319
     *
320
     * ```php
321
     * Customer::deleteAll('status = 3');
322
     * ```
323
     *
324
     * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
325
     *
326
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
327
     * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
328
     * call [[delete()]] on each of them. For example an equivalent of the example above would be:
329
     *
330
     * ```php
331
     * $models = Customer::find()->where('status = 3')->all();
332
     * foreach ($models as $model) {
333
     *     $model->delete();
334
     * }
335
     * ```
336
     *
337
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
338
     *
339
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
340
     * Please refer to [[Query::where()]] on how to specify this parameter.
341
     * @param array $params the parameters (name => value) to be bound to the query.
342
     * @return int the number of rows deleted
343
     */
344 31
    public static function deleteAll($condition = null, $params = [])
345
    {
346 31
        $command = static::getDb()->createCommand();
347 31
        $command->delete(static::tableName(), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 344 can also be of type null; however, yii\db\Command::delete() does only seem to accept string|array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
348
349 31
        return $command->execute();
350
    }
351
352
    /**
353
     * {@inheritdoc}
354
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
355
     */
356 299
    public static function find()
357
    {
358 299
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method 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 method will be removed from the class and what other method or class to use instead.

Loading history...
359
    }
360
361
    /**
362
     * Declares the name of the database table associated with this AR class.
363
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
364
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
365
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
366
     * if the table is not named after this convention.
367
     * @return string the table name
368
     */
369 15
    public static function tableName()
370
    {
371 15
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
372
    }
373
374
    /**
375
     * Returns the schema information of the DB table associated with this AR class.
376
     * @return TableSchema the schema information of the DB table associated with this AR class.
377
     * @throws InvalidConfigException if the table for the AR class does not exist.
378
     */
379 416
    public static function getTableSchema()
380
    {
381 416
        $tableSchema = static::getDb()
382 416
            ->getSchema()
383 416
            ->getTableSchema(static::tableName());
384
385 416
        if ($tableSchema === null) {
386
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
387
        }
388
389 416
        return $tableSchema;
390
    }
391
392
    /**
393
     * Returns the primary key name(s) for this AR class.
394
     * The default implementation will return the primary key(s) as declared
395
     * in the DB table that is associated with this AR class.
396
     *
397
     * If the DB table does not declare any primary key, you should override
398
     * this method to return the attributes that you want to use as primary keys
399
     * for this AR class.
400
     *
401
     * Note that an array should be returned even for a table with single primary key.
402
     *
403
     * @return string[] the primary keys of the associated database table.
404
     */
405 254
    public static function primaryKey()
406
    {
407 254
        return static::getTableSchema()->primaryKey;
408
    }
409
410
    /**
411
     * Returns the list of all attribute names of the model.
412
     * The default implementation will return all column names of the table associated with this AR class.
413
     * @return array list of attribute names.
414
     */
415 401
    public function attributes()
416
    {
417 401
        return array_keys(static::getTableSchema()->columns);
418
    }
419
420
    /**
421
     * Declares which DB operations should be performed within a transaction in different scenarios.
422
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
423
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
424
     * By default, these methods are NOT enclosed in a DB transaction.
425
     *
426
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
427
     * in transactions. You can do so by overriding this method and returning the operations
428
     * that need to be transactional. For example,
429
     *
430
     * ```php
431
     * return [
432
     *     'admin' => self::OP_INSERT,
433
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
434
     *     // the above is equivalent to the following:
435
     *     // 'api' => self::OP_ALL,
436
     *
437
     * ];
438
     * ```
439
     *
440
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
441
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
442
     * in a transaction.
443
     *
444
     * @return array the declarations of transactional operations. The array keys are scenarios names,
445
     * and the array values are the corresponding transaction operations.
446
     */
447 107
    public function transactions()
448
    {
449 107
        return [];
450
    }
451
452
    /**
453
     * {@inheritdoc}
454
     */
455 322
    public static function populateRecord($record, $row)
456
    {
457 322
        $columns = static::getTableSchema()->columns;
458 322
        foreach ($row as $name => $value) {
459 322
            if (isset($columns[$name])) {
460 322
                $row[$name] = $columns[$name]->phpTypecast($value);
461
            }
462
        }
463 322
        parent::populateRecord($record, $row);
464 322
    }
465
466
    /**
467
     * Inserts a row into the associated database table using the attribute values of this record.
468
     *
469
     * This method performs the following steps in order:
470
     *
471
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
472
     *    returns `false`, the rest of the steps will be skipped;
473
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
474
     *    failed, the rest of the steps will be skipped;
475
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
476
     *    the rest of the steps will be skipped;
477
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
478
     * 5. call [[afterSave()]];
479
     *
480
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
481
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
482
     * will be raised by the corresponding methods.
483
     *
484
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
485
     *
486
     * If the table's primary key is auto-incremental and is `null` during insertion,
487
     * it will be populated with the actual value after insertion.
488
     *
489
     * For example, to insert a customer record:
490
     *
491
     * ```php
492
     * $customer = new Customer;
493
     * $customer->name = $name;
494
     * $customer->email = $email;
495
     * $customer->insert();
496
     * ```
497
     *
498
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
499
     * before saving the record. Defaults to `true`. If the validation fails, the record
500
     * will not be saved to the database and this method will return `false`.
501
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
502
     * meaning all attributes that are loaded from DB will be saved.
503
     * @return bool whether the attributes are valid and the record is inserted successfully.
504
     * @throws \Exception|\Throwable in case insert failed.
505
     */
506 91
    public function insert($runValidation = true, $attributes = null)
507
    {
508 91
        if ($runValidation && !$this->validate($attributes)) {
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 506 can also be of type array; however, yii\base\Model::validate() does only seem to accept array<integer,string>|string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
509
            Yii::info('Model not inserted due to validation error.', __METHOD__);
510
            return false;
511
        }
512
513 91
        if (!$this->isTransactional(self::OP_INSERT)) {
514 91
            return $this->insertInternal($attributes);
515
        }
516
517
        $transaction = static::getDb()->beginTransaction();
518
        try {
519
            $result = $this->insertInternal($attributes);
520
            if ($result === false) {
521
                $transaction->rollBack();
522
            } else {
523
                $transaction->commit();
524
            }
525
526
            return $result;
527
        } catch (\Exception $e) {
528
            $transaction->rollBack();
529
            throw $e;
530
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
531
            $transaction->rollBack();
532
            throw $e;
533
        }
534
    }
535
536
    /**
537
     * Inserts an ActiveRecord into DB without considering transaction.
538
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
539
     * meaning all attributes that are loaded from DB will be saved.
540
     * @return bool whether the record is inserted successfully.
541
     */
542 91
    protected function insertInternal($attributes = null)
543
    {
544 91
        if (!$this->beforeSave(true)) {
545
            return false;
546
        }
547 91
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 542 can also be of type array; however, yii\db\BaseActiveRecord::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
548 91
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
549
            return false;
550
        }
551 91
        foreach ($primaryKeys as $name => $value) {
552 80
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
553 80
            $this->setAttribute($name, $id);
554 80
            $values[$name] = $id;
555
        }
556
557 91
        $changedAttributes = array_fill_keys(array_keys($values), null);
558 91
        $this->setOldAttributes($values);
559 91
        $this->afterSave(true, $changedAttributes);
560
561 91
        return true;
562
    }
563
564
    /**
565
     * Saves the changes to this active record into the associated database table.
566
     *
567
     * This method performs the following steps in order:
568
     *
569
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
570
     *    returns `false`, the rest of the steps will be skipped;
571
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
572
     *    failed, the rest of the steps will be skipped;
573
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
574
     *    the rest of the steps will be skipped;
575
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
576
     * 5. call [[afterSave()]];
577
     *
578
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
579
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
580
     * will be raised by the corresponding methods.
581
     *
582
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
583
     *
584
     * For example, to update a customer record:
585
     *
586
     * ```php
587
     * $customer = Customer::findOne($id);
588
     * $customer->name = $name;
589
     * $customer->email = $email;
590
     * $customer->update();
591
     * ```
592
     *
593
     * Note that it is possible the update does not affect any row in the table.
594
     * In this case, this method will return 0. For this reason, you should use the following
595
     * code to check if update() is successful or not:
596
     *
597
     * ```php
598
     * if ($customer->update() !== false) {
599
     *     // update successful
600
     * } else {
601
     *     // update failed
602
     * }
603
     * ```
604
     *
605
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
606
     * before saving the record. Defaults to `true`. If the validation fails, the record
607
     * will not be saved to the database and this method will return `false`.
608
     * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
609
     * meaning all attributes that are loaded from DB will be saved.
610
     * @return int|false the number of rows affected, or false if validation fails
611
     * or [[beforeSave()]] stops the updating process.
612
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
613
     * being updated is outdated.
614
     * @throws \Exception|\Throwable in case update failed.
615
     */
616 38
    public function update($runValidation = true, $attributeNames = null)
617
    {
618 38
        if ($runValidation && !$this->validate($attributeNames)) {
0 ignored issues
show
Bug introduced by
It seems like $attributeNames defined by parameter $attributeNames on line 616 can also be of type array; however, yii\base\Model::validate() does only seem to accept array<integer,string>|string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
619
            Yii::info('Model not updated due to validation error.', __METHOD__);
620
            return false;
621
        }
622
623 38
        if (!$this->isTransactional(self::OP_UPDATE)) {
624 38
            return $this->updateInternal($attributeNames);
625
        }
626
627
        $transaction = static::getDb()->beginTransaction();
628
        try {
629
            $result = $this->updateInternal($attributeNames);
630
            if ($result === false) {
631
                $transaction->rollBack();
632
            } else {
633
                $transaction->commit();
634
            }
635
636
            return $result;
637
        } catch (\Exception $e) {
638
            $transaction->rollBack();
639
            throw $e;
640
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
641
            $transaction->rollBack();
642
            throw $e;
643
        }
644
    }
645
646
    /**
647
     * Deletes the table row corresponding to this active record.
648
     *
649
     * This method performs the following steps in order:
650
     *
651
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
652
     *    rest of the steps;
653
     * 2. delete the record from the database;
654
     * 3. call [[afterDelete()]].
655
     *
656
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
657
     * will be raised by the corresponding methods.
658
     *
659
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
660
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
661
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
662
     * being deleted is outdated.
663
     * @throws \Exception|\Throwable in case delete failed.
664
     */
665 6
    public function delete()
666
    {
667 6
        if (!$this->isTransactional(self::OP_DELETE)) {
668 6
            return $this->deleteInternal();
669
        }
670
671
        $transaction = static::getDb()->beginTransaction();
672
        try {
673
            $result = $this->deleteInternal();
674
            if ($result === false) {
675
                $transaction->rollBack();
676
            } else {
677
                $transaction->commit();
678
            }
679
680
            return $result;
681
        } catch (\Exception $e) {
682
            $transaction->rollBack();
683
            throw $e;
684
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
685
            $transaction->rollBack();
686
            throw $e;
687
        }
688
    }
689
690
    /**
691
     * Deletes an ActiveRecord without considering transaction.
692
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
693
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
694
     * @throws StaleObjectException
695
     */
696 6
    protected function deleteInternal()
697
    {
698 6
        if (!$this->beforeDelete()) {
699
            return false;
700
        }
701
702
        // we do not check the return value of deleteAll() because it's possible
703
        // the record is already deleted in the database and thus the method will return 0
704 6
        $condition = $this->getOldPrimaryKey(true);
705 6
        $lock = $this->optimisticLock();
706 6
        if ($lock !== null) {
707
            $condition[$lock] = $this->$lock;
708
        }
709 6
        $result = static::deleteAll($condition);
710 6
        if ($lock !== null && !$result) {
711
            throw new StaleObjectException('The object being deleted is outdated.');
712
        }
713 6
        $this->setOldAttributes(null);
714 6
        $this->afterDelete();
715
716 6
        return $result;
717
    }
718
719
    /**
720
     * Returns a value indicating whether the given active record is the same as the current one.
721
     * The comparison is made by comparing the table names and the primary key values of the two active records.
722
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
723
     * @param ActiveRecord $record record to compare to
724
     * @return bool whether the two active records refer to the same row in the same database table.
725
     */
726 3
    public function equals($record)
727
    {
728 3
        if ($this->isNewRecord || $record->isNewRecord) {
729 3
            return false;
730
        }
731
732 3
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
733
    }
734
735
    /**
736
     * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
737
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
738
     * @return bool whether the specified operation is transactional in the current [[scenario]].
739
     */
740 107
    public function isTransactional($operation)
741
    {
742 107
        $scenario = $this->getScenario();
743 107
        $transactions = $this->transactions();
744
745 107
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
746
    }
747
}
748