Skip to content

Commit 332b48c

Browse files
committed
fix: Restore $_cast in toArray()
1 parent 43df169 commit 332b48c

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

system/Entity/Entity.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,8 @@ public function fill(?array $data = null)
193193
*/
194194
public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recursive = false): array
195195
{
196-
$this->_cast = $cast;
196+
$lastCastStatus = $this->_cast;
197+
$this->_cast = $cast;
197198

198199
$keys = array_filter(array_keys($this->attributes), static fn ($key): bool => ! str_starts_with($key, '_'));
199200

@@ -222,7 +223,7 @@ public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recu
222223
}
223224
}
224225

225-
$this->_cast = true;
226+
$this->_cast = $lastCastStatus;
226227

227228
return $return;
228229
}

tests/system/Entity/EntityTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,6 +1078,40 @@ public function testAsArraySwapped(): void
10781078
], $result);
10791079
}
10801080

1081+
public function testAsArrayRestoringCastStatus(): void
1082+
{
1083+
$entity = new class () extends Entity {
1084+
protected $attributes = [
1085+
'first' => null,
1086+
];
1087+
protected $original = [
1088+
'first' => null,
1089+
];
1090+
protected $casts = [
1091+
'first' => 'integer',
1092+
];
1093+
};
1094+
$entity->first = '2026 Year';
1095+
1096+
// Disabled casting properties, but we will allow casting in the method.
1097+
$entity->cast(false);
1098+
$beforeCast = $this->getPrivateProperty($entity, '_cast');
1099+
$result = $entity->toArray(true, true);
1100+
$afterCast = $this->getPrivateProperty($entity, '_cast');
1101+
1102+
$this->assertSame($result['first'], 2026);
1103+
$this->assertSame($beforeCast, $afterCast);
1104+
1105+
// Enabled casting properties, but we will disallow casting in the method.
1106+
$entity->cast(true);
1107+
$beforeCast = $this->getPrivateProperty($entity, '_cast');
1108+
$result = $entity->toArray(true, false);
1109+
$afterCast = $this->getPrivateProperty($entity, '_cast');
1110+
1111+
$this->assertSame($result['first'], '2026 Year');
1112+
$this->assertSame($beforeCast, $afterCast);
1113+
}
1114+
10811115
public function testDataMappingIssetSwapped(): void
10821116
{
10831117
$entity = $this->getSimpleSwappedEntity();

0 commit comments

Comments
 (0)