Passed
Push — master ( dde631...13fa9d )
by Sergei
03:04
created

AbstractActiveRecord::relation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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