Passed
Pull Request — master (#314)
by Sergei
02:52
created

BaseActiveRecord::setRelationDependencies()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 23
ccs 8
cts 9
cp 0.8889
rs 9.6111
cc 5
nc 5
nop 3
crap 5.0342
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord;
6
7
use ArrayAccess;
8
use Closure;
9
use ReflectionException;
10
use Throwable;
11
use Yiisoft\Arrays\ArrayableInterface;
12
use Yiisoft\Arrays\ArrayableTrait;
13
use Yiisoft\Db\Connection\ConnectionInterface;
14
use Yiisoft\Db\Exception\Exception;
15
use Yiisoft\Db\Exception\InvalidArgumentException;
16
use Yiisoft\Db\Exception\InvalidCallException;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Exception\NotSupportedException;
19
use Yiisoft\Db\Exception\StaleObjectException;
20
use Yiisoft\Db\Expression\Expression;
21
use Yiisoft\Db\Helper\DbStringHelper;
22
23
use function array_combine;
24
use function array_diff_key;
25
use function array_diff;
26
use function array_fill_keys;
27
use function array_flip;
28
use function array_intersect;
29
use function array_intersect_key;
30
use function array_key_exists;
31
use function array_keys;
32
use function array_merge;
33
use function array_search;
34
use function array_values;
35
use function count;
36
use function get_object_vars;
37
use function in_array;
38
use function is_array;
39
use function is_int;
40
use function reset;
41
42
/**
43
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
44
 *
45
 * See {@see ActiveRecord} for a concrete implementation.
46
 *
47
 * @template-implements ArrayAccess<int, mixed>
48
 */
49
abstract class BaseActiveRecord implements ActiveRecordInterface, ArrayAccess, ArrayableInterface
50
{
51
    use ArrayableTrait;
52
    use BaseActiveRecordTrait;
53
54
    private array $attributes = [];
55
    private array|null $oldAttributes = null;
56
    private array $related = [];
57
    /** @psalm-var string[][] */
58
    private array $relationsDependencies = [];
59
60
    public function __construct(
61
        protected ConnectionInterface $db,
62
        private ActiveRecordFactory|null $arFactory = null,
63 719
        private string $tableName = ''
64
    ) {
65 719
    }
66 719
67 719
    public function delete(): int
68
    {
69
        return $this->deleteInternal();
70
    }
71
72
    public function deleteAll(array $condition = [], array $params = []): int
73
    {
74
        $command = $this->db->createCommand();
75
        $command->delete($this->getTableName(), $condition, $params);
76
77
        return $command->execute();
78
    }
79
80
    public function equals(ActiveRecordInterface $record): bool
81
    {
82
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
83
            return false;
84
        }
85
86
        return $this->getTableName() === $record->getTableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
87
    }
88 1
89
    /**
90 1
     * @return array The default implementation returns the names of the relations that have been populated into this
91
     * record.
92
     */
93
    public function extraFields(): array
94
    {
95
        $fields = array_keys($this->getRelatedRecords());
96
97
        return array_combine($fields, $fields);
98
    }
99
100
    /**
101
     * @psalm-return array<string, string|Closure>
102
     */
103
    public function fields(): array
104
    {
105
        $fields = array_keys($this->attributes);
106
107
        return array_combine($fields, $fields);
108
    }
109
110
    public function getAttribute(string $name): mixed
111 1
    {
112
        return $this->attributes[$name] ?? null;
113 1
    }
114
115
    public function getAttributes(array $names = null, array $except = []): array
116
    {
117
        $names ??= $this->attributes();
118
        $attributes = array_merge($this->attributes, get_object_vars($this));
119
120
        if ($except !== []) {
121
            $names = array_diff($names, $except);
122
        }
123
124
        return array_intersect_key($attributes, array_flip($names));
125
    }
126
127
    public function getIsNewRecord(): bool
128
    {
129
        return $this->oldAttributes === null;
130
    }
131
132
    /**
133
     * Returns the old value of the named attribute.
134
     *
135
     * If this record is the result of a query and the attribute is not loaded, `null` will be returned.
136 1
     *
137
     * @param string $name The attribute name.
138 1
     *
139
     * @return mixed the old attribute value. `null` if the attribute is not loaded before or does not exist.
140
     *
141
     * {@see hasAttribute()}
142
     */
143
    public function getOldAttribute(string $name): mixed
144
    {
145
        return $this->oldAttributes[$name] ?? null;
146
    }
147
148
    /**
149
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
150
     *
151
     * The comparison of new and old values is made for identical values using `===`.
152
     *
153
     * @param array|null $names The names of the attributes whose values may be returned if they are changed recently.
154
     * If null, {@see attributes()} will be used.
155
     *
156
     * @return array The changed attribute values (name-value pairs).
157
     */
158
    public function getDirtyAttributes(array $names = null): array
159
    {
160
        $attributes = $this->getAttributes($names);
161
162 41
        if ($this->oldAttributes === null) {
163
            return $attributes;
164 41
        }
165
166
        $result = array_diff_key($attributes, $this->oldAttributes);
167
168
        foreach (array_diff_key($attributes, $result) as $name => $value) {
169
            if ($value !== $this->oldAttributes[$name]) {
170
                $result[$name] = $value;
171
            }
172
        }
173
174
        return $result;
175
    }
176
177
    public function getOldAttributes(): array
178
    {
179
        return $this->oldAttributes ?? [];
180
    }
181
182
    /**
183
     * @throws InvalidConfigException
184
     * @throws Exception
185
     */
186
    public function getOldPrimaryKey(bool $asArray = false): mixed
187
    {
188
        $keys = $this->primaryKey();
189
190
        if (empty($keys)) {
191
            throw new Exception(
192
                static::class . ' does not have a primary key. You should either define a primary key for '
193
                . 'the corresponding table or override the primaryKey() method.'
194
            );
195
        }
196
197
        if (count($keys) === 1) {
198 116
            $key = $this->oldAttributes[$keys[0]] ?? null;
199
200 116
            return $asArray ? [$keys[0] => $key] : $key;
201
        }
202
203
        $values = [];
204
205
        foreach ($keys as $name) {
206
            $values[$name] = $this->oldAttributes[$name] ?? null;
207
        }
208
209
        return $values;
210
    }
211
212
    public function getPrimaryKey(bool $asArray = false): mixed
213
    {
214
        $keys = $this->primaryKey();
215
216
        if (count($keys) === 1) {
217
            return $asArray ? [$keys[0] => $this->getAttribute($keys[0])] : $this->getAttribute($keys[0]);
218
        }
219
220
        $values = [];
221
222
        foreach ($keys as $name) {
223
            $values[$name] = $this->getAttribute($name);
224
        }
225
226
        return $values;
227
    }
228
229
    /**
230
     * Returns all populated related records.
231
     *
232
     * @return array An array of related records indexed by relation names.
233
     *
234 202
     * {@see getRelation()}
235
     */
236 202
    public function getRelatedRecords(): array
237
    {
238
        return $this->related;
239
    }
240
241
    public function hasAttribute($name): bool
242
    {
243
        return isset($this->attributes[$name]) || in_array($name, $this->attributes(), true);
244
    }
245
246
    /**
247
     * Declares a `has-many` relation.
248
     *
249
     * The declaration is returned in terms of a relational {@see ActiveQuery} instance  through which the related
250
     * record can be queried and retrieved back.
251 248
     *
252
     * A `has-many` relation means that there are multiple related records matching the criteria set by this relation,
253 248
     * e.g., a customer has many orders.
254
     *
255
     * For example, to declare the `orders` relation for `Customer` class, we can write the following code in the
256
     * `Customer` class:
257
     *
258
     * ```php
259
     * public function getOrders()
260
     * {
261
     *     return $this->hasMany(Order::className(), ['customer_id' => 'id']);
262
     * }
263
     * ```
264
     *
265
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to an attribute name in the related
266
     * class `Order`, while the 'id' value refers to an attribute name in the current AR class.
267
     *
268
     * Call methods declared in {@see ActiveQuery} to further customize the relation.
269 162
     *
270
     * @param string $class The class name of the related record
271 162
     * @param array $link The primary-foreign key constraint. The keys of the array refer to the attributes of the
272 19
     * record associated with the `$class` model, while the values of the array refer to the corresponding attributes in
273
     * **this** AR class.
274
     *
275 162
     * @return ActiveQueryInterface The relational query object.
276 162
     *
277
     * @psalm-param class-string<ActiveRecordInterface> $class
278
     */
279
    public function hasMany(string $class, array $link): ActiveQueryInterface
280
    {
281
        return $this->createRelationQuery($class, $link, true);
282
    }
283
284
    /**
285
     * Declares a `has-one` relation.
286
     *
287
     * The declaration is returned in terms of a relational {@see ActiveQuery} instance through which the related record
288 103
     * can be queried and retrieved back.
289
     *
290 103
     * A `has-one` relation means that there is at most one related record matching the criteria set by this relation,
291
     * e.g., a customer has one country.
292
     *
293
     * For example, to declare the `country` relation for `Customer` class, we can write the following code in the
294
     * `Customer` class:
295
     *
296
     * ```php
297
     * public function getCountry()
298
     * {
299
     *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
300 14
     * }
301
     * ```
302 14
     *
303
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name in the related class
304
     * `Country`, while the 'country_id' value refers to an attribute name in the current AR class.
305
     *
306
     * Call methods declared in {@see ActiveQuery} to further customize the relation.
307
     *
308
     * @param string $class The class name of the related record.
309
     * @param array $link The primary-foreign key constraint. The keys of the array refer to the attributes of the
310
     * record associated with the `$class` model, while the values of the array refer to the corresponding attributes in
311
     * **this** AR class.
312 386
     *
313
     * @return ActiveQueryInterface The relational query object.
314 386
     *
315
     * @psalm-param class-string<ActiveRecordInterface> $class
316
     */
317
    public function hasOne(string $class, array $link): ActiveQueryInterface
318
    {
319
        return $this->createRelationQuery($class, $link, false);
320
    }
321
322
    /**
323
     * @psalm-param class-string<ActiveRecordInterface> $arClass
324
     */
325
    public function instantiateQuery(string $arClass): ActiveQueryInterface
326
    {
327
        return new ActiveQuery($arClass, $this->db, $this->arFactory);
328 116
    }
329
330 116
    /**
331
     * Returns a value indicating whether the named attribute has been changed.
332
     *
333
     * @param string $name The name of the attribute.
334
     * @param bool $identical Whether the comparison of new and old value is made for identical values using `===`,
335
     * defaults to `true`. Otherwise `==` is used for comparison.
336
     *
337
     * @return bool Whether the attribute has been changed.
338
     */
339
    public function isAttributeChanged(string $name, bool $identical = true): bool
340
    {
341
        if (isset($this->attributes[$name], $this->oldAttributes[$name])) {
342
            if ($identical) {
343
                return $this->attributes[$name] !== $this->oldAttributes[$name];
344
            }
345 154
346
            return $this->attributes[$name] !== $this->oldAttributes[$name];
347 154
        }
348
349 150
        return isset($this->attributes[$name]) || isset($this->oldAttributes[$name]);
350 150
    }
351
352 10
    public function isPrimaryKey(array $keys): bool
353
    {
354 150
        $pks = $this->primaryKey();
355
356 4
        return count($keys) === count($pks)
357
            && count(array_intersect($keys, $pks)) === count($pks);
358 150
    }
359
360
    public function isRelationPopulated(string $name): bool
361
    {
362
        return array_key_exists($name, $this->related);
363
    }
364
365 8
    public function link(string $name, ActiveRecordInterface $arClass, array $extraColumns = []): void
366
    {
367 8
        $viaClass = null;
368
        $viaTable = null;
369
        $relation = $this->getRelation($name);
370
        $via = $relation?->getVia();
371
372
        if ($via !== null) {
373
            if ($this->getIsNewRecord() || $arClass->getIsNewRecord()) {
374
                throw new InvalidCallException(
375
                    'Unable to link models: the models being linked cannot be newly created.'
376
                );
377
            }
378 137
379
            if (is_array($via)) {
380 137
                [$viaName, $viaRelation] = $via;
381 137
                /** @psalm-var ActiveQueryInterface $viaRelation */
382
                $viaClass = $viaRelation->getARInstance();
383
                // unset $viaName so that it can be reloaded to reflect the change.
384
                /** @psalm-var string $viaName */
385
                unset($this->related[$viaName]);
386
            }
387
388
            if ($via instanceof ActiveQueryInterface) {
389
                $viaRelation = $via;
390
                $from = $via->getFrom();
391
                /** @psalm-var string $viaTable */
392
                $viaTable = reset($from);
393
            }
394 24
395
            $columns = [];
396 24
397
            /** @psalm-var ActiveQueryInterface|null $viaRelation */
398
            $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...
399
400
            /**
401
             * @psalm-var string $a
402
             * @psalm-var string $b
403
             */
404
            foreach ($viaLink as $a => $b) {
405
                /** @psalm-var mixed */
406
                $columns[$a] = $this->$b;
407
            }
408
409 8
            $link = $relation?->getLink() ?? [];
410
411 8
            /**
412 4
             * @psalm-var string $a
413
             * @psalm-var string $b
414 4
             */
415
            foreach ($link as $a => $b) {
416 4
                /** @psalm-var mixed */
417
                $columns[$b] = $arClass->$a;
418
            }
419
420
            /**
421
             * @psalm-var string $k
422
             * @psalm-var mixed $v
423
             */
424
            foreach ($extraColumns as $k => $v) {
425
                /** @psalm-var mixed */
426 6
                $columns[$k] = $v;
427
            }
428 6
429 6
            if ($viaClass instanceof ActiveRecordInterface && is_array($via)) {
430
                /**
431
                 * @psalm-var string $column
432
                 * @psalm-var mixed $value
433
                 */
434
                foreach ($columns as $column => $value) {
435
                    $viaClass->$column = $value;
436
                }
437
438
                $viaClass->insert();
439
            } elseif (is_string($viaTable)) {
440 12
                $this->db->createCommand()->insert($viaTable, $columns)->execute();
441
            }
442 12
        } elseif ($relation instanceof ActiveQueryInterface) {
0 ignored issues
show
introduced by
$relation is always a sub-type of Yiisoft\ActiveRecord\ActiveQueryInterface.
Loading history...
443 8
            $link = $relation->getLink();
444 4
            $p1 = $arClass->isPrimaryKey(array_keys($link));
445
            $p2 = $this->isPrimaryKey(array_values($link));
446
447 4
            if ($p1 && $p2) {
448
                if ($this->getIsNewRecord() && $arClass->getIsNewRecord()) {
449
                    throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
450 4
                }
451
452
                if ($this->getIsNewRecord()) {
453
                    $this->bindModels(array_flip($link), $this, $arClass);
454
                } else {
455
                    $this->bindModels($link, $arClass, $this);
456
                }
457
            } elseif ($p1) {
458
                $this->bindModels(array_flip($link), $this, $arClass);
459
            } elseif ($p2) {
460
                $this->bindModels($link, $arClass, $this);
461
            } else {
462
                throw new InvalidCallException(
463 149
                    'Unable to link models: the link defining the relation does not involve any primary key.'
464
                );
465 149
            }
466 145
        }
467
468
        // update lazily loaded related objects
469 149
        if ($relation instanceof ActiveRecordInterface && !$relation->getMultiple()) {
470 149
            $this->related[$name] = $arClass;
471
        } elseif (isset($this->related[$name])) {
472 149
            $indexBy = $relation?->getIndexBy();
473 133
            if ($indexBy !== null) {
474 129
                if ($indexBy instanceof Closure) {
475 129
                    $index = $relation?->indexBy($arClass::class);
476
                } else {
477
                    $index = $arClass->$indexBy;
478
                }
479 45
480
                if ($index !== null) {
481 45
                    $this->related[$name][$index] = $arClass;
482 45
                }
483
            } else {
484 45
                $this->related[$name][] = $arClass;
485
            }
486
        }
487
    }
488
489 149
    /**
490
     * Marks an attribute dirty.
491
     *
492
     * This method may be called to force updating a record when calling {@see update()}, even if there is no change
493
     * being made to the record.
494
     *
495
     * @param string $name The attribute name.
496
     */
497
    public function markAttributeDirty(string $name): void
498
    {
499
        if ($this->oldAttributes !== null && $name !== '') {
500
            unset($this->oldAttributes[$name]);
501
        }
502
    }
503
504
    /**
505
     * Returns the name of the column that stores the lock version for implementing optimistic locking.
506
     *
507
     * Optimistic locking allows multiple users to access the same record for edits and avoids potential conflicts. In
508
     * case when a user attempts to save the record upon some staled data (because another user has modified the data),
509
     * a {@see StaleObjectException} exception will be thrown, and the update or deletion is skipped.
510
     *
511
     * Optimistic locking is only supported by {@see update()} and {@see delete()}.
512
     *
513
     * To use Optimistic locking:
514 141
     *
515
     * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
516 141
     *    Override this method to return the name of this column.
517 125
     * 2. In the Web form that collects the user input, add a hidden field that stores the lock version of the recording
518
     *    being updated.
519
     * 3. In the controller action that does the data updating, try to catch the {@see StaleObjectException} and
520 30
     *    implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
521
     *
522
     * @return string|null The column name that stores the lock version of a table row. If `null` is returned (default
523
     * implemented), optimistic locking will not be supported.
524
     */
525
    public function optimisticLock(): string|null
526
    {
527
        return null;
528
    }
529
530
    /**
531
     * Populates an active record object using a row of data from the database/storage.
532
     *
533
     * This is an internal method meant to be called to create active record objects after fetching data from the
534
     * database. It is mainly used by {@see ActiveQuery} to populate the query results into active records.
535
     *
536
     * @param array|object $row Attribute values (name => value).
537
     */
538
    public function populateRecord(array|object $row): void
539
    {
540
        foreach ($row as $name => $value) {
541
            $this->$name = $value;
542
            $this->oldAttributes[$name] = $value;
543
        }
544
545
        $this->related = [];
546
        $this->relationsDependencies = [];
547
    }
548
549
    public function populateRelation(string $name, array|ActiveRecordInterface|null $records): void
550
    {
551
        foreach ($this->relationsDependencies as &$relationNames) {
552
            unset($relationNames[$name]);
553
        }
554
555
        $this->related[$name] = $records;
556
    }
557
558 6
    /**
559
     * Repopulates this active record with the latest data.
560 6
     *
561
     * @return bool Whether the row still exists in the database. If `true`, the latest data will be populated to this
562
     * active record. Otherwise, this record will remain unchanged.
563
     */
564
    public function refresh(): bool
565
    {
566
        $record = $this->instantiateQuery(static::class)->findOne($this->getPrimaryKey(true));
567
568
        return $this->refreshInternal($record);
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 5
     * $customer->email = $email;
583
     * $customer->save();
584 5
     * ```
585
     *
586 5
     * @param array|null $attributeNames List of attribute names that need to be saved. Defaults to null, meaning all
587 5
     * attributes that are loaded from DB will be saved.
588 1
     *
589
     * @throws InvalidConfigException
590 5
     * @throws StaleObjectException
591 5
     * @throws Throwable
592
     *
593
     * @return bool Whether the saving succeeded (i.e. no validation errors occurred).
594
     */
595 5
    public function save(array $attributeNames = null): bool
596
    {
597 5
        if ($this->getIsNewRecord()) {
598 4
            return $this->insert($attributeNames);
599
        }
600
601 5
        $this->update($attributeNames);
602
603 5
        return true;
604 5
    }
605
606
    public function setAttribute(string $name, mixed $value): void
607 5
    {
608
        if ($this->hasAttribute($name)) {
609
            if (
610
                !empty($this->relationsDependencies[$name])
611
                && (!array_key_exists($name, $this->attributes) || $this->attributes[$name] !== $value)
612
            ) {
613
                $this->resetDependentRelations($name);
614
            }
615
            $this->attributes[$name] = $value;
616
        } else {
617
            throw new InvalidArgumentException(static::class . ' has no attribute named "' . $name . '".');
618
        }
619 40
    }
620
621 40
    /**
622
     * Sets the attribute values in a massive way.
623 40
     *
624 4
     * @param array $values Attribute values (name => value) to be assigned to the model.
625
     *
626
     * {@see attributes()}
627 40
     */
628 40
    public function setAttributes(array $values): void
629
    {
630 40
        $values = array_intersect_key($values, array_flip($this->attributes()));
631 4
632 4
        /** @psalm-var mixed $value */
633
        foreach ($values as $name => $value) {
634
            $this->$name = $value;
635
        }
636
    }
637
638
    /**
639 40
     * Sets the value indicating whether the record is new.
640
     *
641 40
     * @param bool $value whether the record is new and should be inserted when calling {@see save()}.
642 4
     *
643
     * @see getIsNewRecord()
644
     */
645 40
    public function setIsNewRecord(bool $value): void
646 4
    {
647
        $this->oldAttributes = $value ? null : $this->attributes;
648
    }
649 40
650
    /**
651 40
     * Sets the old value of the named attribute.
652 40
     *
653 40
     * @param string $name The attribute name.
654
     *
655
     * @throws InvalidArgumentException If the named attribute does not exist.
656 40
     *
657
     * {@see hasAttribute()}
658
     */
659
    public function setOldAttribute(string $name, mixed $value): void
660
    {
661
        if (isset($this->oldAttributes[$name]) || $this->hasAttribute($name)) {
662
            $this->oldAttributes[$name] = $value;
663
        } else {
664
            throw new InvalidArgumentException(static::class . ' has no attribute named "' . $name . '".');
665
        }
666
    }
667
668
    /**
669
     * Sets the old attribute values.
670
     *
671
     * All existing old attribute values will be discarded.
672
     *
673
     * @param array|null $values Old attribute values to be set. If set to `null` this record is considered to be
674
     * {@see isNewRecord|new}.
675
     */
676
    public function setOldAttributes(array $values = null): void
677
    {
678
        $this->oldAttributes = $values;
679
    }
680
681 9
    public function update(array $attributeNames = null): int
682
    {
683 9
        return $this->updateInternal($attributeNames);
684 9
    }
685 9
686 4
    public function updateAll(array $attributes, array|string $condition = [], array $params = []): int
687
    {
688 5
        $command = $this->db->createCommand();
689
690
        $command->update($this->getTableName(), $attributes, $condition, $params);
691 9
692
        return $command->execute();
693
    }
694 9
695
    public function updateAttributes(array $attributes): int
696
    {
697
        $attrs = [];
698
699
        foreach ($attributes as $name => $value) {
700
            if (is_int($name)) {
701
                $attrs[] = $value;
702
            } else {
703
                $this->setAttribute($name, $value);
704
                $attrs[] = $name;
705
            }
706
        }
707
708
        $values = $this->getDirtyAttributes($attrs);
709
710
        if (empty($values) || $this->getIsNewRecord()) {
711
            return 0;
712 2
        }
713
714
        $rows = $this->updateAll($values, $this->getOldPrimaryKey(true));
715
716
        $this->oldAttributes = array_merge($this->oldAttributes ?? [], $values);
717
718 2
        return $rows;
719 2
    }
720
721 2
    /**
722
     * Updates the whole table using the provided counter changes and conditions.
723
     *
724
     * For example, to increment all customers' age by 1,
725 2
     *
726
     * ```php
727 2
     * $customer = new Customer($db);
728
     * $customer->updateAllCounters(['age' => 1]);
729
     * ```
730
     *
731 2
     * Note that this method will not trigger any events.
732
     *
733 2
     * @param array $counters The counters to be updated (attribute name => increment value).
734
     * Use negative values if you want to decrement the counters.
735
     * @param array|string $condition The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer
736
     * to {@see Query::where()} on how to specify this parameter.
737
     * @param array $params The parameters (name => value) to be bound to the query.
738
     *
739
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
740
     *
741 153
     * @throws Exception
742
     * @throws InvalidConfigException
743 153
     * @throws Throwable
744
     *
745
     * @return int The number of rows updated.
746
     */
747
    public function updateAllCounters(array $counters, array|string $condition = '', array $params = []): int
748
    {
749
        $n = 0;
750
751
        /** @psalm-var array<string, int> $counters */
752
        foreach ($counters as $name => $value) {
753
            $counters[$name] = new Expression("[[$name]]+:bp$n", [":bp$n" => $value]);
754
            $n++;
755
        }
756
757
        $command = $this->db->createCommand();
758
        $command->update($this->getTableName(), $counters, $condition, $params);
759
760
        return $command->execute();
761
    }
762
763
    /**
764 4
     * Updates one or several counter columns for the current AR object.
765
     *
766
     * Note that this method differs from {@see updateAllCounters()} in that it only saves counters for the current AR
767 4
     * object.
768
     *
769 4
     * An example usage is as follows:
770
     *
771
     * ```php
772
     * $post = new Post($db);
773
     * $post->updateCounters(['view_count' => 1]);
774
     * ```
775
     *
776
     * @param array $counters The counters to be updated (attribute name => increment value), use negative values if you
777
     * want to decrement the counters.
778
     *
779
     * @psalm-param array<string, int> $counters
780
     *
781 32
     * @throws Exception
782
     * @throws NotSupportedException
783 32
     *
784 5
     * @return bool Whether the saving is successful.
785
     *
786
     * {@see updateAllCounters()}
787 32
     */
788 32
    public function updateCounters(array $counters): bool
789
    {
790
        if ($this->updateAllCounters($counters, $this->getOldPrimaryKey(true)) === 0) {
791 32
            return false;
792 32
        }
793 32
794
        foreach ($counters as $name => $value) {
795 32
            $value += $this->$name ?? 0;
796
            $this->$name = $value;
797
            $this->oldAttributes[$name] = $value;
798
        }
799
800
        return true;
801
    }
802
803
    public function unlink(string $name, ActiveRecordInterface $arClass, bool $delete = false): void
804
    {
805
        $viaClass = null;
806
        $viaTable = null;
807
        $relation = $this->getRelation($name);
808 2
        $viaRelation = $relation?->getVia();
809
810 2
        if ($viaRelation !== null) {
811 1
            if (is_array($viaRelation)) {
812
                [$viaName, $viaRelation] = $viaRelation;
813
                /** @psalm-var ActiveQueryInterface $viaRelation */
814 1
                $viaClass = $viaRelation->getARInstance();
815
                /** @psalm-var string $viaName */
816
                unset($this->related[$viaName]);
817
            }
818
819
            $columns = [];
820
            $nulls = [];
821
822
            if ($viaRelation instanceof ActiveQueryInterface) {
823
                $from = $viaRelation->getFrom();
824
                /** @psalm-var mixed $viaTable */
825
                $viaTable = reset($from);
826
827
                foreach ($viaRelation->getLink() as $a => $b) {
828
                    /** @psalm-var mixed */
829
                    $columns[$a] = $this->$b;
830 53
                }
831
832 53
                $link = $relation?->getLink() ?? [];
833
834 53
                foreach ($link as $a => $b) {
835 21
                    /** @psalm-var mixed */
836
                    $columns[$b] = $arClass->$a;
837
                }
838 32
839
                $nulls = array_fill_keys(array_keys($columns), null);
840 32
841 32
                if ($viaRelation->getOn() !== null) {
842
                    $columns = ['and', $columns, $viaRelation->getOn()];
843
                }
844 32
            }
845
846
            if ($viaClass instanceof ActiveRecordInterface) {
847
                if ($delete) {
848
                    $viaClass->deleteAll($columns);
849
                } else {
850
                    $viaClass->updateAll($nulls, $columns);
851
                }
852
            } elseif (is_string($viaTable)) {
853
                $command = $this->db->createCommand();
854
                if ($delete) {
855
                    $command->delete($viaTable, $columns)->execute();
856
                } else {
857
                    $command->update($viaTable, $nulls, $columns)->execute();
858
                }
859
            }
860
        } elseif ($relation instanceof ActiveQueryInterface) {
0 ignored issues
show
introduced by
$relation is always a sub-type of Yiisoft\ActiveRecord\ActiveQueryInterface.
Loading history...
861
            if ($this->isPrimaryKey($relation->getLink())) {
862
                if ($delete) {
863
                    $arClass->delete();
864
                } else {
865
                    foreach ($relation->getLink() as $a => $b) {
866
                        $arClass->$a = null;
867 60
                    }
868
                    $arClass->save();
869 60
                }
870
            } elseif ($arClass->isPrimaryKey(array_keys($relation->getLink()))) {
871 60
                if ($delete) {
872 1
                    $this->delete();
873 1
                } else {
874 1
                    foreach ($relation->getLink() as $a => $b) {
875
                        /** @psalm-var mixed $values */
876
                        $values = $this->$b;
877
                        /** relation via array valued attribute */
878 59
                        if (is_array($values)) {
879
                            if (($key = array_search($arClass->$a, $values, false)) !== false) {
880
                                unset($values[$key]);
881
                                $this->$b = array_values($values);
882 59
                            }
883
                        } else {
884 59
                            $this->$b = null;
885 59
                        }
886
                    }
887
888 59
                    $this->save();
889
                }
890
            } else {
891
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
892
            }
893
        }
894
895
        if ($relation instanceof ActiveQueryInterface && !$relation->getMultiple()) {
896
            unset($this->related[$name]);
897
        } elseif (isset($this->related[$name]) && is_array($this->related[$name])) {
898
            /** @psalm-var array<array-key, ActiveRecordInterface> $related */
899 445
            $related = $this->related[$name];
900
            foreach ($related as $a => $b) {
901 445
                if ($arClass->getPrimaryKey() === $b->getPrimaryKey()) {
902
                    unset($this->related[$name][$a]);
903 445
                }
904 445
            }
905 445
        }
906 8
    }
907 8
908
    /**
909
     * Destroys the relationship in current model.
910
     *
911 445
     * The active record with the foreign key of the relationship will be deleted if `$delete` is `true`. Otherwise, the
912 445
     * foreign key will be set `null` and the model will be saved without validation.
913 445
     *
914 445
     * Note that to destroy the relationship without removing records make sure your keys can be set to null.
915
     *
916 287
     * @param string $name The case sensitive name of the relationship, e.g. `orders` for a relation defined via
917
     * `getOrders()` method.
918 287
     * @param bool $delete Whether to delete the model that contains the foreign key.
919 31
     *
920
     * @throws Exception
921
     * @throws ReflectionException
922 256
     * @throws StaleObjectException
923
     * @throws Throwable
924
     */
925
    public function unlinkAll(string $name, bool $delete = false): void
926
    {
927
        $viaClass = null;
928
        $viaTable = null;
929
        $relation = $this->getRelation($name);
930
        $viaRelation = $relation?->getVia();
931
932
        if ($relation instanceof ActiveQueryInterface && $viaRelation !== null) {
933
            if (is_array($viaRelation)) {
934
                [$viaName, $viaRelation] = $viaRelation;
935
                /** @psalm-var ActiveQueryInterface $viaRelation */
936
                $viaClass = $viaRelation->getARInstance();
937
                /** @psalm-var string $viaName */
938
                unset($this->related[$viaName]);
939
            } else {
940
                $from = $viaRelation->getFrom();
941
                /** @psalm-var mixed $viaTable */
942
                $viaTable = reset($from);
943
            }
944
945
            $condition = [];
946
            $nulls = [];
947
948 9
            if ($viaRelation instanceof ActiveQueryInterface) {
949
                foreach ($viaRelation->getLink() as $a => $b) {
950 9
                    $nulls[$a] = null;
951
                    /** @psalm-var mixed */
952 9
                    $condition[$a] = $this->$b;
953 5
                }
954
955
                if (!empty($viaRelation->getWhere())) {
956
                    $condition = ['and', $condition, $viaRelation->getWhere()];
957
                }
958
959 5
                if (!empty($viaRelation->getOn())) {
960
                    $condition = ['and', $condition, $viaRelation->getOn()];
961 5
                }
962 5
            }
963
964 5
            if ($viaClass instanceof ActiveRecordInterface) {
965
                if ($delete) {
966
                    $viaClass->deleteAll($condition);
967
                } else {
968
                    $viaClass->updateAll($nulls, $condition);
969
                }
970
            } elseif (is_string($viaTable)) {
971 5
                $command = $this->db->createCommand();
972
                if ($delete) {
973 5
                    $command->delete($viaTable, $condition)->execute();
974 5
                } else {
975
                    $command->update($viaTable, $nulls, $condition)->execute();
976
                }
977 5
            }
978 5
        } elseif ($relation instanceof ActiveQueryInterface) {
979
            $relatedModel = $relation->getARInstance();
980
981 5
            $link = $relation->getLink();
982 5
            if (!$delete && count($link) === 1 && is_array($this->{$b = reset($link)})) {
983
                /** relation via array valued attribute */
984
                $this->$b = [];
985 5
                $this->save();
986 5
            } else {
987 5
                $nulls = [];
988
                $condition = [];
989
990 5
                foreach ($relation->getLink() as $a => $b) {
991
                    $nulls[$a] = null;
992
                    /** @psalm-var mixed */
993 5
                    $condition[$a] = $this->$b;
994
                }
995
996 9
                if (!empty($relation->getWhere())) {
997 9
                    $condition = ['and', $condition, $relation->getWhere()];
998
                }
999 9
1000
                if (!empty($relation->getOn())) {
1001
                    $condition = ['and', $condition, $relation->getOn()];
1002
                }
1003
1004
                if ($delete) {
1005
                    $relatedModel->deleteAll($condition);
1006
                } else {
1007
                    $relatedModel->updateAll($nulls, $condition);
1008
                }
1009 9
            }
1010 5
        }
1011 4
1012 4
        unset($this->related[$name]);
1013
    }
1014
1015
    /**
1016
     * Sets relation dependencies for a property.
1017
     *
1018
     * @param string $name property name.
1019
     * @param ActiveQueryInterface $relation relation instance.
1020
     * @param string|null $viaRelationName intermediate relation.
1021 9
     */
1022 5
    private function setRelationDependencies(
1023 9
        string $name,
1024 9
        ActiveQueryInterface $relation,
1025 4
        string $viaRelationName = null
1026
    ): void {
1027
        $via = $relation->getVia();
1028 4
1029
        if (empty($via)) {
1030 4
            foreach ($relation->getLink() as $attribute) {
1031
                $this->relationsDependencies[$attribute][$name] = $name;
1032 5
                if ($viaRelationName !== null) {
1033
                    $this->relationsDependencies[$attribute][] = $viaRelationName;
1034
                }
1035 9
            }
1036
        } elseif ($via instanceof ActiveQueryInterface) {
1037
            $this->setRelationDependencies($name, $via);
1038
        } else {
1039
            /**
1040
             * @psalm-var string|null $viaRelationName
1041
             * @psalm-var ActiveQueryInterface $viaQuery
1042
             */
1043
            [$viaRelationName, $viaQuery] = $via;
1044
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1045
        }
1046
    }
1047
1048
    /**
1049
     * Creates a query instance for `has-one` or `has-many` relation.
1050
     *
1051
     * @param string $arClass The class name of the related record.
1052
     * @param array $link The primary-foreign key constraint.
1053 5
     * @param bool $multiple Whether this query represents a relation to more than one record.
1054
     *
1055 5
     * @return ActiveQueryInterface The relational query object.
1056
     *
1057 5
     * @psalm-param class-string<ActiveRecordInterface> $arClass
1058 5
1059
     * {@see hasOne()}
1060 5
     * {@see hasMany()}
1061 5
     */
1062 5
    protected function createRelationQuery(string $arClass, array $link, bool $multiple): ActiveQueryInterface
1063
    {
1064 4
        return $this->instantiateQuery($arClass)->primaryModel($this)->link($link)->multiple($multiple);
1065 4
    }
1066 4
1067
    /**
1068
     * {@see delete()}
1069 5
     *
1070 5
     * @throws Exception
1071 5
     * @throws StaleObjectException
1072
     * @throws Throwable
1073
     *
1074 5
     * @return int The number of rows deleted.
1075 5
     */
1076
    protected function deleteInternal(): int
1077 5
    {
1078
        /**
1079 5
         * We do not check the return value of deleteAll() because it's possible the record is already deleted in
1080 5
         * the database and thus the method will return 0
1081
         */
1082
        $condition = $this->getOldPrimaryKey(true);
1083 5
        $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\Bas...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...
1084
1085 5
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
1086 5
            $condition[$lock] = $this->$lock;
1087
1088 5
            $result = $this->deleteAll($condition);
1089
1090
            if ($result === 0) {
1091
                throw new StaleObjectException('The object being deleted is outdated.');
1092 4
            }
1093 4
        } else {
1094
            $result = $this->deleteAll($condition);
1095
        }
1096 5
1097
        $this->setOldAttributes();
1098
1099
        return $result;
1100 5
    }
1101 5
1102 5
    /**
1103 5
     * Repopulates this active record with the latest data from a newly fetched instance.
1104 5
     *
1105
     * @param ActiveRecordInterface|array|null $record The record to take attributes from.
1106 5
     *
1107 5
     * @return bool Whether refresh was successful.
1108
     *
1109 5
     * {@see refresh()}
1110
     */
1111
    protected function refreshInternal(array|ActiveRecordInterface $record = null): bool
1112
    {
1113
        if ($record === null || is_array($record)) {
0 ignored issues
show
introduced by
The condition is_array($record) is always true.
Loading history...
1114
            return false;
1115
        }
1116
1117
        foreach ($this->attributes() as $name) {
1118
            $this->setAttribute($name, $record->getAttribute($name));
1119
        }
1120
1121
        $this->oldAttributes = $record->getOldAttributes();
1122
        $this->related = [];
1123
        $this->relationsDependencies = [];
1124
1125
        return true;
1126
    }
1127
1128
    /**
1129
     * {@see update()}
1130 5
     *
1131
     * @param array|null $attributes Attributes to update.
1132 5
     *
1133
     * @throws Exception
1134 5
     * @throws NotSupportedException
1135 5
     * @throws StaleObjectException
1136 5
     *
1137
     * @return int The number of rows affected.
1138
     */
1139
    protected function updateInternal(array $attributes = null): int
1140 5
    {
1141
        $values = $this->getDirtyAttributes($attributes);
1142
1143
        if (empty($values)) {
1144
            return 0;
1145
        }
1146
1147
        $condition = $this->getOldPrimaryKey(true);
1148
        $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\Bas...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...
1149
1150
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
1151
            $lockValue = $this->$lock;
1152
1153
            $condition[$lock] = $lockValue;
1154
            $values[$lock] = ++$lockValue;
1155
1156 22
            $rows = $this->updateAll($values, $condition);
1157
1158 22
            if ($rows === 0) {
1159
                throw new StaleObjectException('The object being updated is outdated.');
1160 22
            }
1161 8
1162
            $this->$lock = $lockValue;
1163 4
        } else {
1164 4
            $rows = $this->updateAll($values, $condition);
1165 4
        }
1166
1167 4
        $this->oldAttributes = array_merge($this->oldAttributes ?? [], $values);
1168 4
1169 4
        return $rows;
1170
    }
1171
1172 8
    private function bindModels(
1173 8
        array $link,
1174
        ActiveRecordInterface $foreignModel,
1175 8
        ActiveRecordInterface $primaryModel
1176 8
    ): void {
1177 8
        /** @psalm-var string[] $link */
1178
        foreach ($link as $fk => $pk) {
1179
            /** @psalm-var mixed $value */
1180 8
            $value = $primaryModel->$pk;
1181
1182
            if ($value === null) {
1183
                throw new InvalidCallException(
1184 8
                    'Unable to link active record: the primary key of ' . $primaryModel::class . ' is null.'
1185
                );
1186
            }
1187
1188 8
            /**
1189
             * relation via array valued attribute
1190 4
             *
1191 4
             * @psalm-suppress MixedArrayAssignment
1192
             */
1193 4
            if (is_array($foreignModel->getAttribute($fk))) {
1194
                /** @psalm-var mixed */
1195
                $foreignModel->{$fk}[] = $value;
1196
            } else {
1197 4
                $foreignModel->setAttribute($fk, $value);
1198 4
            }
1199 4
        }
1200
1201 8
        $foreignModel->save();
1202
    }
1203
1204
    /**
1205 14
     * Resets dependent related models checking if their links contain specific attribute.
1206
     *
1207 14
     * @param string $attribute The changed attribute name.
1208 14
     */
1209
    private function resetDependentRelations(string $attribute): void
1210
    {
1211
        foreach ($this->relationsDependencies[$attribute] as $relation) {
1212
            unset($this->related[$relation]);
1213 14
        }
1214 14
1215
        unset($this->relationsDependencies[$attribute]);
1216 14
    }
1217 14
1218 14
    public function getTableName(): string
1219
    {
1220
        if ($this->tableName === '') {
1221 14
            $this->tableName = '{{%' . DbStringHelper::pascalCaseToId(DbStringHelper::baseName(static::class)) . '}}';
1222 10
        }
1223
1224
        return $this->tableName;
1225 14
    }
1226
}
1227