Passed
Push — master ( 594551...748657 )
by Wilmer
02:40
created

BaseActiveRecord::toArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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