Skip to content

Commit 0adecb5

Browse files
committed
Fix null values for composed structs
1 parent a7df8f0 commit 0adecb5

File tree

2 files changed

+30
-12
lines changed

2 files changed

+30
-12
lines changed

src/Casts/ComposedStructCast.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -69,18 +69,18 @@ public function get($model, $key, $value, $attributes)
6969
*/
7070
public function set($model, $key, $value, $attributes)
7171
{
72+
$class = $this->class;
73+
7274
if (is_null($value)) {
73-
return null;
74-
}
75+
$value = array_fill_keys($class::getPropertyNames(), null);
76+
} else {
77+
if (! $value instanceof Struct) {
78+
throw new InvalidArgumentException('The given value is not a struct instance, "'.get_class($value).'" given.');
79+
}
7580

76-
if (! $value instanceof Struct) {
77-
throw new InvalidArgumentException('The given value is not a struct instance, "'.get_class($value).'" given.');
81+
$value = $class::serializeDatabase($value);
7882
}
7983

80-
$class = $this->class;
81-
82-
$value = $class::serializeDatabase($value);
83-
8484
return $this->composeProperties($key, $value);
8585
}
8686

src/Struct.php

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ abstract class Struct implements Arrayable, JsonSerializable, Castable
3030
*/
3131
public function __construct(array $properties = [])
3232
{
33-
$reflections = $this->getReflectionProperties();
33+
$reflections = static::getReflectionProperties();
3434

3535
foreach ($reflections as $reflection) {
3636
$name = $reflection->getName();
@@ -89,20 +89,38 @@ protected function buildInstance($class, $value)
8989
return new $class($value);
9090
}
9191

92+
/**
93+
* Get the property names.
94+
*
95+
* @return array
96+
*/
97+
public static function getPropertyNames()
98+
{
99+
$reflections = static::getReflectionProperties();
100+
101+
$result = [];
102+
103+
foreach($reflections as $reflection) {
104+
$name = $reflection->getName();
105+
$result[] = $name;
106+
}
107+
108+
return $result;
109+
}
110+
92111
/**
93112
* Get the properties.
94113
*
95114
* @return array
96115
*/
97116
public function getProperties()
98117
{
99-
$reflections = $this->getReflectionProperties();
118+
$reflections = static::getReflectionProperties();
100119

101120
$result = [];
102121

103122
foreach($reflections as $reflection) {
104123
$name = $reflection->getName();
105-
106124
$result[$name] = $this->{$name};
107125
}
108126

@@ -126,7 +144,7 @@ public function toArray()
126144
*
127145
* @return \ReflectionProperty[]
128146
*/
129-
protected function getReflectionProperties()
147+
protected static function getReflectionProperties()
130148
{
131149
if (isset(static::$cache[static::class])) {
132150
return static::$cache[static::class];

0 commit comments

Comments
 (0)