Passed
Push — master ( 537eca...d2535c )
by Sergei
02:59
created

AbstractActiveRecord::insert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord;
6
7
use Closure;
8
use ReflectionException;
9
use Throwable;
10
use Yiisoft\Db\Connection\ConnectionInterface;
11
use Yiisoft\Db\Exception\Exception;
12
use Yiisoft\Db\Exception\InvalidArgumentException;
13
use Yiisoft\Db\Exception\InvalidCallException;
14
use Yiisoft\Db\Exception\InvalidConfigException;
15
use Yiisoft\Db\Exception\NotSupportedException;
16
use Yiisoft\Db\Exception\StaleObjectException;
17
use Yiisoft\Db\Expression\Expression;
18
use Yiisoft\Db\Helper\DbStringHelper;
19
20
use function array_diff_key;
21
use function array_diff;
22
use function array_fill_keys;
23
use function array_flip;
24
use function array_intersect;
25
use function array_intersect_key;
26
use function array_key_exists;
27
use function array_keys;
28
use function array_merge;
29
use function array_search;
30
use function array_values;
31
use function count;
32
use function get_object_vars;
33
use function in_array;
34
use function is_array;
35
use function is_int;
36
use function reset;
37
38
/**
39
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
40
 *
41
 * See {@see ActiveRecord} for a concrete implementation.
42
 */
43
abstract class AbstractActiveRecord implements ActiveRecordInterface
44
{
45
    private array|null $oldAttributes = null;
46
    private array $related = [];
47
    /** @psalm-var string[][] */
48
    private array $relationsDependencies = [];
49
50
    public function __construct(
51
        protected ConnectionInterface $db,
52
        private ActiveRecordFactory|null $arFactory = null,
53
        private string $tableName = ''
54
    ) {
55
    }
56
57
    public function delete(): int
58
    {
59
        return $this->deleteInternal();
60
    }
61
62
    public function deleteAll(array $condition = [], array $params = []): int
63
    {
64
        $command = $this->db->createCommand();
65
        $command->delete($this->getTableName(), $condition, $params);
66
67
        return $command->execute();
68
    }
69
70
    public function equals(ActiveRecordInterface $record): bool
71
    {
72
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
73
            return false;
74
        }
75
76
        return $this->getTableName() === $record->getTableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
77
    }
78
79
    public function getAttribute(string $name): mixed
80
    {
81
        return get_object_vars($this)[$name] ?? null;
82
    }
83
84
    public function getAttributes(array $names = null, array $except = []): array
85
    {
86
        $names ??= $this->attributes();
87
        $attributes = get_object_vars($this);
88
89
        if ($except !== []) {
90
            $names = array_diff($names, $except);
91
        }
92
93
        return array_intersect_key($attributes, array_flip($names));
94
    }
95
96
    public function getIsNewRecord(): bool
97
    {
98
        return $this->oldAttributes === null;
99
    }
100
101
    /**
102
     * Returns the old value of the named attribute.
103
     *
104
     * If this record is the result of a query and the attribute is not loaded, `null` will be returned.
105
     *
106
     * @param string $name The attribute name.
107
     *
108
     * @return mixed the old attribute value. `null` if the attribute is not loaded before or does not exist.
109
     *
110
     * {@see hasAttribute()}
111
     */
112
    public function getOldAttribute(string $name): mixed
113
    {
114
        return $this->oldAttributes[$name] ?? null;
115
    }
116
117
    /**
118
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
119
     *
120
     * The comparison of new and old values is made for identical values using `===`.
121
     *
122
     * @param array|null $names The names of the attributes whose values may be returned if they are changed recently.
123
     * If null, {@see attributes()} will be used.
124
     *
125
     * @return array The changed attribute values (name-value pairs).
126
     */
127
    public function getDirtyAttributes(array $names = null): array
128
    {
129
        $attributes = $this->getAttributes($names);
130
131
        if ($this->oldAttributes === null) {
132
            return $attributes;
133
        }
134
135
        $result = array_diff_key($attributes, $this->oldAttributes);
136
137
        foreach (array_diff_key($attributes, $result) as $name => $value) {
138
            if ($value !== $this->oldAttributes[$name]) {
139
                $result[$name] = $value;
140
            }
141
        }
142
143
        return $result;
144
    }
145
146
    public function getOldAttributes(): array
147
    {
148
        return $this->oldAttributes ?? [];
149
    }
150
151
    /**
152
     * @throws InvalidConfigException
153
     * @throws Exception
154
     */
155
    public function getOldPrimaryKey(bool $asArray = false): mixed
156
    {
157
        $keys = $this->primaryKey();
158
159
        if (empty($keys)) {
160
            throw new Exception(
161
                static::class . ' does not have a primary key. You should either define a primary key for '
162
                . 'the corresponding table or override the primaryKey() method.'
163
            );
164
        }
165
166
        if (count($keys) === 1) {
167
            $key = $this->oldAttributes[$keys[0]] ?? null;
168
169
            return $asArray ? [$keys[0] => $key] : $key;
170
        }
171
172
        $values = [];
173
174
        foreach ($keys as $name) {
175
            $values[$name] = $this->oldAttributes[$name] ?? null;
176
        }
177
178
        return $values;
179
    }
180
181
    public function getPrimaryKey(bool $asArray = false): mixed
182
    {
183
        $keys = $this->primaryKey();
184
185
        if (count($keys) === 1) {
186
            return $asArray ? [$keys[0] => $this->getAttribute($keys[0])] : $this->getAttribute($keys[0]);
187
        }
188
189
        $values = [];
190
191
        foreach ($keys as $name) {
192
            $values[$name] = $this->getAttribute($name);
193
        }
194
195
        return $values;
196
    }
197
198
    /**
199
     * Returns all populated related records.
200
     *
201
     * @return array An array of related records indexed by relation names.
202
     *
203
     * {@see getRelation()}
204
     */
205
    public function getRelatedRecords(): array
206
    {
207
        return $this->related;
208
    }
209
210
    public function hasAttribute(string $name): bool
211
    {
212
        return in_array($name, $this->attributes(), true);
213
    }
214
215
    /**
216
     * Declares a `has-many` relation.
217
     *
218
     * The declaration is returned in terms of a relational {@see ActiveQuery} instance  through which the related
219
     * record can be queried and retrieved back.
220
     *
221
     * A `has-many` relation means that there are multiple related records matching the criteria set by this relation,
222
     * e.g., a customer has many orders.
223
     *
224
     * For example, to declare the `orders` relation for `Customer` class, we can write the following code in the
225
     * `Customer` class:
226
     *
227
     * ```php
228
     * public function getOrders()
229
     * {
230
     *     return $this->hasMany(Order::className(), ['customer_id' => 'id']);
231
     * }
232
     * ```
233
     *
234
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to an attribute name in the related
235
     * class `Order`, while the 'id' value refers to an attribute name in the current AR class.
236
     *
237
     * Call methods declared in {@see ActiveQuery} to further customize the relation.
238
     *
239
     * @param string $class The class name of the related record
240
     * @param array $link The primary-foreign key constraint. The keys of the array refer to the attributes of the
241
     * record associated with the `$class` model, while the values of the array refer to the corresponding attributes in
242
     * **this** AR class.
243
     *
244
     * @return ActiveQueryInterface The relational query object.
245
     *
246
     * @psalm-param class-string<ActiveRecordInterface> $class
247
     */
248
    public function hasMany(string $class, array $link): ActiveQueryInterface
249
    {
250
        return $this->createRelationQuery($class, $link, true);
251
    }
252
253
    /**
254
     * Declares a `has-one` relation.
255
     *
256
     * The declaration is returned in terms of a relational {@see ActiveQuery} instance through which the related record
257
     * can be queried and retrieved back.
258
     *
259
     * A `has-one` relation means that there is at most one related record matching the criteria set by this relation,
260
     * e.g., a customer has one country.
261
     *
262
     * For example, to declare the `country` relation for `Customer` class, we can write the following code in the
263
     * `Customer` class:
264
     *
265
     * ```php
266
     * public function getCountry()
267
     * {
268
     *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
269
     * }
270
     * ```
271
     *
272
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name in the related class
273
     * `Country`, while the 'country_id' value refers to an attribute name in the current AR class.
274
     *
275
     * Call methods declared in {@see ActiveQuery} to further customize the relation.
276
     *
277
     * @param string $class The class name of the related record.
278
     * @param array $link The primary-foreign key constraint. The keys of the array refer to the attributes of the
279
     * record associated with the `$class` model, while the values of the array refer to the corresponding attributes in
280
     * **this** AR class.
281
     *
282
     * @return ActiveQueryInterface The relational query object.
283
     *
284
     * @psalm-param class-string<ActiveRecordInterface> $class
285
     */
286
    public function hasOne(string $class, array $link): ActiveQueryInterface
287
    {
288
        return $this->createRelationQuery($class, $link, false);
289
    }
290
291
    public function insert(array $attributes = null): bool
292
    {
293
        return $this->insertInternal($attributes);
294
    }
295
296
    abstract protected function insertInternal(array $attributes = null): bool;
297
298
    /**
299
     * @psalm-param class-string<ActiveRecordInterface> $arClass
300
     */
301
    public function instantiateQuery(string $arClass): ActiveQueryInterface
302
    {
303
        return new ActiveQuery($arClass, $this->db, $this->arFactory);
304
    }
305
306
    /**
307
     * Returns a value indicating whether the named attribute has been changed.
308
     *
309
     * @param string $name The name of the attribute.
310
     * @param bool $identical Whether the comparison of new and old value is made for identical values using `===`,
311
     * defaults to `true`. Otherwise `==` is used for comparison.
312
     *
313
     * @return bool Whether the attribute has been changed.
314
     */
315
    public function isAttributeChanged(string $name, bool $identical = true): bool
0 ignored issues
show
Unused Code introduced by
The parameter $identical is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

315
    public function isAttributeChanged(string $name, /** @scrutinizer ignore-unused */ bool $identical = true): bool

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
316
    {
317
        if (isset($this->oldAttributes[$name])) {
318
            return $this->$name !== $this->oldAttributes[$name];
319
        }
320
321
        return false;
322
    }
323
324
    public function isPrimaryKey(array $keys): bool
325
    {
326
        $pks = $this->primaryKey();
327
328
        return count($keys) === count($pks)
329
            && count(array_intersect($keys, $pks)) === count($pks);
330
    }
331
332
    public function isRelationPopulated(string $name): bool
333
    {
334
        return array_key_exists($name, $this->related);
335
    }
336
337
    public function link(string $name, ActiveRecordInterface $arClass, array $extraColumns = []): void
338
    {
339
        $viaClass = null;
340
        $viaTable = null;
341
        $relation = $this->getRelation($name);
342
        $via = $relation?->getVia();
343
344
        if ($via !== null) {
345
            if ($this->getIsNewRecord() || $arClass->getIsNewRecord()) {
346
                throw new InvalidCallException(
347
                    'Unable to link models: the models being linked cannot be newly created.'
348
                );
349
            }
350
351
            if (is_array($via)) {
352
                [$viaName, $viaRelation] = $via;
353
                /** @psalm-var ActiveQueryInterface $viaRelation */
354
                $viaClass = $viaRelation->getARInstance();
355
                // unset $viaName so that it can be reloaded to reflect the change.
356
                /** @psalm-var string $viaName */
357
                unset($this->related[$viaName]);
358
            }
359
360
            if ($via instanceof ActiveQueryInterface) {
361
                $viaRelation = $via;
362
                $from = $via->getFrom();
363
                /** @psalm-var string $viaTable */
364
                $viaTable = reset($from);
365
            }
366
367
            $columns = [];
368
369
            /** @psalm-var ActiveQueryInterface|null $viaRelation */
370
            $viaLink = $viaRelation?->getLink() ?? [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaRelation does not seem to be defined for all execution paths leading up to this point.
Loading history...
371
372
            /**
373
             * @psalm-var string $a
374
             * @psalm-var string $b
375
             */
376
            foreach ($viaLink as $a => $b) {
377
                /** @psalm-var mixed */
378
                $columns[$a] = $this->$b;
379
            }
380
381
            $link = $relation?->getLink() ?? [];
382
383
            /**
384
             * @psalm-var string $a
385
             * @psalm-var string $b
386
             */
387
            foreach ($link as $a => $b) {
388
                /** @psalm-var mixed */
389
                $columns[$b] = $arClass->$a;
390
            }
391
392
            /**
393
             * @psalm-var string $k
394
             * @psalm-var mixed $v
395
             */
396
            foreach ($extraColumns as $k => $v) {
397
                /** @psalm-var mixed */
398
                $columns[$k] = $v;
399
            }
400
401
            if ($viaClass instanceof ActiveRecordInterface && is_array($via)) {
402
                /**
403
                 * @psalm-var string $column
404
                 * @psalm-var mixed $value
405
                 */
406
                foreach ($columns as $column => $value) {
407
                    $viaClass->$column = $value;
408
                }
409
410
                $viaClass->insert();
411
            } elseif (is_string($viaTable)) {
412
                $this->db->createCommand()->insert($viaTable, $columns)->execute();
413
            }
414
        } elseif ($relation instanceof ActiveQueryInterface) {
415
            $link = $relation->getLink();
416
            $p1 = $arClass->isPrimaryKey(array_keys($link));
417
            $p2 = $this->isPrimaryKey(array_values($link));
418
419
            if ($p1 && $p2) {
420
                if ($this->getIsNewRecord() && $arClass->getIsNewRecord()) {
421
                    throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
422
                }
423
424
                if ($this->getIsNewRecord()) {
425
                    $this->bindModels(array_flip($link), $this, $arClass);
426
                } else {
427
                    $this->bindModels($link, $arClass, $this);
428
                }
429
            } elseif ($p1) {
430
                $this->bindModels(array_flip($link), $this, $arClass);
431
            } elseif ($p2) {
432
                $this->bindModels($link, $arClass, $this);
433
            } else {
434
                throw new InvalidCallException(
435
                    'Unable to link models: the link defining the relation does not involve any primary key.'
436
                );
437
            }
438
        }
439
440
        // update lazily loaded related objects
441
        if ($relation instanceof ActiveRecordInterface && !$relation->getMultiple()) {
0 ignored issues
show
Bug introduced by
The method getMultiple() does not exist on Yiisoft\ActiveRecord\ActiveRecordInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

441
        if ($relation instanceof ActiveRecordInterface && !$relation->/** @scrutinizer ignore-call */ getMultiple()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
442
            $this->related[$name] = $arClass;
443
        } elseif (isset($this->related[$name])) {
444
            $indexBy = $relation?->getIndexBy();
445
            if ($indexBy !== null) {
446
                if ($indexBy instanceof Closure) {
447
                    $index = $relation?->indexBy($arClass::class);
448
                } else {
449
                    $index = $arClass->$indexBy;
450
                }
451
452
                if ($index !== null) {
453
                    $this->related[$name][$index] = $arClass;
454
                }
455
            } else {
456
                $this->related[$name][] = $arClass;
457
            }
458
        }
459
    }
460
461
    /**
462
     * Marks an attribute dirty.
463
     *
464
     * This method may be called to force updating a record when calling {@see update()}, even if there is no change
465
     * being made to the record.
466
     *
467
     * @param string $name The attribute name.
468
     */
469
    public function markAttributeDirty(string $name): void
470
    {
471
        if ($this->oldAttributes !== null && $name !== '') {
472
            unset($this->oldAttributes[$name]);
473
        }
474
    }
475
476
    /**
477
     * Returns the name of the column that stores the lock version for implementing optimistic locking.
478
     *
479
     * Optimistic locking allows multiple users to access the same record for edits and avoids potential conflicts. In
480
     * case when a user attempts to save the record upon some staled data (because another user has modified the data),
481
     * a {@see StaleObjectException} exception will be thrown, and the update or deletion is skipped.
482
     *
483
     * Optimistic locking is only supported by {@see update()} and {@see delete()}.
484
     *
485
     * To use Optimistic locking:
486
     *
487
     * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
488
     *    Override this method to return the name of this column.
489
     * 2. In the Web form that collects the user input, add a hidden field that stores the lock version of the recording
490
     *    being updated.
491
     * 3. In the controller action that does the data updating, try to catch the {@see StaleObjectException} and
492
     *    implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
493
     *
494
     * @return string|null The column name that stores the lock version of a table row. If `null` is returned (default
495
     * implemented), optimistic locking will not be supported.
496
     */
497
    public function optimisticLock(): string|null
498
    {
499
        return null;
500
    }
501
502
    /**
503
     * Populates an active record object using a row of data from the database/storage.
504
     *
505
     * This is an internal method meant to be called to create active record objects after fetching data from the
506
     * database. It is mainly used by {@see ActiveQuery} to populate the query results into active records.
507
     *
508
     * @param array|object $row Attribute values (name => value).
509
     */
510
    public function populateRecord(array|object $row): void
511
    {
512
        foreach ($row as $name => $value) {
513
            $this->populateAttribute($name, $value);
514
            $this->oldAttributes[$name] = $value;
515
        }
516
517
        $this->related = [];
518
        $this->relationsDependencies = [];
519
    }
520
521
    public function populateRelation(string $name, array|ActiveRecordInterface|null $records): void
522
    {
523
        foreach ($this->relationsDependencies as &$relationNames) {
524
            unset($relationNames[$name]);
525
        }
526
527
        $this->related[$name] = $records;
528
    }
529
530
    /**
531
     * Repopulates this active record with the latest data.
532
     *
533
     * @return bool Whether the row still exists in the database. If `true`, the latest data will be populated to this
534
     * active record. Otherwise, this record will remain unchanged.
535
     */
536
    public function refresh(): bool
537
    {
538
        $record = $this->instantiateQuery(static::class)->findOne($this->getPrimaryKey(true));
539
540
        return $this->refreshInternal($record);
541
    }
542
543
    public function resetRelation(string $name): void
544
    {
545
        foreach ($this->relationsDependencies as &$relationNames) {
546
            unset($relationNames[$name]);
547
        }
548
549
        unset($this->related[$name]);
550
    }
551
552
    protected function retrieveRelation(string $name): ActiveRecordInterface|array|null
553
    {
554
        /** @var ActiveQueryInterface $query */
555
        $query = $this->getRelation($name);
556
557
        $this->setRelationDependencies($name, $query);
558
559
        return $this->related[$name] = $query->relatedRecords();
560
    }
561
562
    /**
563
     * Saves the current record.
564
     *
565
     * This method will call {@see insert()} when {@see getIsNewRecord} is `true`, or {@see update()} when
566
     * {@see getIsNewRecord} is `false`.
567
     *
568
     * For example, to save a customer record:
569
     *
570
     * ```php
571
     * $customer = new Customer($db);
572
     * $customer->name = $name;
573
     * $customer->email = $email;
574
     * $customer->save();
575
     * ```
576
     *
577
     * @param array|null $attributeNames List of attribute names that need to be saved. Defaults to null, meaning all
578
     * attributes that are loaded from DB will be saved.
579
     *
580
     * @throws InvalidConfigException
581
     * @throws StaleObjectException
582
     * @throws Throwable
583
     *
584
     * @return bool Whether the saving succeeded (i.e. no validation errors occurred).
585
     */
586
    public function save(array $attributeNames = null): bool
587
    {
588
        if ($this->getIsNewRecord()) {
589
            return $this->insert($attributeNames);
590
        }
591
592
        $this->update($attributeNames);
593
594
        return true;
595
    }
596
597
    public function setAttribute(string $name, mixed $value): void
598
    {
599
        if (
600
            isset($this->relationsDependencies[$name])
601
            && (!isset(get_object_vars($this)[$name]) || $this->$name !== $value)
602
        ) {
603
            $this->resetDependentRelations($name);
604
        }
605
606
        $this->$name = $value;
607
    }
608
609
    /**
610
     * Sets the attribute values in a massive way.
611
     *
612
     * @param array $values Attribute values (name => value) to be assigned to the model.
613
     *
614
     * {@see attributes()}
615
     */
616
    public function setAttributes(array $values): void
617
    {
618
        $values = array_intersect_key($values, array_flip($this->attributes()));
619
620
        /** @psalm-var mixed $value */
621
        foreach ($values as $name => $value) {
622
            $this->$name = $value;
623
        }
624
    }
625
626
    /**
627
     * Sets the value indicating whether the record is new.
628
     *
629
     * @param bool $value whether the record is new and should be inserted when calling {@see save()}.
630
     *
631
     * @see getIsNewRecord()
632
     */
633
    public function setIsNewRecord(bool $value): void
634
    {
635
        $this->oldAttributes = $value ? null : get_object_vars($this);
636
    }
637
638
    /**
639
     * Sets the old value of the named attribute.
640
     *
641
     * @param string $name The attribute name.
642
     *
643
     * @throws InvalidArgumentException If the named attribute does not exist.
644
     *
645
     * {@see hasAttribute()}
646
     */
647
    public function setOldAttribute(string $name, mixed $value): void
648
    {
649
        if (isset($this->oldAttributes[$name]) || $this->hasAttribute($name)) {
650
            $this->oldAttributes[$name] = $value;
651
        } else {
652
            throw new InvalidArgumentException(static::class . ' has no attribute named "' . $name . '".');
653
        }
654
    }
655
656
    /**
657
     * Sets the old attribute values.
658
     *
659
     * All existing old attribute values will be discarded.
660
     *
661
     * @param array|null $values Old attribute values to be set. If set to `null` this record is considered to be
662
     * {@see isNewRecord|new}.
663
     */
664
    public function setOldAttributes(array $values = null): void
665
    {
666
        $this->oldAttributes = $values;
667
    }
668
669
    public function update(array $attributeNames = null): int
670
    {
671
        return $this->updateInternal($attributeNames);
672
    }
673
674
    public function updateAll(array $attributes, array|string $condition = [], array $params = []): int
675
    {
676
        $command = $this->db->createCommand();
677
678
        $command->update($this->getTableName(), $attributes, $condition, $params);
679
680
        return $command->execute();
681
    }
682
683
    public function updateAttributes(array $attributes): int
684
    {
685
        $attrs = [];
686
687
        foreach ($attributes as $name => $value) {
688
            if (is_int($name)) {
689
                $attrs[] = $value;
690
            } else {
691
                $this->setAttribute($name, $value);
692
                $attrs[] = $name;
693
            }
694
        }
695
696
        $values = $this->getDirtyAttributes($attrs);
697
698
        if (empty($values) || $this->getIsNewRecord()) {
699
            return 0;
700
        }
701
702
        $rows = $this->updateAll($values, $this->getOldPrimaryKey(true));
703
704
        $this->oldAttributes = array_merge($this->oldAttributes ?? [], $values);
705
706
        return $rows;
707
    }
708
709
    /**
710
     * Updates the whole table using the provided counter changes and conditions.
711
     *
712
     * For example, to increment all customers' age by 1,
713
     *
714
     * ```php
715
     * $customer = new Customer($db);
716
     * $customer->updateAllCounters(['age' => 1]);
717
     * ```
718
     *
719
     * Note that this method will not trigger any events.
720
     *
721
     * @param array $counters The counters to be updated (attribute name => increment value).
722
     * Use negative values if you want to decrement the counters.
723
     * @param array|string $condition The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer
724
     * to {@see Query::where()} on how to specify this parameter.
725
     * @param array $params The parameters (name => value) to be bound to the query.
726
     *
727
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
728
     *
729
     * @throws Exception
730
     * @throws InvalidConfigException
731
     * @throws Throwable
732
     *
733
     * @return int The number of rows updated.
734
     */
735
    public function updateAllCounters(array $counters, array|string $condition = '', array $params = []): int
736
    {
737
        $n = 0;
738
739
        /** @psalm-var array<string, int> $counters */
740
        foreach ($counters as $name => $value) {
741
            $counters[$name] = new Expression("[[$name]]+:bp$n", [":bp$n" => $value]);
742
            $n++;
743
        }
744
745
        $command = $this->db->createCommand();
746
        $command->update($this->getTableName(), $counters, $condition, $params);
747
748
        return $command->execute();
749
    }
750
751
    /**
752
     * Updates one or several counter columns for the current AR object.
753
     *
754
     * Note that this method differs from {@see updateAllCounters()} in that it only saves counters for the current AR
755
     * object.
756
     *
757
     * An example usage is as follows:
758
     *
759
     * ```php
760
     * $post = new Post($db);
761
     * $post->updateCounters(['view_count' => 1]);
762
     * ```
763
     *
764
     * @param array $counters The counters to be updated (attribute name => increment value), use negative values if you
765
     * want to decrement the counters.
766
     *
767
     * @psalm-param array<string, int> $counters
768
     *
769
     * @throws Exception
770
     * @throws NotSupportedException
771
     *
772
     * @return bool Whether the saving is successful.
773
     *
774
     * {@see updateAllCounters()}
775
     */
776
    public function updateCounters(array $counters): bool
777
    {
778
        if ($this->updateAllCounters($counters, $this->getOldPrimaryKey(true)) === 0) {
779
            return false;
780
        }
781
782
        foreach ($counters as $name => $value) {
783
            $value += $this->$name ?? 0;
784
            $this->$name = $value;
785
            $this->oldAttributes[$name] = $value;
786
        }
787
788
        return true;
789
    }
790
791
    public function unlink(string $name, ActiveRecordInterface $arClass, bool $delete = false): void
792
    {
793
        $viaClass = null;
794
        $viaTable = null;
795
        $relation = $this->getRelation($name);
796
        $viaRelation = $relation?->getVia();
797
798
        if ($viaRelation !== null) {
799
            if (is_array($viaRelation)) {
800
                [$viaName, $viaRelation] = $viaRelation;
801
                /** @psalm-var ActiveQueryInterface $viaRelation */
802
                $viaClass = $viaRelation->getARInstance();
803
                /** @psalm-var string $viaName */
804
                unset($this->related[$viaName]);
805
            }
806
807
            $columns = [];
808
            $nulls = [];
809
810
            if ($viaRelation instanceof ActiveQueryInterface) {
811
                $from = $viaRelation->getFrom();
812
                /** @psalm-var mixed $viaTable */
813
                $viaTable = reset($from);
814
815
                foreach ($viaRelation->getLink() as $a => $b) {
816
                    /** @psalm-var mixed */
817
                    $columns[$a] = $this->$b;
818
                }
819
820
                $link = $relation?->getLink() ?? [];
821
822
                foreach ($link as $a => $b) {
823
                    /** @psalm-var mixed */
824
                    $columns[$b] = $arClass->$a;
825
                }
826
827
                $nulls = array_fill_keys(array_keys($columns), null);
828
829
                if ($viaRelation->getOn() !== null) {
830
                    $columns = ['and', $columns, $viaRelation->getOn()];
831
                }
832
            }
833
834
            if ($viaClass instanceof ActiveRecordInterface) {
835
                if ($delete) {
836
                    $viaClass->deleteAll($columns);
837
                } else {
838
                    $viaClass->updateAll($nulls, $columns);
839
                }
840
            } elseif (is_string($viaTable)) {
841
                $command = $this->db->createCommand();
842
                if ($delete) {
843
                    $command->delete($viaTable, $columns)->execute();
844
                } else {
845
                    $command->update($viaTable, $nulls, $columns)->execute();
846
                }
847
            }
848
        } elseif ($relation instanceof ActiveQueryInterface) {
849
            if ($this->isPrimaryKey($relation->getLink())) {
850
                if ($delete) {
851
                    $arClass->delete();
852
                } else {
853
                    foreach ($relation->getLink() as $a => $b) {
854
                        $arClass->$a = null;
855
                    }
856
                    $arClass->save();
857
                }
858
            } elseif ($arClass->isPrimaryKey(array_keys($relation->getLink()))) {
859
                foreach ($relation->getLink() as $a => $b) {
860
                    /** @psalm-var mixed $values */
861
                    $values = $this->$b;
862
                    /** relation via array valued attribute */
863
                    if (is_array($values)) {
864
                        if (($key = array_search($arClass->$a, $values, false)) !== false) {
865
                            unset($values[$key]);
866
                            $this->$b = array_values($values);
867
                        }
868
                    } else {
869
                        $this->$b = null;
870
                    }
871
                }
872
                $delete ? $this->delete() : $this->save();
873
            } else {
874
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
875
            }
876
        }
877
878
        if ($relation instanceof ActiveQueryInterface && !$relation->getMultiple()) {
879
            unset($this->related[$name]);
880
        } elseif (isset($this->related[$name]) && is_array($this->related[$name])) {
881
            /** @psalm-var array<array-key, ActiveRecordInterface> $related */
882
            $related = $this->related[$name];
883
            foreach ($related as $a => $b) {
884
                if ($arClass->getPrimaryKey() === $b->getPrimaryKey()) {
885
                    unset($this->related[$name][$a]);
886
                }
887
            }
888
        }
889
    }
890
891
    /**
892
     * Destroys the relationship in current model.
893
     *
894
     * The active record with the foreign key of the relationship will be deleted if `$delete` is `true`. Otherwise, the
895
     * foreign key will be set `null` and the model will be saved without validation.
896
     *
897
     * Note that to destroy the relationship without removing records make sure your keys can be set to null.
898
     *
899
     * @param string $name The case sensitive name of the relationship, e.g. `orders` for a relation defined via
900
     * `getOrders()` method.
901
     * @param bool $delete Whether to delete the model that contains the foreign key.
902
     *
903
     * @throws Exception
904
     * @throws ReflectionException
905
     * @throws StaleObjectException
906
     * @throws Throwable
907
     */
908
    public function unlinkAll(string $name, bool $delete = false): void
909
    {
910
        $viaClass = null;
911
        $viaTable = null;
912
        $relation = $this->getRelation($name);
913
        $viaRelation = $relation?->getVia();
914
915
        if ($relation instanceof ActiveQueryInterface && $viaRelation !== null) {
916
            if (is_array($viaRelation)) {
917
                [$viaName, $viaRelation] = $viaRelation;
918
                /** @psalm-var ActiveQueryInterface $viaRelation */
919
                $viaClass = $viaRelation->getARInstance();
920
                /** @psalm-var string $viaName */
921
                unset($this->related[$viaName]);
922
            } else {
923
                $from = $viaRelation->getFrom();
924
                /** @psalm-var mixed $viaTable */
925
                $viaTable = reset($from);
926
            }
927
928
            $condition = [];
929
            $nulls = [];
930
931
            if ($viaRelation instanceof ActiveQueryInterface) {
932
                foreach ($viaRelation->getLink() as $a => $b) {
933
                    $nulls[$a] = null;
934
                    /** @psalm-var mixed */
935
                    $condition[$a] = $this->$b;
936
                }
937
938
                if (!empty($viaRelation->getWhere())) {
939
                    $condition = ['and', $condition, $viaRelation->getWhere()];
940
                }
941
942
                if (!empty($viaRelation->getOn())) {
943
                    $condition = ['and', $condition, $viaRelation->getOn()];
944
                }
945
            }
946
947
            if ($viaClass instanceof ActiveRecordInterface) {
948
                if ($delete) {
949
                    $viaClass->deleteAll($condition);
950
                } else {
951
                    $viaClass->updateAll($nulls, $condition);
952
                }
953
            } elseif (is_string($viaTable)) {
954
                $command = $this->db->createCommand();
955
                if ($delete) {
956
                    $command->delete($viaTable, $condition)->execute();
957
                } else {
958
                    $command->update($viaTable, $nulls, $condition)->execute();
959
                }
960
            }
961
        } elseif ($relation instanceof ActiveQueryInterface) {
962
            $relatedModel = $relation->getARInstance();
963
964
            $link = $relation->getLink();
965
            if (!$delete && count($link) === 1 && is_array($this->{$b = reset($link)})) {
966
                /** relation via array valued attribute */
967
                $this->$b = [];
968
                $this->save();
969
            } else {
970
                $nulls = [];
971
                $condition = [];
972
973
                foreach ($relation->getLink() as $a => $b) {
974
                    $nulls[$a] = null;
975
                    /** @psalm-var mixed */
976
                    $condition[$a] = $this->$b;
977
                }
978
979
                if (!empty($relation->getWhere())) {
980
                    $condition = ['and', $condition, $relation->getWhere()];
981
                }
982
983
                if (!empty($relation->getOn())) {
984
                    $condition = ['and', $condition, $relation->getOn()];
985
                }
986
987
                if ($delete) {
988
                    $relatedModel->deleteAll($condition);
989
                } else {
990
                    $relatedModel->updateAll($nulls, $condition);
991
                }
992
            }
993
        }
994
995
        unset($this->related[$name]);
996
    }
997
998
    /**
999
     * Sets relation dependencies for a property.
1000
     *
1001
     * @param string $name property name.
1002
     * @param ActiveQueryInterface $relation relation instance.
1003
     * @param string|null $viaRelationName intermediate relation.
1004
     */
1005
    protected function setRelationDependencies(
1006
        string $name,
1007
        ActiveQueryInterface $relation,
1008
        string $viaRelationName = null
1009
    ): void {
1010
        $via = $relation->getVia();
1011
1012
        if (empty($via)) {
1013
            foreach ($relation->getLink() as $attribute) {
1014
                $this->relationsDependencies[$attribute][$name] = $name;
1015
                if ($viaRelationName !== null) {
1016
                    $this->relationsDependencies[$attribute][] = $viaRelationName;
1017
                }
1018
            }
1019
        } elseif ($via instanceof ActiveQueryInterface) {
1020
            $this->setRelationDependencies($name, $via);
1021
        } else {
1022
            /**
1023
             * @psalm-var string|null $viaRelationName
1024
             * @psalm-var ActiveQueryInterface $viaQuery
1025
             */
1026
            [$viaRelationName, $viaQuery] = $via;
1027
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1028
        }
1029
    }
1030
1031
    /**
1032
     * Creates a query instance for `has-one` or `has-many` relation.
1033
     *
1034
     * @param string $arClass The class name of the related record.
1035
     * @param array $link The primary-foreign key constraint.
1036
     * @param bool $multiple Whether this query represents a relation to more than one record.
1037
     *
1038
     * @return ActiveQueryInterface The relational query object.
1039
     *
1040
     * @psalm-param class-string<ActiveRecordInterface> $arClass
1041
1042
     * {@see hasOne()}
1043
     * {@see hasMany()}
1044
     */
1045
    protected function createRelationQuery(string $arClass, array $link, bool $multiple): ActiveQueryInterface
1046
    {
1047
        return $this->instantiateQuery($arClass)->primaryModel($this)->link($link)->multiple($multiple);
1048
    }
1049
1050
    /**
1051
     * {@see delete()}
1052
     *
1053
     * @throws Exception
1054
     * @throws StaleObjectException
1055
     * @throws Throwable
1056
     *
1057
     * @return int The number of rows deleted.
1058
     */
1059
    protected function deleteInternal(): int
1060
    {
1061
        /**
1062
         * We do not check the return value of deleteAll() because it's possible the record is already deleted in
1063
         * the database and thus the method will return 0
1064
         */
1065
        $condition = $this->getOldPrimaryKey(true);
1066
        $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting Yiisoft\ActiveRecord\Abs...ecord::optimisticLock() seems to always return null.

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

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

}

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

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

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

Loading history...
1067
1068
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
1069
            $condition[$lock] = $this->$lock;
1070
1071
            $result = $this->deleteAll($condition);
1072
1073
            if ($result === 0) {
1074
                throw new StaleObjectException('The object being deleted is outdated.');
1075
            }
1076
        } else {
1077
            $result = $this->deleteAll($condition);
1078
        }
1079
1080
        $this->setOldAttributes();
1081
1082
        return $result;
1083
    }
1084
1085
    /**
1086
     * Repopulates this active record with the latest data from a newly fetched instance.
1087
     *
1088
     * @param ActiveRecordInterface|array|null $record The record to take attributes from.
1089
     *
1090
     * @return bool Whether refresh was successful.
1091
     *
1092
     * {@see refresh()}
1093
     */
1094
    protected function refreshInternal(array|ActiveRecordInterface $record = null): bool
1095
    {
1096
        if ($record === null || is_array($record)) {
0 ignored issues
show
introduced by
The condition is_array($record) is always true.
Loading history...
1097
            return false;
1098
        }
1099
1100
        foreach ($this->attributes() as $name) {
1101
            $this->setAttribute($name, $record->getAttribute($name));
1102
        }
1103
1104
        $this->oldAttributes = $record->getOldAttributes();
1105
        $this->related = [];
1106
        $this->relationsDependencies = [];
1107
1108
        return true;
1109
    }
1110
1111
    /**
1112
     * {@see update()}
1113
     *
1114
     * @param array|null $attributes Attributes to update.
1115
     *
1116
     * @throws Exception
1117
     * @throws NotSupportedException
1118
     * @throws StaleObjectException
1119
     *
1120
     * @return int The number of rows affected.
1121
     */
1122
    protected function updateInternal(array $attributes = null): int
1123
    {
1124
        $values = $this->getDirtyAttributes($attributes);
1125
1126
        if (empty($values)) {
1127
            return 0;
1128
        }
1129
1130
        $condition = $this->getOldPrimaryKey(true);
1131
        $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting Yiisoft\ActiveRecord\Abs...ecord::optimisticLock() seems to always return null.

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

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

}

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

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

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

Loading history...
1132
1133
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
1134
            $lockValue = $this->$lock;
1135
1136
            $condition[$lock] = $lockValue;
1137
            $values[$lock] = ++$lockValue;
1138
1139
            $rows = $this->updateAll($values, $condition);
1140
1141
            if ($rows === 0) {
1142
                throw new StaleObjectException('The object being updated is outdated.');
1143
            }
1144
1145
            $this->$lock = $lockValue;
1146
        } else {
1147
            $rows = $this->updateAll($values, $condition);
1148
        }
1149
1150
        $this->oldAttributes = array_merge($this->oldAttributes ?? [], $values);
1151
1152
        return $rows;
1153
    }
1154
1155
    private function bindModels(
1156
        array $link,
1157
        ActiveRecordInterface $foreignModel,
1158
        ActiveRecordInterface $primaryModel
1159
    ): void {
1160
        /** @psalm-var string[] $link */
1161
        foreach ($link as $fk => $pk) {
1162
            /** @psalm-var mixed $value */
1163
            $value = $primaryModel->$pk;
1164
1165
            if ($value === null) {
1166
                throw new InvalidCallException(
1167
                    'Unable to link active record: the primary key of ' . $primaryModel::class . ' is null.'
1168
                );
1169
            }
1170
1171
            /**
1172
             * relation via array valued attribute
1173
             *
1174
             * @psalm-suppress MixedArrayAssignment
1175
             */
1176
            if (is_array($foreignModel->getAttribute($fk))) {
1177
                /** @psalm-var mixed */
1178
                $foreignModel->{$fk}[] = $value;
1179
            } else {
1180
                $foreignModel->setAttribute($fk, $value);
1181
            }
1182
        }
1183
1184
        $foreignModel->save();
1185
    }
1186
1187
    protected function hasDependentRelations(string $attribute): bool
1188
    {
1189
        return isset($this->relationsDependencies[$attribute]);
1190
    }
1191
1192
    /**
1193
     * Resets dependent related models checking if their links contain specific attribute.
1194
     *
1195
     * @param string $attribute The changed attribute name.
1196
     */
1197
    protected function resetDependentRelations(string $attribute): void
1198
    {
1199
        foreach ($this->relationsDependencies[$attribute] as $relation) {
1200
            unset($this->related[$relation]);
1201
        }
1202
1203
        unset($this->relationsDependencies[$attribute]);
1204
    }
1205
1206
    public function getTableName(): string
1207
    {
1208
        if ($this->tableName === '') {
1209
            $this->tableName = '{{%' . DbStringHelper::pascalCaseToId(DbStringHelper::baseName(static::class)) . '}}';
1210
        }
1211
1212
        return $this->tableName;
1213
    }
1214
1215
    protected function populateAttribute(string $name, mixed $value): void
1216
    {
1217
        $this->$name = $value;
1218
    }
1219
}
1220