Reputation: 22363
In a Controller, during serialization, using the Symfony Serializer, I need to dynamically add a property portal
to an object, depending on an outside $portal
value, which is a query argument.
$content = $response->getContent();
# Switching the complete class, just to set a property
$type = match ( $portal ) {
'portal_a' => FooBarContainsCustomPropA::class."[]",
'portal_b' => FooBarContainsCustomPropB::class."[]",
};
$my_object = $this->serializer->deserialize(
$response->getContent(),
$type,
'json',
[ UnwrappingDenormalizer::UNWRAP_PATH => '[data][someObjectList]' ]
);
In this scenario, I am using custom objects, extending a main class, to set the property (hard-coded). I am searching for a better solution as this way, I am forced to add one additional class per portal
/ case, which will get unmaintainable with possibly hundreds of user defined portals.
# This solution depends on someone manually adding classes
# when a user adds a portal:
class FooBar {
# various properties
}
class FooBarContainsCustomPropA extends FooBar {
public string $portal = 'Portal A';
}
class FooBarContainsCustomPropB extends FooBar {
public string $portal = 'Portal B';
}
Current output + the desired result:
{
"some": "prop",
"another": "property",
+ "portal": "Portal B"
}
Upvotes: 0
Views: 467