I would like to handle a single object property on serialization and deserialization with JMSSerializer. Suposing we have this class :
class Task {
const STATUS_PENDING = 0;
const STATUS_OVER = 1;
protected $status;
/* getter and setter */
public function getStatusLabel()
{
return ['pending', 'over'][$this->getStatus()];
}
public static function getStatusFromLabel($label)
{
return [
'pending' => self::STATUS_PENDING,
'over' => self::STATUS_OVER
][$label];
}
}
I would like to return instances of Task threw a REST API (using FOSRestBundle). The problem is that I don't want to return the raw value of the $status
attribute, but the "label" value.
Configuring my serialization like this :
Task:
exclusion_policy: ALL
properties:
status:
expose: true
type: string
The JMS Serializer considers the raw value which is 0 or 1, but I want to send 'pending' or 'over' in my serialized object (using getStatusLabel
). And do the reverse job on deserialization (using getStatusFromLabel
).
I thaught about a virtual_properties
but it works only in serilization direction.
I tried with a custom handler looking like this :
class TaskHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return [
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'Task',
'method' => 'serializeToArray',
]
];
}
public function serializeToArray(JsonSerializationVisitor $visitor, Task $task, array $type, Context $context)
{
$task->setStatus($task->getStatusLabel());
return $visitor->getNavigator()->accept($task, $type, $context);
}
But it obviously doesn't work !
How could I call my custom getters in both serilization and deserialization directions ?