Skip to content

Latest commit

 

History

History
47 lines (39 loc) · 1.68 KB

File metadata and controls

47 lines (39 loc) · 1.68 KB

Payload serializer

If you use the Payload package, you can simplify the serialization of your specific commands.

use GpsLab\Component\Command\Command;
use GpsLab\Component\Payload\Payload;
use Symfony\Component\Serializer\Exception\UnsupportedException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class RenameArticleCommandSerializer implements NormalizerInterface, DenormalizerInterface
{
    public function supportsNormalization($data, $format = null): bool
    {
        return $data instanceof RenameArticleCommand;
    }

    public function normalize($object, $format = null, array $context = []): array
    {
        return [
            'type' => 'RenameArticle',
            'payload' => $object->payload(),
        ];
    }

    public function denormalize($data, $class, $format = null, array $context = []): RenameArticleCommand
    {
        if ($data['type'] !== 'RenameArticle' || $class !== RenameArticleCommand::class) {
            throw new UnsupportedException();
        }

        return new RenameArticleCommand($data['payload']);
    }

    public function supportsDenormalization($data, $type, $format = null): bool
    {
        return $type === Command::class && isset($data['type'], $data['payload']) && $data['type'] === 'RenameArticle';
    }
}

You can use universal serializers from Payload package and wrap it. Remember that the $type and $class for denormalization will always be equal to GpsLab\Component\Command\Command in PredisCommandQueue and PredisUniqueCommandQueue.