Completed
Push — master ( d2781c...0559a9 )
by Carsten
09:39
created

ActiveRecord::update()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 30.0568

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 4
cts 18
cp 0.2222
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 20
nc 10
nop 2
crap 30.0568
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\InvalidConfigException;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Inflector;
14
use yii\helpers\StringHelper;
15
16
/**
17
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
18
 *
19
 * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
20
 * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
21
 * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
22
 * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
23
 *
24
 * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
25
 * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
26
 * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
27
 * the `name` column for the table row, you can use the expression `$customer->name`.
28
 * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
29
 * But Active Record provides much more functionality than this.
30
 *
31
 * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
32
 * implement the `tableName` method:
33
 *
34
 * ```php
35
 * <?php
36
 *
37
 * class Customer extends \yii\db\ActiveRecord
38
 * {
39
 *     public static function tableName()
40
 *     {
41
 *         return 'customer';
42
 *     }
43
 * }
44
 * ```
45
 *
46
 * The `tableName` method only has to return the name of the database table associated with the class.
47
 *
48
 * > Tip: You may also use the [Gii code generator](guide:start-gii) to generate ActiveRecord classes from your
49
 * > database tables.
50
 *
51
 * Class instances are obtained in one of two ways:
52
 *
53
 * * Using the `new` operator to create a new, empty object
54
 * * Using a method to fetch an existing record (or records) from the database
55
 *
56
 * Below is an example showing some typical usage of ActiveRecord:
57
 *
58
 * ```php
59
 * $user = new User();
60
 * $user->name = 'Qiang';
61
 * $user->save();  // a new row is inserted into user table
62
 *
63
 * // the following will retrieve the user 'CeBe' from the database
64
 * $user = User::find()->where(['name' => 'CeBe'])->one();
65
 *
66
 * // this will get related records from orders table when relation is defined
67
 * $orders = $user->orders;
68
 * ```
69
 *
70
 * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](guide:db-active-record).
71
 *
72
 * @method ActiveQuery hasMany($class, array $link) see [[BaseActiveRecord::hasMany()]] for more info
73
 * @method ActiveQuery hasOne($class, array $link) see [[BaseActiveRecord::hasOne()]] for more info
74
 *
75
 * @author Qiang Xue <[email protected]>
76
 * @author Carsten Brandt <[email protected]>
77
 * @since 2.0
78
 */
79
class ActiveRecord extends BaseActiveRecord
80
{
81
    /**
82
     * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
83
     */
84
    const OP_INSERT = 0x01;
85
    /**
86
     * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
87
     */
88
    const OP_UPDATE = 0x02;
89
    /**
90
     * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
91
     */
92
    const OP_DELETE = 0x04;
93
    /**
94
     * All three operations: insert, update, delete.
95
     * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
96
     */
97
    const OP_ALL = 0x07;
98
99
100
    /**
101
     * Loads default values from database table schema
102
     *
103
     * You may call this method to load default values after creating a new instance:
104
     *
105
     * ```php
106
     * // class Customer extends \yii\db\ActiveRecord
107
     * $customer = new Customer();
108
     * $customer->loadDefaultValues();
109
     * ```
110
     *
111
     * @param bool $skipIfSet whether existing value should be preserved.
112
     * This will only set defaults for attributes that are `null`.
113
     * @return $this the model instance itself.
114
     */
115 4
    public function loadDefaultValues($skipIfSet = true)
116
    {
117 4
        foreach (static::getTableSchema()->columns as $column) {
118 4
            if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
119 4
                $this->{$column->name} = $column->defaultValue;
120
            }
121
        }
122 4
        return $this;
123
    }
124
125
    /**
126
     * Returns the database connection used by this AR class.
127
     * By default, the "db" application component is used as the database connection.
128
     * You may override this method if you want to use a different database connection.
129
     * @return Connection the database connection used by this AR class.
130
     */
131 33
    public static function getDb()
132
    {
133 33
        return Yii::$app->getDb();
134
    }
135
136
    /**
137
     * Creates an [[ActiveQuery]] instance with a given SQL statement.
138
     *
139
     * Note that because the SQL statement is already specified, calling additional
140
     * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
141
     * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
142
     * still fine.
143
     *
144
     * Below is an example:
145
     *
146
     * ```php
147
     * $customers = Customer::findBySql('SELECT * FROM customer')->all();
148
     * ```
149
     *
150
     * @param string $sql the SQL statement to be executed
151
     * @param array $params parameters to be bound to the SQL statement during execution.
152
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
153
     */
154 6
    public static function findBySql($sql, $params = [])
155
    {
156 6
        $query = static::find();
157 6
        $query->sql = $sql;
158
159 6
        return $query->params($params);
160
    }
161
162
    /**
163
     * Finds ActiveRecord instance(s) by the given condition.
164
     * This method is internally called by [[findOne()]] and [[findAll()]].
165
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
166
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
167
     * @throws InvalidConfigException if there is no primary key defined
168
     * @internal
169
     */
170 172
    protected static function findByCondition($condition)
171
    {
172 172
        $query = static::find();
173
174 172
        if (!ArrayHelper::isAssociative($condition)) {
175
            // query by primary key
176 142
            $primaryKey = static::primaryKey();
177 142
            if (isset($primaryKey[0])) {
178 142
                $pk = $primaryKey[0];
179 142
                if (!empty($query->join) || !empty($query->joinWith)) {
180 3
                    $pk = static::tableName() . '.' . $pk;
181
                }
182 142
                $condition = [$pk => $condition];
183
            } else {
184
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
185
            }
186
        }
187
188 172
        return $query->andWhere($condition);
189
    }
190
191
    /**
192
     * @inheritdoc
193
     */
194 25
    public function refresh()
195
    {
196 25
        $pk = [];
197
        // disambiguate column names in case ActiveQuery adds a JOIN
198 25
        foreach($this->getPrimaryKey(true) as $key => $value) {
199 25
            $pk[static::tableName() . '.' . $key] = $value;
200
        }
201
        /* @var $record BaseActiveRecord */
202 25
        $record = static::findOne($pk);
203 25
        return $this->refreshInternal($record);
204
    }
205
206
    /**
207
     * Updates the whole table using the provided attribute values and conditions.
208
     *
209
     * For example, to change the status to be 1 for all customers whose status is 2:
210
     *
211
     * ```php
212
     * Customer::updateAll(['status' => 1], 'status = 2');
213
     * ```
214
     *
215
     * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
216
     *
217
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
218
     * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
219
     * call [[update()]] on each of them. For example an equivalent of the example above would be:
220
     *
221
     * ```php
222
     * $models = Customer::find()->where('status = 2')->all();
223
     * foreach ($models as $model) {
224
     *     $model->status = 1;
225
     *     $model->update(false); // skipping validation as no user input is involved
226
     * }
227
     * ```
228
     *
229
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
230
     *
231
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
232
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
233
     * Please refer to [[Query::where()]] on how to specify this parameter.
234
     * @param array $params the parameters (name => value) to be bound to the query.
235
     * @return int the number of rows updated
236
     */
237 40
    public static function updateAll($attributes, $condition = '', $params = [])
238
    {
239 40
        $command = static::getDb()->createCommand();
240 40
        $command->update(static::tableName(), $attributes, $condition, $params);
241
242 40
        return $command->execute();
243
    }
244
245
    /**
246
     * Updates the whole table using the provided counter changes and conditions.
247
     *
248
     * For example, to increment all customers' age by 1,
249
     *
250
     * ```php
251
     * Customer::updateAllCounters(['age' => 1]);
252
     * ```
253
     *
254
     * Note that this method will not trigger any events.
255
     *
256
     * @param array $counters the counters to be updated (attribute name => increment value).
257
     * Use negative values if you want to decrement the counters.
258
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
259
     * Please refer to [[Query::where()]] on how to specify this parameter.
260
     * @param array $params the parameters (name => value) to be bound to the query.
261
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
262
     * @return int the number of rows updated
263
     */
264 6
    public static function updateAllCounters($counters, $condition = '', $params = [])
265
    {
266 6
        $n = 0;
267 6
        foreach ($counters as $name => $value) {
268 6
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
269 6
            $n++;
270
        }
271 6
        $command = static::getDb()->createCommand();
272 6
        $command->update(static::tableName(), $counters, $condition, $params);
273
274 6
        return $command->execute();
275
    }
276
277
    /**
278
     * Deletes rows in the table using the provided conditions.
279
     *
280
     * For example, to delete all customers whose status is 3:
281
     *
282
     * ```php
283
     * Customer::deleteAll('status = 3');
284
     * ```
285
     *
286
     * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
287
     *
288
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
289
     * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
290
     * call [[delete()]] on each of them. For example an equivalent of the example above would be:
291
     *
292
     * ```php
293
     * $models = Customer::find()->where('status = 3')->all();
294
     * foreach ($models as $model) {
295
     *     $model->delete();
296
     * }
297
     * ```
298
     *
299
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
300
     *
301
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
302
     * Please refer to [[Query::where()]] on how to specify this parameter.
303
     * @param array $params the parameters (name => value) to be bound to the query.
304
     * @return int the number of rows deleted
305
     */
306 31
    public static function deleteAll($condition = null, $params = [])
307
    {
308 31
        $command = static::getDb()->createCommand();
309 31
        $command->delete(static::tableName(), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 306 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...
310
311 31
        return $command->execute();
312
    }
313
314
    /**
315
     * @inheritdoc
316
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
317
     */
318 249
    public static function find()
319
    {
320 249
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
321
    }
322
323
    /**
324
     * Declares the name of the database table associated with this AR class.
325
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
326
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
327
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
328
     * if the table is not named after this convention.
329
     * @return string the table name
330
     */
331 9
    public static function tableName()
332
    {
333 9
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
334
    }
335
336
    /**
337
     * Returns the schema information of the DB table associated with this AR class.
338
     * @return TableSchema the schema information of the DB table associated with this AR class.
339
     * @throws InvalidConfigException if the table for the AR class does not exist.
340
     */
341 335
    public static function getTableSchema()
342
    {
343 335
        $tableSchema = static::getDb()
344 335
            ->getSchema()
345 335
            ->getTableSchema(static::tableName());
346
347 335
        if ($tableSchema === null) {
348
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
349
        }
350
351 335
        return $tableSchema;
352
    }
353
354
    /**
355
     * Returns the primary key name(s) for this AR class.
356
     * The default implementation will return the primary key(s) as declared
357
     * in the DB table that is associated with this AR class.
358
     *
359
     * If the DB table does not declare any primary key, you should override
360
     * this method to return the attributes that you want to use as primary keys
361
     * for this AR class.
362
     *
363
     * Note that an array should be returned even for a table with single primary key.
364
     *
365
     * @return string[] the primary keys of the associated database table.
366
     */
367 204
    public static function primaryKey()
368
    {
369 204
        return static::getTableSchema()->primaryKey;
370
    }
371
372
    /**
373
     * Returns the list of all attribute names of the model.
374
     * The default implementation will return all column names of the table associated with this AR class.
375
     * @return array list of attribute names.
376
     */
377 332
    public function attributes()
378
    {
379 332
        return array_keys(static::getTableSchema()->columns);
380
    }
381
382
    /**
383
     * Declares which DB operations should be performed within a transaction in different scenarios.
384
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
385
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
386
     * By default, these methods are NOT enclosed in a DB transaction.
387
     *
388
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
389
     * in transactions. You can do so by overriding this method and returning the operations
390
     * that need to be transactional. For example,
391
     *
392
     * ```php
393
     * return [
394
     *     'admin' => self::OP_INSERT,
395
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
396
     *     // the above is equivalent to the following:
397
     *     // 'api' => self::OP_ALL,
398
     *
399
     * ];
400
     * ```
401
     *
402
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
403
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
404
     * in a transaction.
405
     *
406
     * @return array the declarations of transactional operations. The array keys are scenarios names,
407
     * and the array values are the corresponding transaction operations.
408
     */
409 98
    public function transactions()
410
    {
411 98
        return [];
412
    }
413
414
    /**
415
     * @inheritdoc
416
     */
417 264
    public static function populateRecord($record, $row)
418
    {
419 264
        $columns = static::getTableSchema()->columns;
420 264
        foreach ($row as $name => $value) {
421 264
            if (isset($columns[$name])) {
422 264
                $row[$name] = $columns[$name]->phpTypecast($value);
423
            }
424
        }
425 264
        parent::populateRecord($record, $row);
426 264
    }
427
428
    /**
429
     * Inserts a row into the associated database table using the attribute values of this record.
430
     *
431
     * This method performs the following steps in order:
432
     *
433
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
434
     *    returns `false`, the rest of the steps will be skipped;
435
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
436
     *    failed, the rest of the steps will be skipped;
437
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
438
     *    the rest of the steps will be skipped;
439
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
440
     * 5. call [[afterSave()]];
441
     *
442
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
443
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
444
     * will be raised by the corresponding methods.
445
     *
446
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
447
     *
448
     * If the table's primary key is auto-incremental and is `null` during insertion,
449
     * it will be populated with the actual value after insertion.
450
     *
451
     * For example, to insert a customer record:
452
     *
453
     * ```php
454
     * $customer = new Customer;
455
     * $customer->name = $name;
456
     * $customer->email = $email;
457
     * $customer->insert();
458
     * ```
459
     *
460
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
461
     * before saving the record. Defaults to `true`. If the validation fails, the record
462
     * will not be saved to the database and this method will return `false`.
463
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
464
     * meaning all attributes that are loaded from DB will be saved.
465
     * @return bool whether the attributes are valid and the record is inserted successfully.
466
     * @throws \Exception|\Throwable in case insert failed.
467
     */
468 82
    public function insert($runValidation = true, $attributes = null)
469
    {
470 82
        if ($runValidation && !$this->validate($attributes)) {
471
            Yii::info('Model not inserted due to validation error.', __METHOD__);
472
            return false;
473
        }
474
475 82
        if (!$this->isTransactional(self::OP_INSERT)) {
476 82
            return $this->insertInternal($attributes);
477
        }
478
479
        $transaction = static::getDb()->beginTransaction();
480
        try {
481
            $result = $this->insertInternal($attributes);
482
            if ($result === false) {
483
                $transaction->rollBack();
484
            } else {
485
                $transaction->commit();
486
            }
487
            return $result;
488
        } catch (\Exception $e) {
489
            $transaction->rollBack();
490
            throw $e;
491
        } 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...
492
            $transaction->rollBack();
493
            throw $e;
494
        }
495
    }
496
497
    /**
498
     * Inserts an ActiveRecord into DB without considering transaction.
499
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
500
     * meaning all attributes that are loaded from DB will be saved.
501
     * @return bool whether the record is inserted successfully.
502
     */
503 82
    protected function insertInternal($attributes = null)
504
    {
505 82
        if (!$this->beforeSave(true)) {
506
            return false;
507
        }
508 82
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 503 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...
509 82
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
510
            return false;
511
        }
512 82
        foreach ($primaryKeys as $name => $value) {
513 71
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
514 71
            $this->setAttribute($name, $id);
515 71
            $values[$name] = $id;
516
        }
517
518 82
        $changedAttributes = array_fill_keys(array_keys($values), null);
519 82
        $this->setOldAttributes($values);
520 82
        $this->afterSave(true, $changedAttributes);
521
522 82
        return true;
523
    }
524
525
    /**
526
     * Saves the changes to this active record into the associated database table.
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. save 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_UPDATE]], and [[EVENT_AFTER_UPDATE]]
541
     * will be raised by the corresponding methods.
542
     *
543
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
544
     *
545
     * For example, to update a customer record:
546
     *
547
     * ```php
548
     * $customer = Customer::findOne($id);
549
     * $customer->name = $name;
550
     * $customer->email = $email;
551
     * $customer->update();
552
     * ```
553
     *
554
     * Note that it is possible the update does not affect any row in the table.
555
     * In this case, this method will return 0. For this reason, you should use the following
556
     * code to check if update() is successful or not:
557
     *
558
     * ```php
559
     * if ($customer->update() !== false) {
560
     *     // update successful
561
     * } else {
562
     *     // update failed
563
     * }
564
     * ```
565
     *
566
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
567
     * before saving the record. Defaults to `true`. If the validation fails, the record
568
     * will not be saved to the database and this method will return `false`.
569
     * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
570
     * meaning all attributes that are loaded from DB will be saved.
571
     * @return int|false the number of rows affected, or false if validation fails
572
     * or [[beforeSave()]] stops the updating process.
573
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
574
     * being updated is outdated.
575
     * @throws \Exception|\Throwable in case update failed.
576
     */
577 30
    public function update($runValidation = true, $attributeNames = null)
578
    {
579 30
        if ($runValidation && !$this->validate($attributeNames)) {
580
            Yii::info('Model not updated due to validation error.', __METHOD__);
581
            return false;
582
        }
583
584 30
        if (!$this->isTransactional(self::OP_UPDATE)) {
585 30
            return $this->updateInternal($attributeNames);
586
        }
587
588
        $transaction = static::getDb()->beginTransaction();
589
        try {
590
            $result = $this->updateInternal($attributeNames);
591
            if ($result === false) {
592
                $transaction->rollBack();
593
            } else {
594
                $transaction->commit();
595
            }
596
            return $result;
597
        } catch (\Exception $e) {
598
            $transaction->rollBack();
599
            throw $e;
600
        } 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...
601
            $transaction->rollBack();
602
            throw $e;
603
        }
604
    }
605
606
    /**
607
     * Deletes the table row corresponding to this active record.
608
     *
609
     * This method performs the following steps in order:
610
     *
611
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
612
     *    rest of the steps;
613
     * 2. delete the record from the database;
614
     * 3. call [[afterDelete()]].
615
     *
616
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
617
     * will be raised by the corresponding methods.
618
     *
619
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
620
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
621
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
622
     * being deleted is outdated.
623
     * @throws \Exception|\Throwable in case delete failed.
624
     */
625 6
    public function delete()
626
    {
627 6
        if (!$this->isTransactional(self::OP_DELETE)) {
628 6
            return $this->deleteInternal();
629
        }
630
631
        $transaction = static::getDb()->beginTransaction();
632
        try {
633
            $result = $this->deleteInternal();
634
            if ($result === false) {
635
                $transaction->rollBack();
636
            } else {
637
                $transaction->commit();
638
            }
639
            return $result;
640
        } catch (\Exception $e) {
641
            $transaction->rollBack();
642
            throw $e;
643
        } 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...
644
            $transaction->rollBack();
645
            throw $e;
646
        }
647
    }
648
649
    /**
650
     * Deletes an ActiveRecord without considering transaction.
651
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
652
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
653
     * @throws StaleObjectException
654
     */
655 6
    protected function deleteInternal()
656
    {
657 6
        if (!$this->beforeDelete()) {
658
            return false;
659
        }
660
661
        // we do not check the return value of deleteAll() because it's possible
662
        // the record is already deleted in the database and thus the method will return 0
663 6
        $condition = $this->getOldPrimaryKey(true);
664 6
        $lock = $this->optimisticLock();
665 6
        if ($lock !== null) {
666
            $condition[$lock] = $this->$lock;
667
        }
668 6
        $result = static::deleteAll($condition);
669 6
        if ($lock !== null && !$result) {
670
            throw new StaleObjectException('The object being deleted is outdated.');
671
        }
672 6
        $this->setOldAttributes(null);
673 6
        $this->afterDelete();
674
675 6
        return $result;
676
    }
677
678
    /**
679
     * Returns a value indicating whether the given active record is the same as the current one.
680
     * The comparison is made by comparing the table names and the primary key values of the two active records.
681
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
682
     * @param ActiveRecord $record record to compare to
683
     * @return bool whether the two active records refer to the same row in the same database table.
684
     */
685 3
    public function equals($record)
686
    {
687 3
        if ($this->isNewRecord || $record->isNewRecord) {
688 3
            return false;
689
        }
690
691 3
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
692
    }
693
694
    /**
695
     * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
696
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
697
     * @return bool whether the specified operation is transactional in the current [[scenario]].
698
     */
699 98
    public function isTransactional($operation)
700
    {
701 98
        $scenario = $this->getScenario();
702 98
        $transactions = $this->transactions();
703
704 98
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
705
    }
706
}
707