Fix serializing collection with intersection types

This commit is contained in:
2023-08-30 20:25:35 +02:00
parent 711cdc3481
commit bad3cdca09
2 changed files with 111 additions and 4 deletions

View File

@@ -96,7 +96,10 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
return 'docgen' === $format && (is_object($data) || null === $data);
}
private function getExpectedType(AttributeMetadata $attribute, ReflectionClass $reflection): string
/**
* @return string|array<string>
*/
private function getExpectedType(AttributeMetadata $attribute, ReflectionClass $reflection): string|array
{
$type = null;
@@ -147,14 +150,31 @@ class DocGenObjectNormalizer implements NormalizerAwareInterface, NormalizerInte
}
} while (null === $type && $reflection instanceof ReflectionClass);
if (null === $type ?? null) {
if ($type instanceof \ReflectionNamedType) {
return $type->getName();
}
if ($type instanceof \ReflectionIntersectionType) {
foreach (array_map(fn (\ReflectionNamedType $t) => $t->getName(), $type->getTypes()) as $classString) {
if (ReadableCollection::class === $classString) {
return ReadableCollection::class;
}
$class = new ReflectionClass($classString);
if ($class->implementsInterface(ReadableCollection::class)) {
return ReadableCollection::class;
}
}
throw new \LogicException(sprintf("The automatic normalization of intersection types is not supported, unless a %s is contained in the intersected types", ReadableCollection::class));
} elseif (null === $type ?? null) {
throw new \LogicException(sprintf(
'Could not determine the type for this attribute: %s. Add a return type to the method or property declaration',
$attribute->getName()
));
}
return $type->getName();
throw new \LogicException(sprintf("The automatic normalization of %s is not supported", $type::class));
}
/**