From b2219f7eec647137680186235a1c69998d246cb5 Mon Sep 17 00:00:00 2001 From: Tigrov Date: Sat, 16 Dec 2023 11:28:26 +0700 Subject: [PATCH] Add `BaseActiveRecord::setAttributeInternal()` method --- src/BaseActiveRecord.php | 23 ++++++++++++++++------- src/BaseActiveRecordTrait.php | 14 +++----------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/BaseActiveRecord.php b/src/BaseActiveRecord.php index bdbdd4d1d..5fb7974be 100644 --- a/src/BaseActiveRecord.php +++ b/src/BaseActiveRecord.php @@ -658,13 +658,7 @@ public function save(array $attributeNames = null): bool public function setAttribute(string $name, mixed $value): void { if ($this->hasAttribute($name)) { - if ( - !empty($this->relationsDependencies[$name]) - && (!array_key_exists($name, $this->attributes) || $this->attributes[$name] !== $value) - ) { - $this->resetDependentRelations($name); - } - $this->attributes[$name] = $value; + $this->setAttributeInternal($name, $value); } else { throw new InvalidArgumentException(static::class . ' has no attribute named "' . $name . '".'); } @@ -1281,4 +1275,19 @@ public function toArray(): array } return $data; } + + /** + * Sets the named attribute value without checking if the attribute exists. + */ + protected function setAttributeInternal(string $name, mixed $value): void + { + if ( + !empty($this->relationsDependencies[$name]) + && ($value === null || $value !== $this->attributes[$name] ?? null) + ) { + $this->resetDependentRelations($name); + } + + $this->attributes[$name] = $value; + } } diff --git a/src/BaseActiveRecordTrait.php b/src/BaseActiveRecordTrait.php index 18f77d485..9d917aabb 100644 --- a/src/BaseActiveRecordTrait.php +++ b/src/BaseActiveRecordTrait.php @@ -167,10 +167,7 @@ public function __isset(string $name): bool public function __unset(string $name): void { if ($this->hasAttribute($name)) { - unset($this->attributes[$name]); - if (!empty($this->relationsDependencies[$name])) { - $this->resetDependentRelations($name); - } + $this->setAttributeInternal($name, null); } elseif (array_key_exists($name, $this->related)) { unset($this->related[$name]); } @@ -189,13 +186,8 @@ public function __unset(string $name): void public function __set(string $name, mixed $value): void { if ($this->hasAttribute($name)) { - if ( - !empty($this->relationsDependencies[$name]) - && (!array_key_exists($name, $this->attributes) || $this->attributes[$name] !== $value) - ) { - $this->resetDependentRelations($name); - } - $this->attributes[$name] = $value; + $this->setAttributeInternal($name, $value); + return; } if (method_exists($this, 'get' . ucfirst($name))) {