Passed
Push — master ( dab8d6...352e04 )
by Sergei
02:50
created

AbstractActiveRecord::link()   D

Complexity

Conditions 23
Paths 73

Size

Total Lines 117
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 62
c 0
b 0
f 0
dl 0
loc 117
rs 4.1666
cc 23
nc 73
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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