Completed
Push — master ( b4f1a5...4c1600 )
by Carsten
80:08 queued 71:13
created

ActiveRecord::filterCondition()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 4
nop 1
crap 5
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\InvalidConfigException;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\Inflector;
15
use yii\helpers\StringHelper;
16
17
/**
18
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
19
 *
20
 * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
21
 * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
22
 * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
23
 * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
24
 *
25
 * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
26
 * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
27
 * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
28
 * the `name` column for the table row, you can use the expression `$customer->name`.
29
 * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
30
 * But Active Record provides much more functionality than this.
31
 *
32
 * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
33
 * implement the `tableName` method:
34
 *
35
 * ```php
36
 * <?php
37
 *
38
 * class Customer extends \yii\db\ActiveRecord
39
 * {
40
 *     public static function tableName()
41
 *     {
42
 *         return 'customer';
43
 *     }
44
 * }
45
 * ```
46
 *
47
 * The `tableName` method only has to return the name of the database table associated with the class.
48
 *
49
 * > Tip: You may also use the [Gii code generator](guide:start-gii) to generate ActiveRecord classes from your
50
 * > database tables.
51
 *
52
 * Class instances are obtained in one of two ways:
53
 *
54
 * * Using the `new` operator to create a new, empty object
55
 * * Using a method to fetch an existing record (or records) from the database
56
 *
57
 * Below is an example showing some typical usage of ActiveRecord:
58
 *
59
 * ```php
60
 * $user = new User();
61
 * $user->name = 'Qiang';
62
 * $user->save();  // a new row is inserted into user table
63
 *
64
 * // the following will retrieve the user 'CeBe' from the database
65
 * $user = User::find()->where(['name' => 'CeBe'])->one();
66
 *
67
 * // this will get related records from orders table when relation is defined
68
 * $orders = $user->orders;
69
 * ```
70
 *
71
 * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](guide:db-active-record).
72
 *
73
 * @method ActiveQuery hasMany($class, array $link) see [[BaseActiveRecord::hasMany()]] for more info
74
 * @method ActiveQuery hasOne($class, array $link) see [[BaseActiveRecord::hasOne()]] for more info
75
 *
76
 * @author Qiang Xue <[email protected]>
77
 * @author Carsten Brandt <[email protected]>
78
 * @since 2.0
79
 */
80
class ActiveRecord extends BaseActiveRecord
81
{
82
    /**
83
     * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
84
     */
85
    const OP_INSERT = 0x01;
86
    /**
87
     * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
88
     */
89
    const OP_UPDATE = 0x02;
90
    /**
91
     * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
92
     */
93
    const OP_DELETE = 0x04;
94
    /**
95
     * All three operations: insert, update, delete.
96
     * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
97
     */
98
    const OP_ALL = 0x07;
99
100
101
    /**
102
     * Loads default values from database table schema.
103
     *
104
     * You may call this method to load default values after creating a new instance:
105
     *
106
     * ```php
107
     * // class Customer extends \yii\db\ActiveRecord
108
     * $customer = new Customer();
109
     * $customer->loadDefaultValues();
110
     * ```
111
     *
112
     * @param bool $skipIfSet whether existing value should be preserved.
113
     * This will only set defaults for attributes that are `null`.
114
     * @return $this the model instance itself.
115
     */
116 4
    public function loadDefaultValues($skipIfSet = true)
117
    {
118 4
        foreach (static::getTableSchema()->columns as $column) {
119 4
            if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
120 4
                $this->{$column->name} = $column->defaultValue;
121
            }
122
        }
123
124 4
        return $this;
125
    }
126
127
    /**
128
     * Returns the database connection used by this AR class.
129
     * By default, the "db" application component is used as the database connection.
130
     * You may override this method if you want to use a different database connection.
131
     * @return Connection the database connection used by this AR class.
132
     */
133 44
    public static function getDb()
134
    {
135 44
        return Yii::$app->getDb();
136
    }
137
138
    /**
139
     * Creates an [[ActiveQuery]] instance with a given SQL statement.
140
     *
141
     * Note that because the SQL statement is already specified, calling additional
142
     * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
143
     * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
144
     * still fine.
145
     *
146
     * Below is an example:
147
     *
148
     * ```php
149
     * $customers = Customer::findBySql('SELECT * FROM customer')->all();
150
     * ```
151
     *
152
     * @param string $sql the SQL statement to be executed
153
     * @param array $params parameters to be bound to the SQL statement during execution.
154
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
155
     */
156 6
    public static function findBySql($sql, $params = [])
157
    {
158 6
        $query = static::find();
159 6
        $query->sql = $sql;
160
161 6
        return $query->params($params);
162
    }
163
164
    /**
165
     * Finds ActiveRecord instance(s) by the given condition.
166
     * This method is internally called by [[findOne()]] and [[findAll()]].
167
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
168
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
169
     * @throws InvalidConfigException if there is no primary key defined.
170
     * @internal
171
     */
172 199
    protected static function findByCondition($condition)
173
    {
174 199
        $query = static::find();
175
176 199
        if (!ArrayHelper::isAssociative($condition)) {
177
            // query by primary key
178 161
            $primaryKey = static::primaryKey();
179 161
            if (isset($primaryKey[0])) {
180 161
                $pk = $primaryKey[0];
181 161
                if (!empty($query->join) || !empty($query->joinWith)) {
182 3
                    $pk = static::tableName() . '.' . $pk;
183
                }
184
                // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
185 161
                $condition = [$pk => is_array($condition) ? array_values($condition) : $condition];
186
            } else {
187 161
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
188
            }
189 50
        } elseif (is_array($condition)) {
190 50
            $condition = static::filterCondition($condition);
191
        }
192
193 187
        return $query->andWhere($condition);
194
    }
195
196
    /**
197
     * Filters array condition before it is assiged to a Query filter.
198
     *
199
     * This method will ensure that an array condition only filters on existing table columns.
200
     *
201
     * @param array $condition condition to filter.
202
     * @return array filtered condition.
203
     * @throws InvalidArgumentException in case array contains unsafe values.
204
     * @since 2.0.15
205
     * @internal
206
     */
207 50
    protected static function filterCondition(array $condition)
208
    {
209 50
        $result = [];
210 50
        $columnNames = static::getTableSchema()->getColumnNames();
211 50
        foreach ($condition as $key => $value) {
212 50
            if (is_string($key) && !in_array($key, $columnNames, true)) {
213 12
                throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
214
            }
215 38
            $result[$key] = is_array($value) ? array_values($value) : $value;
216
        }
217
218 38
        return $result;
219
    }
220
221
    /**
222
     * {@inheritdoc}
223
     */
224 29
    public function refresh()
225
    {
226 29
        $query = static::find();
227 29
        $tableName = key($query->getTablesUsedInFrom());
228 29
        $pk = [];
229
        // disambiguate column names in case ActiveQuery adds a JOIN
230 29
        foreach ($this->getPrimaryKey(true) as $key => $value) {
231 29
            $pk[$tableName . '.' . $key] = $value;
232
        }
233 29
        $query->where($pk);
234
235
        /* @var $record BaseActiveRecord */
236 29
        $record = $query->one();
237 29
        return $this->refreshInternal($record);
238
    }
239
240
    /**
241
     * Updates the whole table using the provided attribute values and conditions.
242
     *
243
     * For example, to change the status to be 1 for all customers whose status is 2:
244
     *
245
     * ```php
246
     * Customer::updateAll(['status' => 1], 'status = 2');
247
     * ```
248
     *
249
     * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
250
     *
251
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
252
     * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
253
     * call [[update()]] on each of them. For example an equivalent of the example above would be:
254
     *
255
     * ```php
256
     * $models = Customer::find()->where('status = 2')->all();
257
     * foreach ($models as $model) {
258
     *     $model->status = 1;
259
     *     $model->update(false); // skipping validation as no user input is involved
260
     * }
261
     * ```
262
     *
263
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
264
     *
265
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
266
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
267
     * Please refer to [[Query::where()]] on how to specify this parameter.
268
     * @param array $params the parameters (name => value) to be bound to the query.
269
     * @return int the number of rows updated
270
     */
271 49
    public static function updateAll($attributes, $condition = '', $params = [])
272
    {
273 49
        $command = static::getDb()->createCommand();
274 49
        $command->update(static::tableName(), $attributes, $condition, $params);
275
276 49
        return $command->execute();
277
    }
278
279
    /**
280
     * Updates the whole table using the provided counter changes and conditions.
281
     *
282
     * For example, to increment all customers' age by 1,
283
     *
284
     * ```php
285
     * Customer::updateAllCounters(['age' => 1]);
286
     * ```
287
     *
288
     * Note that this method will not trigger any events.
289
     *
290
     * @param array $counters the counters to be updated (attribute name => increment value).
291
     * Use negative values if you want to decrement the counters.
292
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
293
     * Please refer to [[Query::where()]] on how to specify this parameter.
294
     * @param array $params the parameters (name => value) to be bound to the query.
295
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
296
     * @return int the number of rows updated
297
     */
298 6
    public static function updateAllCounters($counters, $condition = '', $params = [])
299
    {
300 6
        $n = 0;
301 6
        foreach ($counters as $name => $value) {
302 6
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
303 6
            $n++;
304
        }
305 6
        $command = static::getDb()->createCommand();
306 6
        $command->update(static::tableName(), $counters, $condition, $params);
307
308 6
        return $command->execute();
309
    }
310
311
    /**
312
     * Deletes rows in the table using the provided conditions.
313
     *
314
     * For example, to delete all customers whose status is 3:
315
     *
316
     * ```php
317
     * Customer::deleteAll('status = 3');
318
     * ```
319
     *
320
     * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
321
     *
322
     * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
323
     * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
324
     * call [[delete()]] on each of them. For example an equivalent of the example above would be:
325
     *
326
     * ```php
327
     * $models = Customer::find()->where('status = 3')->all();
328
     * foreach ($models as $model) {
329
     *     $model->delete();
330
     * }
331
     * ```
332
     *
333
     * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
334
     *
335
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
336
     * Please refer to [[Query::where()]] on how to specify this parameter.
337
     * @param array $params the parameters (name => value) to be bound to the query.
338
     * @return int the number of rows deleted
339
     */
340 31
    public static function deleteAll($condition = null, $params = [])
341
    {
342 31
        $command = static::getDb()->createCommand();
343 31
        $command->delete(static::tableName(), $condition, $params);
0 ignored issues
show
Bug introduced by
It seems like $condition defined by parameter $condition on line 340 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...
344
345 31
        return $command->execute();
346
    }
347
348
    /**
349
     * {@inheritdoc}
350
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
351
     */
352 296
    public static function find()
353
    {
354 296
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
355
    }
356
357
    /**
358
     * Declares the name of the database table associated with this AR class.
359
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
360
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
361
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
362
     * if the table is not named after this convention.
363
     * @return string the table name
364
     */
365 15
    public static function tableName()
366
    {
367 15
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
368
    }
369
370
    /**
371
     * Returns the schema information of the DB table associated with this AR class.
372
     * @return TableSchema the schema information of the DB table associated with this AR class.
373
     * @throws InvalidConfigException if the table for the AR class does not exist.
374
     */
375 413
    public static function getTableSchema()
376
    {
377 413
        $tableSchema = static::getDb()
378 413
            ->getSchema()
379 413
            ->getTableSchema(static::tableName());
380
381 413
        if ($tableSchema === null) {
382
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
383
        }
384
385 413
        return $tableSchema;
386
    }
387
388
    /**
389
     * Returns the primary key name(s) for this AR class.
390
     * The default implementation will return the primary key(s) as declared
391
     * in the DB table that is associated with this AR class.
392
     *
393
     * If the DB table does not declare any primary key, you should override
394
     * this method to return the attributes that you want to use as primary keys
395
     * for this AR class.
396
     *
397
     * Note that an array should be returned even for a table with single primary key.
398
     *
399
     * @return string[] the primary keys of the associated database table.
400
     */
401 251
    public static function primaryKey()
402
    {
403 251
        return static::getTableSchema()->primaryKey;
404
    }
405
406
    /**
407
     * Returns the list of all attribute names of the model.
408
     * The default implementation will return all column names of the table associated with this AR class.
409
     * @return array list of attribute names.
410
     */
411 398
    public function attributes()
412
    {
413 398
        return array_keys(static::getTableSchema()->columns);
414
    }
415
416
    /**
417
     * Declares which DB operations should be performed within a transaction in different scenarios.
418
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
419
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
420
     * By default, these methods are NOT enclosed in a DB transaction.
421
     *
422
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
423
     * in transactions. You can do so by overriding this method and returning the operations
424
     * that need to be transactional. For example,
425
     *
426
     * ```php
427
     * return [
428
     *     'admin' => self::OP_INSERT,
429
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
430
     *     // the above is equivalent to the following:
431
     *     // 'api' => self::OP_ALL,
432
     *
433
     * ];
434
     * ```
435
     *
436
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
437
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
438
     * in a transaction.
439
     *
440
     * @return array the declarations of transactional operations. The array keys are scenarios names,
441
     * and the array values are the corresponding transaction operations.
442
     */
443 107
    public function transactions()
444
    {
445 107
        return [];
446
    }
447
448
    /**
449
     * {@inheritdoc}
450
     */
451 319
    public static function populateRecord($record, $row)
452
    {
453 319
        $columns = static::getTableSchema()->columns;
454 319
        foreach ($row as $name => $value) {
455 319
            if (isset($columns[$name])) {
456 319
                $row[$name] = $columns[$name]->phpTypecast($value);
457
            }
458
        }
459 319
        parent::populateRecord($record, $row);
460 319
    }
461
462
    /**
463
     * Inserts a row into the associated database table using the attribute values of this record.
464
     *
465
     * This method performs the following steps in order:
466
     *
467
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
468
     *    returns `false`, the rest of the steps will be skipped;
469
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
470
     *    failed, the rest of the steps will be skipped;
471
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
472
     *    the rest of the steps will be skipped;
473
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
474
     * 5. call [[afterSave()]];
475
     *
476
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
477
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
478
     * will be raised by the corresponding methods.
479
     *
480
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
481
     *
482
     * If the table's primary key is auto-incremental and is `null` during insertion,
483
     * it will be populated with the actual value after insertion.
484
     *
485
     * For example, to insert a customer record:
486
     *
487
     * ```php
488
     * $customer = new Customer;
489
     * $customer->name = $name;
490
     * $customer->email = $email;
491
     * $customer->insert();
492
     * ```
493
     *
494
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
495
     * before saving the record. Defaults to `true`. If the validation fails, the record
496
     * will not be saved to the database and this method will return `false`.
497
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
498
     * meaning all attributes that are loaded from DB will be saved.
499
     * @return bool whether the attributes are valid and the record is inserted successfully.
500
     * @throws \Exception|\Throwable in case insert failed.
501
     */
502 91
    public function insert($runValidation = true, $attributes = null)
503
    {
504 91
        if ($runValidation && !$this->validate($attributes)) {
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 502 can also be of type array; however, yii\base\Model::validate() does only seem to accept array<integer,string>|string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
505
            Yii::info('Model not inserted due to validation error.', __METHOD__);
506
            return false;
507
        }
508
509 91
        if (!$this->isTransactional(self::OP_INSERT)) {
510 91
            return $this->insertInternal($attributes);
511
        }
512
513
        $transaction = static::getDb()->beginTransaction();
514
        try {
515
            $result = $this->insertInternal($attributes);
516
            if ($result === false) {
517
                $transaction->rollBack();
518
            } else {
519
                $transaction->commit();
520
            }
521
522
            return $result;
523
        } catch (\Exception $e) {
524
            $transaction->rollBack();
525
            throw $e;
526
        } 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...
527
            $transaction->rollBack();
528
            throw $e;
529
        }
530
    }
531
532
    /**
533
     * Inserts an ActiveRecord into DB without considering transaction.
534
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
535
     * meaning all attributes that are loaded from DB will be saved.
536
     * @return bool whether the record is inserted successfully.
537
     */
538 91
    protected function insertInternal($attributes = null)
539
    {
540 91
        if (!$this->beforeSave(true)) {
541
            return false;
542
        }
543 91
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 538 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...
544 91
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
545
            return false;
546
        }
547 91
        foreach ($primaryKeys as $name => $value) {
548 80
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
549 80
            $this->setAttribute($name, $id);
550 80
            $values[$name] = $id;
551
        }
552
553 91
        $changedAttributes = array_fill_keys(array_keys($values), null);
554 91
        $this->setOldAttributes($values);
555 91
        $this->afterSave(true, $changedAttributes);
556
557 91
        return true;
558
    }
559
560
    /**
561
     * Saves the changes to this active record into the associated database table.
562
     *
563
     * This method performs the following steps in order:
564
     *
565
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
566
     *    returns `false`, the rest of the steps will be skipped;
567
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
568
     *    failed, the rest of the steps will be skipped;
569
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
570
     *    the rest of the steps will be skipped;
571
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
572
     * 5. call [[afterSave()]];
573
     *
574
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
575
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
576
     * will be raised by the corresponding methods.
577
     *
578
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
579
     *
580
     * For example, to update a customer record:
581
     *
582
     * ```php
583
     * $customer = Customer::findOne($id);
584
     * $customer->name = $name;
585
     * $customer->email = $email;
586
     * $customer->update();
587
     * ```
588
     *
589
     * Note that it is possible the update does not affect any row in the table.
590
     * In this case, this method will return 0. For this reason, you should use the following
591
     * code to check if update() is successful or not:
592
     *
593
     * ```php
594
     * if ($customer->update() !== false) {
595
     *     // update successful
596
     * } else {
597
     *     // update failed
598
     * }
599
     * ```
600
     *
601
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
602
     * before saving the record. Defaults to `true`. If the validation fails, the record
603
     * will not be saved to the database and this method will return `false`.
604
     * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
605
     * meaning all attributes that are loaded from DB will be saved.
606
     * @return int|false the number of rows affected, or false if validation fails
607
     * or [[beforeSave()]] stops the updating process.
608
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
609
     * being updated is outdated.
610
     * @throws \Exception|\Throwable in case update failed.
611
     */
612 38
    public function update($runValidation = true, $attributeNames = null)
613
    {
614 38
        if ($runValidation && !$this->validate($attributeNames)) {
0 ignored issues
show
Bug introduced by
It seems like $attributeNames defined by parameter $attributeNames on line 612 can also be of type array; however, yii\base\Model::validate() does only seem to accept array<integer,string>|string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
615
            Yii::info('Model not updated due to validation error.', __METHOD__);
616
            return false;
617
        }
618
619 38
        if (!$this->isTransactional(self::OP_UPDATE)) {
620 38
            return $this->updateInternal($attributeNames);
621
        }
622
623
        $transaction = static::getDb()->beginTransaction();
624
        try {
625
            $result = $this->updateInternal($attributeNames);
626
            if ($result === false) {
627
                $transaction->rollBack();
628
            } else {
629
                $transaction->commit();
630
            }
631
632
            return $result;
633
        } catch (\Exception $e) {
634
            $transaction->rollBack();
635
            throw $e;
636
        } 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...
637
            $transaction->rollBack();
638
            throw $e;
639
        }
640
    }
641
642
    /**
643
     * Deletes the table row corresponding to this active record.
644
     *
645
     * This method performs the following steps in order:
646
     *
647
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
648
     *    rest of the steps;
649
     * 2. delete the record from the database;
650
     * 3. call [[afterDelete()]].
651
     *
652
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
653
     * will be raised by the corresponding methods.
654
     *
655
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
656
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
657
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
658
     * being deleted is outdated.
659
     * @throws \Exception|\Throwable in case delete failed.
660
     */
661 6
    public function delete()
662
    {
663 6
        if (!$this->isTransactional(self::OP_DELETE)) {
664 6
            return $this->deleteInternal();
665
        }
666
667
        $transaction = static::getDb()->beginTransaction();
668
        try {
669
            $result = $this->deleteInternal();
670
            if ($result === false) {
671
                $transaction->rollBack();
672
            } else {
673
                $transaction->commit();
674
            }
675
676
            return $result;
677
        } catch (\Exception $e) {
678
            $transaction->rollBack();
679
            throw $e;
680
        } 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...
681
            $transaction->rollBack();
682
            throw $e;
683
        }
684
    }
685
686
    /**
687
     * Deletes an ActiveRecord without considering transaction.
688
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
689
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
690
     * @throws StaleObjectException
691
     */
692 6
    protected function deleteInternal()
693
    {
694 6
        if (!$this->beforeDelete()) {
695
            return false;
696
        }
697
698
        // we do not check the return value of deleteAll() because it's possible
699
        // the record is already deleted in the database and thus the method will return 0
700 6
        $condition = $this->getOldPrimaryKey(true);
701 6
        $lock = $this->optimisticLock();
702 6
        if ($lock !== null) {
703
            $condition[$lock] = $this->$lock;
704
        }
705 6
        $result = static::deleteAll($condition);
706 6
        if ($lock !== null && !$result) {
707
            throw new StaleObjectException('The object being deleted is outdated.');
708
        }
709 6
        $this->setOldAttributes(null);
710 6
        $this->afterDelete();
711
712 6
        return $result;
713
    }
714
715
    /**
716
     * Returns a value indicating whether the given active record is the same as the current one.
717
     * The comparison is made by comparing the table names and the primary key values of the two active records.
718
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
719
     * @param ActiveRecord $record record to compare to
720
     * @return bool whether the two active records refer to the same row in the same database table.
721
     */
722 3
    public function equals($record)
723
    {
724 3
        if ($this->isNewRecord || $record->isNewRecord) {
725 3
            return false;
726
        }
727
728 3
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
729
    }
730
731
    /**
732
     * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
733
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
734
     * @return bool whether the specified operation is transactional in the current [[scenario]].
735
     */
736 107
    public function isTransactional($operation)
737
    {
738 107
        $scenario = $this->getScenario();
739 107
        $transactions = $this->transactions();
740
741 107
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
742
    }
743
}
744