Skip to content

Commit 554d56d

Browse files
committed
Make multi level entity serialization more readable
1 parent bd9ad23 commit 554d56d

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/AbstractEntity.php

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,31 @@ public function getChangedColumns(): array
127127
*/
128128
public function jsonSerialize(): array
129129
{
130-
return $this->toArray();
130+
$schema = static::schema();
131+
if ($schema->hydrator) {
132+
return $schema->hydrator->toArray($this);
133+
}
134+
$result = [];
135+
foreach ($schema->columns as $columnName => $column) {
136+
if ($this->isNew() && !$column->isInitialized($this)) {
137+
continue;
138+
}
139+
$value = $this->{$columnName};
140+
if ($value === null && $column->isNullable) {
141+
$result[$columnName] = null;
142+
} else {
143+
if ($column instanceof Columns\EntityColumn) {
144+
$result[$columnName] = $value->jsonSerialize();
145+
} elseif ($column instanceof Columns\ArrayColumn) {
146+
$result[$columnName] = $value;
147+
} elseif ($column instanceof Columns\EntityListColumn) {
148+
$result[$columnName] = array_map(fn ($item) => $item->jsonSerialize(), $value);
149+
} else {
150+
$result[$columnName] = $column->uncast($value);
151+
}
152+
}
153+
}
154+
return $result;
131155
}
132156

133157
/**

0 commit comments

Comments
 (0)