Passed
Push — master ( 0c8902...537eca )
by Sergei
02:46
created

AbstractActiveRecord::isRelationPopulated()   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
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
    /**
292
     * @psalm-param class-string<ActiveRecordInterface> $arClass
293
     */
294
    public function instantiateQuery(string $arClass): ActiveQueryInterface
295
    {
296
        return new ActiveQuery($arClass, $this->db, $this->arFactory);
297
    }
298
299
    /**
300
     * Returns a value indicating whether the named attribute has been changed.
301
     *
302
     * @param string $name The name of the attribute.
303
     * @param bool $identical Whether the comparison of new and old value is made for identical values using `===`,
304
     * defaults to `true`. Otherwise `==` is used for comparison.
305
     *
306
     * @return bool Whether the attribute has been changed.
307
     */
308
    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

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

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