Skip to content

Commit d8dd06f

Browse files
fix(trait): improve snapshot handling in HasSnapshot by refining condition checks and ensuring null safety
1 parent 6446bde commit d8dd06f

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

src/Concerns/HasSnapshot.php

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,11 @@ public static function bootHasSnapshot()
4949
{
5050
self::saving(function ($model) {
5151
$snapshot = $model->snapshot;
52-
5352
$snapshotSourceChanged = false;
5453
$snapshotSourceForeignKey = $model->getSnapshotSourceForeignKey();
5554

56-
if( $model->getAttribute($snapshotSourceForeignKey)
57-
&& $snapshot
55+
if( $model->getAttribute($snapshotSourceForeignKey)
56+
&& $snapshot
5857
&& ((int)$snapshot->source_id != (int)$model->getAttribute($snapshotSourceForeignKey))
5958
){ // updating snapshot source
6059
$snapshotSourceChanged = true;
@@ -93,7 +92,6 @@ public static function bootHasSnapshot()
9392
}
9493
}
9594

96-
9795
});
9896

9997
static::saved(function ($model) {
@@ -230,7 +228,7 @@ public function prepareDataToSnapshot(): array
230228
$serializedData = null;
231229

232230
// if relationshipName exists on payload, get this value but not real relationship
233-
if ($valueOnModel) {
231+
if ($valueOnModel !== null) {
234232
if ($valueOnModel instanceof Collection) {
235233
$valueOnModel = $valueOnModel->toArray();
236234
}
@@ -268,11 +266,12 @@ public function prepareDataToSnapshot(): array
268266
: $source->{$relationshipName};
269267

270268

271-
272269
if (json_encode($valueOnModel) != json_encode($oldValue)) {
273270
if (is_array($valueOnModel)) {
274271
if (count($valueOnModel) > 0) {
275272
$serializedData = $source->{$relationshipName}()->getRelated()->whereIn('id', $valueOnModel)->get();
273+
} else {
274+
$serializedData = [];
276275
}
277276
} else {
278277
$serializedData = $source->{$relationshipName}()->getRelated()->where('id', $valueOnModel)->first();
@@ -285,7 +284,7 @@ public function prepareDataToSnapshot(): array
285284
$serializedData = $source->{$relationshipName};
286285
}
287286

288-
if ($serializedData) {
287+
if ($serializedData !== null) {
289288
$data[$relationshipName] = $serializedData;
290289
$serializedData = null;
291290
}
@@ -421,8 +420,8 @@ public function __get($key)
421420
$foreignKey = $this->getSnapshotSourceForeignKey();
422421

423422

424-
if($this->exists
425-
&& !in_array($key, $reservedAttributes)
423+
if($this->exists
424+
&& !in_array($key, $reservedAttributes)
426425
&& !in_array($key, ['snapshot', 'source', 'snapshotSource'])
427426
){
428427

0 commit comments

Comments
 (0)