Skip to content

Commit c125384

Browse files
committed
Allow null for composed structs when all attributes are null
1 parent f09949e commit c125384

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/Casts/ComposedStructCast.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace ProAI\Struct\Casts;
44

55
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6+
use Illuminate\Support\Str;
67
use ProAI\Struct\Struct;
78
use InvalidArgumentException;
89

@@ -40,11 +41,16 @@ public function get($model, $key, $value, $attributes)
4041
$properties = [];
4142

4243
foreach ($attributes as $name => $attribute) {
43-
if (! Str::startsWith($name.'_')) {
44+
if (is_null($attribute) || ! Str::startsWith($name, $key.'_')) {
4445
continue;
4546
}
4647

47-
$properties[Str::after($name.'_')] = $attribute;
48+
$properties[Str::after($name, $key.'_')] = $attribute;
49+
}
50+
51+
// Assume that result is null when all properties are null.
52+
if (count($properties) === 0) {
53+
return null;
4854
}
4955

5056
$class = $this->class;
@@ -63,6 +69,10 @@ public function get($model, $key, $value, $attributes)
6369
*/
6470
public function set($model, $key, $value, $attributes)
6571
{
72+
if (is_null($value)) {
73+
return null;
74+
}
75+
6676
if (! $value instanceof Struct) {
6777
throw new InvalidArgumentException('The given value is not a struct instance, "'.get_class($value).'" given.');
6878
}

0 commit comments

Comments
 (0)