Completed
Push — cache-closure ( 7d9053...380edd )
by Dmitry
35:54
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 31.113

Importance

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