0

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"
}
3
  • It's unclear what you want to accomplish, what's wrong with your solution, what are your constraints, and where $portal is coming from. Commented Mar 7, 2024 at 9:29
  • Why $portal can't be part of the payload directly? Or if not, can't you add portal to the payload after receiving it ($payload['portal'] = $portal) and deserialize that? Commented Mar 7, 2024 at 9:47
  • @yivi how would I get the data from the payload $request->getContent() into a DTO that gets queried and serialized? Commented Mar 7, 2024 at 14:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.