Take the following DTO classes:
class UserDTO {
/**
* @param AddressDTO[] $addressBook
*/
public function __construct(
public string $name,
public int $age,
public ?AddressDTO $billingAddress,
public ?AddressDTO $shippingAddress,
public array $addressBook,
) {
}
}
class AddressDTO {
public function __construct(
public string $street,
public string $city,
) {
}
}
I'd like to serialize and deserialize them to/from JSON.
I'm using the following Serializer configuration:
$encoders = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [
new PhpDocExtractor(),
new ReflectionExtractor(),
]);
$normalizers = [
new ObjectNormalizer(null, null, null, $extractor),
new ArrayDenormalizer(),
];
$serializer = new Serializer($normalizers, $encoders);
But when serializing/deserializing this object:
$address = new AddressDTO('Rue Paradis', 'Marseille');
$user = new UserDTO('John', 25, $address, null, [$address]);
$jsonContent = $serializer->serialize($user, 'json');
dd($serializer->deserialize($jsonContent, UserDTO::class, 'json'));
I get the following result:
UserDTO^ {#54
+name: "John"
+age: 25
+billingAddress: AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
+shippingAddress: null
+addressBook: array:1 [
0 => array:2 [
"street" => "Rue Paradis"
"city" => "Marseille"
]
]
}
When I would expect:
UserDTO^ {#54
+name: "John"
+age: 25
+billingAddress: AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
+shippingAddress: null
+addressBook: array:1 [
0 => AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
]
}
As you can see, $addressBook
is deserialized as an array of array
, instead of an array of AddressDTO
. I expected the PhpDocExtractor
to read the @param AddressDTO[]
from the constructor, but this does not work.
It only works if I make $addressBook
a public property documented with @var
.
Is there a way to make it work with a simple @param
on the constructor?
(Non-)working-demo: https://phpsandbox.io/n/gentle-mountain-mmod-rnmqd
What I've read and tried:
- Extract types of constructor parameters from docblock comment
- symfony deserialize nested objects
- How can I deserialize an array of objects in Symfony Serializer?
None of the proposed solutions seem to work for me.