Passed
Pull Request — master (#314)
by Sergei
03:56
created

BaseActiveRecord::setRelationDependencies()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5

Importance

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