I am using the JMS/Serialzier library .
I have setup an Event-Subscriber, which listens for Events::PRE_SERIALIZE
and I then convert all the object instances of an the class Price
having the property currency
and amount
into different currencies.
public function onPreSerialize(PreSerializeEvent $event)
{
$object = $event->getObject();
$class = get_class($object);
switch ($class) {
case Price::class:
return $this->currencyService->convertPrice($object);
}
}
Yet now, in my application I have the edge case that one price belonging to one container object EdgeCase
does not need to be converted at all:
use JMS\Serializer\Annotation\Type;
class EdgeCase {
/**
* @Type("Kopernikus\Price")
* @var Price
*/
private $price; // this one instance should not be handled by the event subscriber
}
but has to retain its original state. Yet I don't seem to be able to differentiate the origin of where my object is comming from.
I want to be able to configure which Price
objects should be converted and when.
As a quick and dirty solution I have just created a StaticPrice
class extending the Price
and changed the instantiaton of for the Price object for that edge case.
I have added a further check in the subscriber, so the relevant subscriber looks like:
switch ($class) {
case Price::class:
if ($object instanceof StaticPrice) {
break;
}
return $this->currencyService->convertPrice($object);
}
Yet it feels wrong to solve this in such a hard-coded way on the object level; and that I have to change the logic creating the price objects. But it works for now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.