Completed
Push — 2.0.13-dev ( 4608bb )
by Carsten
10:19
created

ActiveRecord::tableName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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