Skip to content

Commit 828766e

Browse files
committed
Don't cast empty values (null or '') to value objects. Instead, return null.
1 parent 3602f61 commit 828766e

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/CastsValueObjects.php

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ public function getAttribute($key)
2323
// Allow other mutators and such to do their work first.
2424
$value = parent::getAttribute($key);
2525

26+
// Don't cast empty $value.
27+
if ($value === null || $value === '') {
28+
return null;
29+
}
30+
2631
// Cache the instantiated value for future access.
2732
// This allows tests such as ($model->casted === $model->casted) to be true.
2833
if (!$this->isValueObjectCached($key)) {

tests/CastsValueObjectTest.php

+16
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,20 @@ public function testModelToJsonWithValueObjects()
123123
$this->assertJson($json);
124124
$this->assertJsonStringEqualsJsonString(json_encode(['email' => $email]), $json);
125125
}
126+
127+
public function testNullValuesDontGetCast()
128+
{
129+
$user = new UserModel();
130+
131+
$this->assertNull($user->email);
132+
}
133+
134+
public function testEmptyStringValuesDontGetCast()
135+
{
136+
$user = new UserModel();
137+
138+
$user->setInternalAttributes(['email' => '']);
139+
140+
$this->assertNull($user->email);
141+
}
126142
}

0 commit comments

Comments
 (0)