Test Failed
Pull Request — 22.0 (#20441)
by Wilmer
05:41
created

ActiveRecord::deleteAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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](https://en.wikipedia.org/wiki/Active_record_pattern).
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
 * @author Qiang Xue <[email protected]>
74
 * @author Carsten Brandt <[email protected]>
75
 * @since 2.0
76
 */
77
class ActiveRecord extends BaseActiveRecord
78
{
79
    /**
80
     * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
81
     */
82
    const OP_INSERT = 0x01;
83
    /**
84
     * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
85
     */
86
    const OP_UPDATE = 0x02;
87
    /**
88
     * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
89
     */
90
    const OP_DELETE = 0x04;
91
    /**
92
     * All three operations: insert, update, delete.
93
     * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
94
     */
95
    const OP_ALL = 0x07;
96
97
98
    /**
99
     * Loads default values from database table schema.
100
     *
101
     * You may call this method to load default values after creating a new instance:
102
     *
103
     * ```php
104
     * // class Customer extends \yii\db\ActiveRecord
105
     * $customer = new Customer();
106
     * $customer->loadDefaultValues();
107
     * ```
108
     *
109
     * @param bool $skipIfSet whether existing value should be preserved.
110
     * This will only set defaults for attributes that are `null`.
111
     * @return $this the model instance itself.
112
     */
113
    public function loadDefaultValues($skipIfSet = true)
114
    {
115
        $columns = static::getTableSchema()->columns;
116
        foreach ($this->attributes() as $name) {
117
            if (isset($columns[$name])) {
118
                $defaultValue = $columns[$name]->defaultValue;
119
                if ($defaultValue !== null && (!$skipIfSet || $this->getAttribute($name) === null)) {
120
                    $this->setAttribute($name, $defaultValue);
121
                }
122
            }
123
        }
124
125
        return $this;
126
    }
127
128
    /**
129
     * Returns the database connection used by this AR class.
130
     * By default, the "db" application component is used as the database connection.
131
     * You may override this method if you want to use a different database connection.
132
     * @return Connection the database connection used by this AR class.
133
     */
134
    public static function getDb()
135
    {
136
        return Yii::$app->getDb();
137 58
    }
138
139 58
    /**
140
     * Creates an [[ActiveQuery]] instance with a given SQL statement.
141
     *
142
     * Note that because the SQL statement is already specified, calling additional
143
     * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
144
     * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
145
     * still fine.
146
     *
147
     * Below is an example:
148
     *
149
     * ```php
150
     * $customers = Customer::findBySql('SELECT * FROM customer')->all();
151
     * ```
152
     *
153
     * @param string $sql the SQL statement to be executed
154
     * @param array $params parameters to be bound to the SQL statement during execution.
155
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
156
     *
157
     * @phpstan-return ActiveQuery<static>
158
     * @psalm-return ActiveQuery<static>
159
     */
160
    public static function findBySql($sql, $params = [])
161
    {
162
        $query = static::find();
163
        $query->sql = $sql;
164
165
        return $query->params($params);
166
    }
167
168
    /**
169
     * Finds ActiveRecord instance(s) by the given condition.
170
     * This method is internally called by [[findOne()]] and [[findAll()]].
171
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
172
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
173
     * @throws InvalidConfigException if there is no primary key defined.
174
     * @internal
175
     */
176
    protected static function findByCondition($condition)
177
    {
178
        $query = static::find();
179 1
180
        if (!ArrayHelper::isAssociative($condition) && !$condition instanceof ExpressionInterface) {
181 1
            // query by primary key
182
            $primaryKey = static::primaryKey();
183 1
            if (isset($primaryKey[0])) {
184
                $pk = $primaryKey[0];
185
                if (!empty($query->join) || !empty($query->joinWith)) {
186
                    $pk = static::tableName() . '.' . $pk;
187
                }
188
                // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
189
                $condition = [$pk => is_array($condition) ? array_values($condition) : $condition];
190
            } else {
191
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
192
            }
193
        } elseif (is_array($condition)) {
194
            $aliases = static::filterValidAliases($query);
195
            $condition = static::filterCondition($condition, $aliases);
196 1
        }
197 1
198 1
        return $query->andWhere($condition);
199
    }
200
201 1
    /**
202
     * Returns table aliases which are not the same as the name of the tables.
203
     *
204
     * @param Query $query
205
     * @return array
206
     * @throws InvalidConfigException
207
     * @since 2.0.17
208
     * @internal
209
     */
210
    protected static function filterValidAliases(Query $query)
211
    {
212
        $tables = $query->getTablesUsedInFrom();
213 1
214
        $aliases = array_diff(array_keys($tables), $tables);
215 1
216
        return array_map(function ($alias) {
217 1
            return preg_replace('/{{(\w+)}}/', '$1', $alias);
218
        }, array_values($aliases));
219 1
    }
220
221 1
    /**
222
     * Filters array condition before it is assiged to a Query filter.
223
     *
224
     * This method will ensure that an array condition only filters on existing table columns.
225
     *
226
     * @param array $condition condition to filter.
227
     * @param array $aliases
228
     * @return array filtered condition.
229
     * @throws InvalidArgumentException in case array contains unsafe values.
230
     * @throws InvalidConfigException
231
     * @since 2.0.15
232
     * @internal
233
     */
234
    protected static function filterCondition(array $condition, array $aliases = [])
235
    {
236
        $result = [];
237 1
        $db = static::getDb();
238
        $columnNames = static::filterValidColumnNames($db, $aliases);
239 1
240 1
        foreach ($condition as $key => $value) {
241 1
            if (is_string($key) && !in_array($db->quoteSql($key), $columnNames, true)) {
242
                throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
243 1
            }
244 1
            $result[$key] = is_array($value) ? array_values($value) : $value;
245
        }
246
247 1
        return $result;
248
    }
249
250 1
    /**
251
     * Valid column names are table column names or column names prefixed with table name or table alias
252
     *
253
     * @param Connection $db
254
     * @param array $aliases
255
     * @return array
256
     * @throws InvalidConfigException
257
     * @since 2.0.17
258
     * @internal
259
     */
260
    protected static function filterValidColumnNames($db, array $aliases)
261
    {
262
        $columnNames = [];
263 1
        $tableName = static::tableName();
264
        $quotedTableName = $db->quoteTableName($tableName);
265 1
266 1
        foreach (static::getTableSchema()->getColumnNames() as $columnName) {
267 1
            $columnNames[] = $columnName;
268
            $columnNames[] = $db->quoteColumnName($columnName);
269 1
            $columnNames[] = "$tableName.$columnName";
270 1
            $columnNames[] = $db->quoteSql("$quotedTableName.[[$columnName]]");
271 1
            foreach ($aliases as $tableAlias) {
272 1
                $columnNames[] = "$tableAlias.$columnName";
273 1
                $quotedTableAlias = $db->quoteTableName($tableAlias);
274 1
                $columnNames[] = $db->quoteSql("$quotedTableAlias.[[$columnName]]");
275
            }
276
        }
277
278
        return $columnNames;
279
    }
280
281 1
    /**
282
     * {@inheritdoc}
283
     */
284
    public function refresh()
285
    {
286
        $query = static::find();
287 4
        $tableName = key($query->getTablesUsedInFrom());
288
        $pk = [];
289 4
        // disambiguate column names in case ActiveQuery adds a JOIN
290 4
        foreach ($this->getPrimaryKey(true) as $key => $value) {
291 4
            $pk[$tableName . '.' . $key] = $value;
292
        }
293 4
        $query->where($pk);
294 4
295
        /** @var BaseActiveRecord $record */
296 4
        $record = $query->noCache()->one();
297
        return $this->refreshInternal($record);
298
    }
299 4
300 4
    /**
301
     * Updates the whole table using the provided attribute values and conditions.
302
     *
303
     * For example, to change the status to be 1 for all customers whose status is 2:
304
     *
305
     * ```php
306
     * Customer::updateAll(['status' => 1], 'status = 2');
307
     * ```
308
     *
309
     * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
310
     *
311
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
312
     * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
313
     * call [[update()]] on each of them. For example an equivalent of the example above would be:
314
     *
315
     * ```php
316
     * $models = Customer::find()->where('status = 2')->all();
317
     * foreach ($models as $model) {
318
     *     $model->status = 1;
319
     *     $model->update(false); // skipping validation as no user input is involved
320
     * }
321
     * ```
322
     *
323
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
324
     *
325
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
326
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
327
     * Please refer to [[Query::where()]] on how to specify this parameter.
328
     * @param array $params the parameters (name => value) to be bound to the query.
329
     * @return int the number of rows updated
330
     */
331
    public static function updateAll($attributes, $condition = '', $params = [])
332
    {
333
        $command = static::getDb()->createCommand();
334 11
        $command->update(static::tableName(), $attributes, $condition, $params);
335
336 11
        return $command->execute();
337 11
    }
338
339 11
    /**
340
     * Updates the whole table using the provided counter changes and conditions.
341
     *
342
     * For example, to increment all customers' age by 1,
343
     *
344
     * ```php
345
     * Customer::updateAllCounters(['age' => 1]);
346
     * ```
347
     *
348
     * Note that this method will not trigger any events.
349
     *
350
     * @param array $counters the counters to be updated (attribute name => increment value).
351
     * Use negative values if you want to decrement the counters.
352
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
353
     * Please refer to [[Query::where()]] on how to specify this parameter.
354
     * @param array $params the parameters (name => value) to be bound to the query.
355
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
356
     * @return int the number of rows updated
357
     */
358
    public static function updateAllCounters($counters, $condition = '', $params = [])
359
    {
360
        $n = 0;
361
        foreach ($counters as $name => $value) {
362
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
363
            $n++;
364
        }
365
        $command = static::getDb()->createCommand();
366
        $command->update(static::tableName(), $counters, $condition, $params);
367
368
        return $command->execute();
369
    }
370
371
    /**
372
     * Deletes rows in the table using the provided conditions.
373
     *
374
     * For example, to delete all customers whose status is 3:
375
     *
376
     * ```php
377
     * Customer::deleteAll('status = 3');
378
     * ```
379
     *
380
     * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
381
     *
382
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
383
     * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
384
     * call [[delete()]] on each of them. For example an equivalent of the example above would be:
385
     *
386
     * ```php
387
     * $models = Customer::find()->where('status = 3')->all();
388
     * foreach ($models as $model) {
389
     *     $model->delete();
390
     * }
391
     * ```
392
     *
393
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
394
     *
395
     * @param string|array|null $condition the conditions that will be put in the WHERE part of the DELETE SQL.
396
     * Please refer to [[Query::where()]] on how to specify this parameter.
397
     * @param array $params the parameters (name => value) to be bound to the query.
398
     * @return int the number of rows deleted
399
     */
400
    public static function deleteAll($condition = null, $params = [])
401
    {
402
        $command = static::getDb()->createCommand();
403 1
        $command->delete(static::tableName(), $condition, $params);
404
405 1
        return $command->execute();
406 1
    }
407
408 1
    /**
409
     * {@inheritdoc}
410
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
411
     *
412
     * @phpstan-return ActiveQuery<static>
413
     * @psalm-return ActiveQuery<static>
414
     */
415
    public static function find()
416
    {
417
        return Yii::createObject(ActiveQuery::class, [get_called_class()]);
418 17
    }
419
420 17
    /**
421
     * Declares the name of the database table associated with this AR class.
422
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
423
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
424
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
425
     * if the table is not named after this convention.
426
     * @return string the table name
427
     */
428
    public static function tableName()
429
    {
430
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
431
    }
432
433
    /**
434
     * Returns the schema information of the DB table associated with this AR class.
435
     * @return TableSchema the schema information of the DB table associated with this AR class.
436
     * @throws InvalidConfigException if the table for the AR class does not exist.
437
     */
438
    public static function getTableSchema()
439
    {
440
        $tableSchema = static::getDb()
441 58
            ->getSchema()
442
            ->getTableSchema(static::tableName());
443 58
444 58
        if ($tableSchema === null) {
445 58
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
446
        }
447 58
448
        return $tableSchema;
449
    }
450
451 58
    /**
452
     * Returns the primary key name(s) for this AR class.
453
     * The default implementation will return the primary key(s) as declared
454
     * in the DB table that is associated with this AR class.
455
     *
456
     * If the DB table does not declare any primary key, you should override
457
     * this method to return the attributes that you want to use as primary keys
458
     * for this AR class.
459
     *
460
     * Note that an array should be returned even for a table with single primary key.
461
     *
462
     * @return string[] the primary keys of the associated database table.
463
     */
464
    public static function primaryKey()
465
    {
466
        return static::getTableSchema()->primaryKey;
467 13
    }
468
469 13
    /**
470
     * Returns the list of all attribute names of the model.
471
     * The default implementation will return all column names of the table associated with this AR class.
472
     * @return array list of attribute names.
473
     */
474
    public function attributes()
475
    {
476
        return static::getTableSchema()->getColumnNames();
477 58
    }
478
479 58
    /**
480
     * Declares which DB operations should be performed within a transaction in different scenarios.
481
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
482
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
483
     * By default, these methods are NOT enclosed in a DB transaction.
484
     *
485
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
486
     * in transactions. You can do so by overriding this method and returning the operations
487
     * that need to be transactional. For example,
488
     *
489
     * ```php
490
     * return [
491
     *     'admin' => self::OP_INSERT,
492
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
493
     *     // the above is equivalent to the following:
494
     *     // 'api' => self::OP_ALL,
495
     *
496
     * ];
497
     * ```
498
     *
499
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
500
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
501
     * in a transaction.
502
     *
503
     * @return array the declarations of transactional operations. The array keys are scenarios names,
504
     * and the array values are the corresponding transaction operations.
505
     */
506
    public function transactions()
507
    {
508
        return [];
509 25
    }
510
511 25
    /**
512
     * {@inheritdoc}
513
     */
514
    public static function populateRecord($record, $row)
515
    {
516
        $columns = static::getTableSchema()->columns;
517 8
        foreach ($row as $name => $value) {
518
            if (isset($columns[$name])) {
519 8
                $row[$name] = $columns[$name]->phpTypecast($value);
520 8
            }
521 8
        }
522 8
        parent::populateRecord($record, $row);
523
    }
524
525 8
    /**
526
     * Inserts a row into the associated database table using the attribute values of this record.
527
     *
528
     * This method performs the following steps in order:
529
     *
530
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
531
     *    returns `false`, the rest of the steps will be skipped;
532
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
533
     *    failed, the rest of the steps will be skipped;
534
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
535
     *    the rest of the steps will be skipped;
536
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
537
     * 5. call [[afterSave()]];
538
     *
539
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
540
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
541
     * will be raised by the corresponding methods.
542
     *
543
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
544
     *
545
     * If the table's primary key is auto-incremental and is `null` during insertion,
546
     * it will be populated with the actual value after insertion.
547
     *
548
     * For example, to insert a customer record:
549
     *
550
     * ```php
551
     * $customer = new Customer;
552
     * $customer->name = $name;
553
     * $customer->email = $email;
554
     * $customer->insert();
555
     * ```
556
     *
557
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
558
     * before saving the record. Defaults to `true`. If the validation fails, the record
559
     * will not be saved to the database and this method will return `false`.
560
     * @param array|null $attributes list of attributes that need to be saved. Defaults to `null`,
561
     * meaning all attributes that are loaded from DB will be saved.
562
     * @return bool whether the attributes are valid and the record is inserted successfully.
563
     * @throws \Throwable in case insert failed.
564
     */
565
    public function insert($runValidation = true, $attributes = null)
566
    {
567
        if ($runValidation && !$this->validate($attributes)) {
568 25
            Yii::info('Model not inserted due to validation error.', __METHOD__);
569
            return false;
570 25
        }
571
572
        if (!$this->isTransactional(self::OP_INSERT)) {
573
            return $this->insertInternal($attributes);
574
        }
575 25
576 25
        $transaction = static::getDb()->beginTransaction();
577
        try {
578
            $result = $this->insertInternal($attributes);
579
            if ($result === false) {
580
                $transaction->rollBack();
581
            } else {
582
                $transaction->commit();
583
            }
584
585
            return $result;
586
        } catch (\Exception $e) {
587
            $transaction->rollBack();
588
            throw $e;
589
        } catch (\Throwable $e) {
590
            $transaction->rollBack();
591
            throw $e;
592
        }
593
    }
594
595
    /**
596
     * {@inheritdoc}
597
     *
598
     * @return ActiveQuery
599
     *
600
     * @template T
601
     *
602
     * @phpstan-param class-string<T> $class
603
     * @psalm-param class-string<T> $class
604 25
     *
605
     * @phpstan-return ActiveQuery<T>
606 25
     * @psalm-return ActiveQuery<T>
607
     */
608
    public function hasMany($class, $link)
609 25
    {
610 25
        return parent::hasMany($class, $link);
611
    }
612
613 25
    /**
614 24
     * {@inheritdoc}
615 24
     *
616 24
     * @return ActiveQuery
617
     *
618
     * @template T
619 25
     *
620 25
     * @phpstan-param class-string<T> $class
621 25
     * @psalm-param class-string<T> $class
622
     *
623 25
     * @phpstan-return ActiveQuery<T>
624
     * @psalm-return ActiveQuery<T>
625
     */
626
    public function hasOne($class, $link)
627
    {
628
        return parent::hasOne($class, $link);
629
    }
630
631
    /**
632
     * Inserts an ActiveRecord into DB without considering transaction.
633
     * @param array|null $attributes list of attributes that need to be saved. Defaults to `null`,
634
     * meaning all attributes that are loaded from DB will be saved.
635
     * @return bool whether the record is inserted successfully.
636
     */
637
    protected function insertInternal($attributes = null)
638
    {
639
        if (!$this->beforeSave(true)) {
640
            return false;
641
        }
642
        $values = $this->getDirtyAttributes($attributes);
643
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
644
            return false;
645
        }
646
        foreach ($primaryKeys as $name => $value) {
647
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
648
            $this->setAttribute($name, $id);
649
            $values[$name] = $id;
650
        }
651
652
        $changedAttributes = array_fill_keys(array_keys($values), null);
653
        $this->setOldAttributes($values);
654
        $this->afterSave(true, $changedAttributes);
655
656
        return true;
657
    }
658
659
    /**
660
     * Saves the changes to this active record into the associated database table.
661
     *
662
     * This method performs the following steps in order:
663
     *
664
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
665
     *    returns `false`, the rest of the steps will be skipped;
666
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
667
     *    failed, the rest of the steps will be skipped;
668
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
669
     *    the rest of the steps will be skipped;
670
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
671
     * 5. call [[afterSave()]];
672
     *
673
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
674
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
675
     * will be raised by the corresponding methods.
676
     *
677
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
678 11
     *
679
     * For example, to update a customer record:
680 11
     *
681
     * ```php
682
     * $customer = Customer::findOne($id);
683
     * $customer->name = $name;
684
     * $customer->email = $email;
685 11
     * $customer->update();
686 11
     * ```
687
     *
688
     * Note that it is possible the update does not affect any row in the table.
689
     * In this case, this method will return 0. For this reason, you should use the following
690
     * code to check if update() is successful or not:
691
     *
692
     * ```php
693
     * if ($customer->update() !== false) {
694
     *     // update successful
695
     * } else {
696
     *     // update failed
697
     * }
698
     * ```
699
     *
700
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
701
     * before saving the record. Defaults to `true`. If the validation fails, the record
702
     * will not be saved to the database and this method will return `false`.
703
     * @param array|null $attributeNames list of attributes that need to be saved. Defaults to `null`,
704
     * meaning all attributes that are loaded from DB will be saved.
705
     * @return int|false the number of rows affected, or false if validation fails
706
     * or [[beforeSave()]] stops the updating process.
707
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
708
     * being updated is outdated.
709
     * @throws \Throwable in case update failed.
710
     */
711
    public function update($runValidation = true, $attributeNames = null)
712
    {
713
        if ($runValidation && !$this->validate($attributeNames)) {
714
            Yii::info('Model not updated due to validation error.', __METHOD__);
715
            return false;
716
        }
717
718
        if (!$this->isTransactional(self::OP_UPDATE)) {
719
            return $this->updateInternal($attributeNames);
720
        }
721
722
        $transaction = static::getDb()->beginTransaction();
723
        try {
724
            $result = $this->updateInternal($attributeNames);
725
            if ($result === false) {
726
                $transaction->rollBack();
727 1
            } else {
728
                $transaction->commit();
729 1
            }
730 1
731
            return $result;
732
        } catch (\Exception $e) {
733
            $transaction->rollBack();
734
            throw $e;
735
        } catch (\Throwable $e) {
736
            $transaction->rollBack();
737
            throw $e;
738
        }
739
    }
740
741
    /**
742
     * Deletes the table row corresponding to this active record.
743
     *
744
     * This method performs the following steps in order:
745
     *
746
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
747
     *    rest of the steps;
748
     * 2. delete the record from the database;
749
     * 3. call [[afterDelete()]].
750
     *
751
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
752
     * will be raised by the corresponding methods.
753
     *
754
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
755
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
756
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
757
     * being deleted is outdated.
758 1
     * @throws \Throwable in case delete failed.
759
     */
760 1
    public function delete()
761
    {
762
        if (!$this->isTransactional(self::OP_DELETE)) {
763
            return $this->deleteInternal();
764
        }
765
766 1
        $transaction = static::getDb()->beginTransaction();
767 1
        try {
768 1
            $result = $this->deleteInternal();
769 1
            if ($result === false) {
770
                $transaction->rollBack();
771 1
            } else {
772 1
                $transaction->commit();
773 1
            }
774
775 1
            return $result;
776 1
        } catch (\Exception $e) {
777
            $transaction->rollBack();
778 1
            throw $e;
779
        } catch (\Throwable $e) {
780
            $transaction->rollBack();
781
            throw $e;
782
        }
783
    }
784
785
    /**
786
     * Deletes an ActiveRecord without considering transaction.
787
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
788
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
789
     * @throws StaleObjectException
790
     */
791
    protected function deleteInternal()
792
    {
793
        if (!$this->beforeDelete()) {
794
            return false;
795
        }
796
797
        // we do not check the return value of deleteAll() because it's possible
798
        // the record is already deleted in the database and thus the method will return 0
799
        $condition = $this->getOldPrimaryKey(true);
800
        $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting yii\db\BaseActiveRecord::optimisticLock() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
801
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
802 25
            $condition[$lock] = $this->$lock;
803
        }
804 25
        $result = static::deleteAll($condition);
805 25
        if ($lock !== null && !$result) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
806
            throw new StaleObjectException('The object being deleted is outdated.');
807 25
        }
808
        $this->setOldAttributes(null);
809
        $this->afterDelete();
810
811
        return $result;
812
    }
813
814
    /**
815
     * Returns a value indicating whether the given active record is the same as the current one.
816
     * The comparison is made by comparing the table names and the primary key values of the two active records.
817
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
818
     * @param ActiveRecord $record record to compare to
819
     * @return bool whether the two active records refer to the same row in the same database table.
820
     */
821
    public function equals($record)
822
    {
823
        if ($this->isNewRecord || $record->isNewRecord) {
824
            return false;
825
        }
826
827
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
828
    }
829
830
    /**
831
     * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
832
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
833
     * @return bool whether the specified operation is transactional in the current [[scenario]].
834
     */
835
    public function isTransactional($operation)
836
    {
837
        $scenario = $this->getScenario();
838
        $transactions = $this->transactions();
839
840
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
841
    }
842
}
843