Completed
Push — 2.0.15-dev ( 0af1c0...b195d9 )
by Carsten
17:17 queued 08:28
created

ActiveRecord   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 669
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Test Coverage

Coverage 73.1%

Importance

Changes 0
Metric Value
wmc 69
lcom 1
cbo 16
dl 0
loc 669
ccs 125
cts 171
cp 0.731
rs 2.4396
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
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
B loadDefaultValues() 0 10 5
A getDb() 0 4 1
A findBySql() 0 7 1
C findByCondition() 0 23 7
B filterCondition() 0 18 5

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
        $tableName = static::tableName();
213 53
        $columnNames = array_merge($columnNames, array_map(function($columnName) use ($tableName) {
214 53
            return "$tableName.$columnName";
215 53
        }, $columnNames));
216 53
        foreach ($condition as $key => $value) {
217 53
            if (is_string($key) && !in_array($key, $columnNames, true)) {
218 12
                throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
219
            }
220 41
            $result[$key] = is_array($value) ? array_values($value) : $value;
221
        }
222
223 41
        return $result;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229 29
    public function refresh()
230
    {
231 29
        $query = static::find();
232 29
        $tableName = key($query->getTablesUsedInFrom());
233 29
        $pk = [];
234
        // disambiguate column names in case ActiveQuery adds a JOIN
235 29
        foreach ($this->getPrimaryKey(true) as $key => $value) {
236 29
            $pk[$tableName . '.' . $key] = $value;
237
        }
238 29
        $query->where($pk);
239
240
        /* @var $record BaseActiveRecord */
241 29
        $record = $query->one();
242 29
        return $this->refreshInternal($record);
243
    }
244
245
    /**
246
     * Updates the whole table using the provided attribute values and conditions.
247
     *
248
     * For example, to change the status to be 1 for all customers whose status is 2:
249
     *
250
     * ```php
251
     * Customer::updateAll(['status' => 1], 'status = 2');
252
     * ```
253
     *
254
     * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
255
     *
256
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
257
     * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
258
     * call [[update()]] on each of them. For example an equivalent of the example above would be:
259
     *
260
     * ```php
261
     * $models = Customer::find()->where('status = 2')->all();
262
     * foreach ($models as $model) {
263
     *     $model->status = 1;
264
     *     $model->update(false); // skipping validation as no user input is involved
265
     * }
266
     * ```
267
     *
268
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
269
     *
270
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
271
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
272
     * Please refer to [[Query::where()]] on how to specify this parameter.
273
     * @param array $params the parameters (name => value) to be bound to the query.
274
     * @return int the number of rows updated
275
     */
276 49
    public static function updateAll($attributes, $condition = '', $params = [])
277
    {
278 49
        $command = static::getDb()->createCommand();
279 49
        $command->update(static::tableName(), $attributes, $condition, $params);
280
281 49
        return $command->execute();
282
    }
283
284
    /**
285
     * Updates the whole table using the provided counter changes and conditions.
286
     *
287
     * For example, to increment all customers' age by 1,
288
     *
289
     * ```php
290
     * Customer::updateAllCounters(['age' => 1]);
291
     * ```
292
     *
293
     * Note that this method will not trigger any events.
294
     *
295
     * @param array $counters the counters to be updated (attribute name => increment value).
296
     * Use negative values if you want to decrement the counters.
297
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
298
     * Please refer to [[Query::where()]] on how to specify this parameter.
299
     * @param array $params the parameters (name => value) to be bound to the query.
300
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
301
     * @return int the number of rows updated
302
     */
303 6
    public static function updateAllCounters($counters, $condition = '', $params = [])
304
    {
305 6
        $n = 0;
306 6
        foreach ($counters as $name => $value) {
307 6
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
308 6
            $n++;
309
        }
310 6
        $command = static::getDb()->createCommand();
311 6
        $command->update(static::tableName(), $counters, $condition, $params);
312
313 6
        return $command->execute();
314
    }
315
316
    /**
317
     * Deletes rows in the table using the provided conditions.
318
     *
319
     * For example, to delete all customers whose status is 3:
320
     *
321
     * ```php
322
     * Customer::deleteAll('status = 3');
323
     * ```
324
     *
325
     * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
326
     *
327
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
328
     * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
329
     * call [[delete()]] on each of them. For example an equivalent of the example above would be:
330
     *
331
     * ```php
332
     * $models = Customer::find()->where('status = 3')->all();
333
     * foreach ($models as $model) {
334
     *     $model->delete();
335
     * }
336
     * ```
337
     *
338
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
339
     *
340
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
341
     * Please refer to [[Query::where()]] on how to specify this parameter.
342
     * @param array $params the parameters (name => value) to be bound to the query.
343
     * @return int the number of rows deleted
344
     */
345 31
    public static function deleteAll($condition = null, $params = [])
346
    {
347 31
        $command = static::getDb()->createCommand();
348 31
        $command->delete(static::tableName(), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 345 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...
349
350 31
        return $command->execute();
351
    }
352
353
    /**
354
     * {@inheritdoc}
355
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
356
     */
357 299
    public static function find()
358
    {
359 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...
360
    }
361
362
    /**
363
     * Declares the name of the database table associated with this AR class.
364
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
365
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
366
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
367
     * if the table is not named after this convention.
368
     * @return string the table name
369
     */
370 15
    public static function tableName()
371
    {
372 15
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
373
    }
374
375
    /**
376
     * Returns the schema information of the DB table associated with this AR class.
377
     * @return TableSchema the schema information of the DB table associated with this AR class.
378
     * @throws InvalidConfigException if the table for the AR class does not exist.
379
     */
380 416
    public static function getTableSchema()
381
    {
382 416
        $tableSchema = static::getDb()
383 416
            ->getSchema()
384 416
            ->getTableSchema(static::tableName());
385
386 416
        if ($tableSchema === null) {
387
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
388
        }
389
390 416
        return $tableSchema;
391
    }
392
393
    /**
394
     * Returns the primary key name(s) for this AR class.
395
     * The default implementation will return the primary key(s) as declared
396
     * in the DB table that is associated with this AR class.
397
     *
398
     * If the DB table does not declare any primary key, you should override
399
     * this method to return the attributes that you want to use as primary keys
400
     * for this AR class.
401
     *
402
     * Note that an array should be returned even for a table with single primary key.
403
     *
404
     * @return string[] the primary keys of the associated database table.
405
     */
406 254
    public static function primaryKey()
407
    {
408 254
        return static::getTableSchema()->primaryKey;
409
    }
410
411
    /**
412
     * Returns the list of all attribute names of the model.
413
     * The default implementation will return all column names of the table associated with this AR class.
414
     * @return array list of attribute names.
415
     */
416 401
    public function attributes()
417
    {
418 401
        return array_keys(static::getTableSchema()->columns);
419
    }
420
421
    /**
422
     * Declares which DB operations should be performed within a transaction in different scenarios.
423
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
424
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
425
     * By default, these methods are NOT enclosed in a DB transaction.
426
     *
427
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
428
     * in transactions. You can do so by overriding this method and returning the operations
429
     * that need to be transactional. For example,
430
     *
431
     * ```php
432
     * return [
433
     *     'admin' => self::OP_INSERT,
434
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
435
     *     // the above is equivalent to the following:
436
     *     // 'api' => self::OP_ALL,
437
     *
438
     * ];
439
     * ```
440
     *
441
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
442
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
443
     * in a transaction.
444
     *
445
     * @return array the declarations of transactional operations. The array keys are scenarios names,
446
     * and the array values are the corresponding transaction operations.
447
     */
448 107
    public function transactions()
449
    {
450 107
        return [];
451
    }
452
453
    /**
454
     * {@inheritdoc}
455
     */
456 322
    public static function populateRecord($record, $row)
457
    {
458 322
        $columns = static::getTableSchema()->columns;
459 322
        foreach ($row as $name => $value) {
460 322
            if (isset($columns[$name])) {
461 322
                $row[$name] = $columns[$name]->phpTypecast($value);
462
            }
463
        }
464 322
        parent::populateRecord($record, $row);
465 322
    }
466
467
    /**
468
     * Inserts a row into the associated database table using the attribute values of this record.
469
     *
470
     * This method performs the following steps in order:
471
     *
472
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
473
     *    returns `false`, the rest of the steps will be skipped;
474
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
475
     *    failed, the rest of the steps will be skipped;
476
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
477
     *    the rest of the steps will be skipped;
478
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
479
     * 5. call [[afterSave()]];
480
     *
481
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
482
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
483
     * will be raised by the corresponding methods.
484
     *
485
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
486
     *
487
     * If the table's primary key is auto-incremental and is `null` during insertion,
488
     * it will be populated with the actual value after insertion.
489
     *
490
     * For example, to insert a customer record:
491
     *
492
     * ```php
493
     * $customer = new Customer;
494
     * $customer->name = $name;
495
     * $customer->email = $email;
496
     * $customer->insert();
497
     * ```
498
     *
499
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
500
     * before saving the record. Defaults to `true`. If the validation fails, the record
501
     * will not be saved to the database and this method will return `false`.
502
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
503
     * meaning all attributes that are loaded from DB will be saved.
504
     * @return bool whether the attributes are valid and the record is inserted successfully.
505
     * @throws \Exception|\Throwable in case insert failed.
506
     */
507 91
    public function insert($runValidation = true, $attributes = null)
508
    {
509 91
        if ($runValidation && !$this->validate($attributes)) {
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 507 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...
510
            Yii::info('Model not inserted due to validation error.', __METHOD__);
511
            return false;
512
        }
513
514 91
        if (!$this->isTransactional(self::OP_INSERT)) {
515 91
            return $this->insertInternal($attributes);
516
        }
517
518
        $transaction = static::getDb()->beginTransaction();
519
        try {
520
            $result = $this->insertInternal($attributes);
521
            if ($result === false) {
522
                $transaction->rollBack();
523
            } else {
524
                $transaction->commit();
525
            }
526
527
            return $result;
528
        } catch (\Exception $e) {
529
            $transaction->rollBack();
530
            throw $e;
531
        } 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...
532
            $transaction->rollBack();
533
            throw $e;
534
        }
535
    }
536
537
    /**
538
     * Inserts an ActiveRecord into DB without considering transaction.
539
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
540
     * meaning all attributes that are loaded from DB will be saved.
541
     * @return bool whether the record is inserted successfully.
542
     */
543 91
    protected function insertInternal($attributes = null)
544
    {
545 91
        if (!$this->beforeSave(true)) {
546
            return false;
547
        }
548 91
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 543 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...
549 91
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
550
            return false;
551
        }
552 91
        foreach ($primaryKeys as $name => $value) {
553 80
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
554 80
            $this->setAttribute($name, $id);
555 80
            $values[$name] = $id;
556
        }
557
558 91
        $changedAttributes = array_fill_keys(array_keys($values), null);
559 91
        $this->setOldAttributes($values);
560 91
        $this->afterSave(true, $changedAttributes);
561
562 91
        return true;
563
    }
564
565
    /**
566
     * Saves the changes to this active record into the associated database table.
567
     *
568
     * This method performs the following steps in order:
569
     *
570
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
571
     *    returns `false`, the rest of the steps will be skipped;
572
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
573
     *    failed, the rest of the steps will be skipped;
574
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
575
     *    the rest of the steps will be skipped;
576
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
577
     * 5. call [[afterSave()]];
578
     *
579
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
580
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
581
     * will be raised by the corresponding methods.
582
     *
583
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
584
     *
585
     * For example, to update a customer record:
586
     *
587
     * ```php
588
     * $customer = Customer::findOne($id);
589
     * $customer->name = $name;
590
     * $customer->email = $email;
591
     * $customer->update();
592
     * ```
593
     *
594
     * Note that it is possible the update does not affect any row in the table.
595
     * In this case, this method will return 0. For this reason, you should use the following
596
     * code to check if update() is successful or not:
597
     *
598
     * ```php
599
     * if ($customer->update() !== false) {
600
     *     // update successful
601
     * } else {
602
     *     // update failed
603
     * }
604
     * ```
605
     *
606
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
607
     * before saving the record. Defaults to `true`. If the validation fails, the record
608
     * will not be saved to the database and this method will return `false`.
609
     * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
610
     * meaning all attributes that are loaded from DB will be saved.
611
     * @return int|false the number of rows affected, or false if validation fails
612
     * or [[beforeSave()]] stops the updating process.
613
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
614
     * being updated is outdated.
615
     * @throws \Exception|\Throwable in case update failed.
616
     */
617 38
    public function update($runValidation = true, $attributeNames = null)
618
    {
619 38
        if ($runValidation && !$this->validate($attributeNames)) {
0 ignored issues
show
Bug introduced by
It seems like $attributeNames defined by parameter $attributeNames on line 617 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...
620
            Yii::info('Model not updated due to validation error.', __METHOD__);
621
            return false;
622
        }
623
624 38
        if (!$this->isTransactional(self::OP_UPDATE)) {
625 38
            return $this->updateInternal($attributeNames);
626
        }
627
628
        $transaction = static::getDb()->beginTransaction();
629
        try {
630
            $result = $this->updateInternal($attributeNames);
631
            if ($result === false) {
632
                $transaction->rollBack();
633
            } else {
634
                $transaction->commit();
635
            }
636
637
            return $result;
638
        } catch (\Exception $e) {
639
            $transaction->rollBack();
640
            throw $e;
641
        } 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...
642
            $transaction->rollBack();
643
            throw $e;
644
        }
645
    }
646
647
    /**
648
     * Deletes the table row corresponding to this active record.
649
     *
650
     * This method performs the following steps in order:
651
     *
652
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
653
     *    rest of the steps;
654
     * 2. delete the record from the database;
655
     * 3. call [[afterDelete()]].
656
     *
657
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
658
     * will be raised by the corresponding methods.
659
     *
660
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
661
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
662
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
663
     * being deleted is outdated.
664
     * @throws \Exception|\Throwable in case delete failed.
665
     */
666 6
    public function delete()
667
    {
668 6
        if (!$this->isTransactional(self::OP_DELETE)) {
669 6
            return $this->deleteInternal();
670
        }
671
672
        $transaction = static::getDb()->beginTransaction();
673
        try {
674
            $result = $this->deleteInternal();
675
            if ($result === false) {
676
                $transaction->rollBack();
677
            } else {
678
                $transaction->commit();
679
            }
680
681
            return $result;
682
        } catch (\Exception $e) {
683
            $transaction->rollBack();
684
            throw $e;
685
        } 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...
686
            $transaction->rollBack();
687
            throw $e;
688
        }
689
    }
690
691
    /**
692
     * Deletes an ActiveRecord without considering transaction.
693
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
694
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
695
     * @throws StaleObjectException
696
     */
697 6
    protected function deleteInternal()
698
    {
699 6
        if (!$this->beforeDelete()) {
700
            return false;
701
        }
702
703
        // we do not check the return value of deleteAll() because it's possible
704
        // the record is already deleted in the database and thus the method will return 0
705 6
        $condition = $this->getOldPrimaryKey(true);
706 6
        $lock = $this->optimisticLock();
707 6
        if ($lock !== null) {
708
            $condition[$lock] = $this->$lock;
709
        }
710 6
        $result = static::deleteAll($condition);
711 6
        if ($lock !== null && !$result) {
712
            throw new StaleObjectException('The object being deleted is outdated.');
713
        }
714 6
        $this->setOldAttributes(null);
715 6
        $this->afterDelete();
716
717 6
        return $result;
718
    }
719
720
    /**
721
     * Returns a value indicating whether the given active record is the same as the current one.
722
     * The comparison is made by comparing the table names and the primary key values of the two active records.
723
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
724
     * @param ActiveRecord $record record to compare to
725
     * @return bool whether the two active records refer to the same row in the same database table.
726
     */
727 3
    public function equals($record)
728
    {
729 3
        if ($this->isNewRecord || $record->isNewRecord) {
730 3
            return false;
731
        }
732
733 3
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
734
    }
735
736
    /**
737
     * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
738
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
739
     * @return bool whether the specified operation is transactional in the current [[scenario]].
740
     */
741 107
    public function isTransactional($operation)
742
    {
743 107
        $scenario = $this->getScenario();
744 107
        $transactions = $this->transactions();
745
746 107
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
747
    }
748
}
749