Skip to content

Commit

Permalink
Handle serializing a null flattened object.
Browse files Browse the repository at this point in the history
  • Loading branch information
Crell committed Aug 2, 2024
1 parent bbb2f42 commit 16a80b6
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/PropertyHandler/ObjectExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,30 @@ protected function flattenValue(Dict $dict, Field $field, callable $propReader,
}

if ($field->typeCategory === TypeCategory::Object) {
// This whole mess is to keep the code below nullsafe.
// If we want to serialize a null but flattened object, we
// need to be aware of the flatten prefix it would have used.
// If there's a single property on the child object, we can use
// it to form the resulting field name that will be null.
// If there's several, we skip it and just use the flattenPrefix
// of the field itself, because that's all we can reasonably do.
if ($value === null) {
return $dict;
if ($field->flattenPrefix) {
$properties = $serializer->propertiesFor($field->phpType);

Check failure on line 100 in src/PropertyHandler/ObjectExporter.php

View workflow job for this annotation

GitHub Actions / PHPStan checks on 8.1

Parameter #1 $class of method Crell\Serde\Serializer::propertiesFor() expects class-string, string given.

Check failure on line 100 in src/PropertyHandler/ObjectExporter.php

View workflow job for this annotation

GitHub Actions / PHPStan checks on 8.2

Parameter #1 $class of method Crell\Serde\Serializer::propertiesFor() expects class-string, string given.

Check failure on line 100 in src/PropertyHandler/ObjectExporter.php

View workflow job for this annotation

GitHub Actions / PHPStan checks on 8.3

Parameter #1 $class of method Crell\Serde\Serializer::propertiesFor() expects class-string, string given.
if (count($properties) === 1) {
$prop = reset($properties);
/** @var Field $newField */
$newField = $field->with(
serializedName: $field->flattenPrefix . $prop->serializedName,
flattenPrefix: $field->flattenPrefix . $prop->flattenPrefix
);
return $dict->add(new CollectionItem(field: $newField, value: null));
} else {
return $dict->add(new CollectionItem(field: $field, value: null));
}
} else {
return $dict->add(new CollectionItem(field: $field, value: null));
}
}
$subPropReader = (fn (string $prop): mixed
=> array_key_exists($prop, get_object_vars($this)) ? $this->$prop : DeformatterResult::Missing)->bindTo($value, $value);
Expand Down

0 comments on commit 16a80b6

Please sign in to comment.