Context
By using the JMS serializer library, I need to serialize/unserialize data which are internally represented by php backed enums.
What's the problem
I found a solution by using the SubscribingHandlerInterface interface, but I would like to simplify the process, by removing (if possible) a boilerplate class which has to be created for each new enum.
Actual working code, to be simplified
- Example enum:
<?php
namespace App\Enum;
enum MyEnum: string
{
case Hello = 'hello';
case World = 'world';
}
- This abstract class is here to minimize redundant code for the final classes (the ones which I would like to "remove"):
<?php
namespace App\Serializer;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use LogicException;
abstract class AbstractEnumSerializer implements SubscribingHandlerInterface
{
public static function getEnumClass(): string
{
throw new LogicException("Please implement this");
}
public static function getSubscribingMethods(): array
{
return [
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json',
'type' => static::getEnumClass(),
'method' => 'deserializeFromJSON',
], [
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => static::getEnumClass(),
'method' => 'serializeToJSON',
],
];
}
public function deserializeFromJSON(JsonDeserializationVisitor $visitor, $data, array $type)
{
return static::getEnumClass()::tryFrom($data);
}
public function serializeToJSON(
SerializationVisitorInterface $visitor,
$enum,
array $type,
SerializationContext $context
): string
{
return $enum->value;
}
}
- Here is the class which I want to "remove", by preferring some kind of automatic generation/registration: it implements (de)serialization for the above example enum, but it's boilerplate code, needed for each new enum:
<?php
namespace App\Serializer;
use App\Enum\MyEnum;
class MyEnumSerializer extends AbstractEnumSerializer
{
public static function getEnumClass(): string
{
return MyEnum::class;
}
}
Question
Let's imagine that many php backed enums have to be (de)serialized; is it possible to avoid writing the MyEnumSerializer
class for each enum, by preferring some kind of automatic generation/registration?
The main goal is to keep it simple to add new backed enums, while automatically implementing JMS serialization/deserialization for them.