bluepsyduck/jms-serializer-factory

A Laminas factory to initialize the JMS serializer through the config.

1.1.0 2021-12-14 17:43 UTC

This package is auto-updated.

Last update: 2024-04-14 23:14:36 UTC


README

GitHub release GitHub build Codecov

This library provides a Laminas-compatible factory to create JMS serializer instances from the config without the need to write an actual factory.

Usage

Install the package through composer with:

composer require bluepsyduck/jms-serializer-factory

The first step is to add the settings to your Laminas config. Use the ConfigKey interface to get the names of the config options. A full list of options can be found below.

<?php
// config/serializers.php

use BluePsyduck\JmsSerializerFactory\Constant\ConfigKey;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

return [
    'serializers' => [
        'my-fancy-serializer' => [
            ConfigKey::PROPERTY_NAMING_STRATEGY => IdenticalPropertyNamingStrategy::class,
            ConfigKey::HANDLERS => [
                MyFancyHandler::class,
            ],
            ConfigKey::METADATA_DIRS => [
                'My\Fancy\Namespace' => __DIR__ . '/../serializer',
            ],
            ConfigKey::CACHE_DIR => __DIR__ . '/../../data/cache',
        ],
    ],
];

The JMS Serializer Factory will request any dependencies from the container, so make sure to register all of them. If they do not have any dependencies themselves, use the InvokableFactory to register them.

<?php
// config/dependencies.php

use BluePsyduck\JmsSerializerFactory\JmsSerializerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

return [
    'dependencies' => [
        'factories' => [
            // Add the services used in the serializer config to the container.
            IdenticalPropertyNamingStrategy::class => InvokableFactory::class,
            MyFancyHandler::class => InvokableFactory::class,
            
            // Add the actual serializer instance to the container.
            'MyFancySerializer' => new JmsSerializerFactory('serializers', 'my-fancy-serializer'),
            // This will take the config for the serializer from $config['serializers']['my-fancy-serializer']
        ],
    ],
];

With this configuration, you now can get your serializer instance from the container:

<?php

/* @var \JMS\Serializer\SerializerInterface $myFancySerializer */
$myFancySerializer = $container->get('MyFancySerializer');

// Use it as usual.
$json = $myFancySerializer->serialize($data, 'json');

Alternatively, if the Laminas AutoWire Factory is set up, the Attribute UseJmsSerializer can be used to resolve a parameter of the constructor to the configuration of the serializer:

use BluePsyduck\JmsSerializerFactory\Attribute\UseJmsSerializer;
use JMS\Serializer\SerializerInterface;

class MyFancyClass {
    public function __construct(
        #[UseJmsSerializer('serializers', 'my-fancy-serializer')] // The keys to the configuration of the serializer.
        private SerializerInterface $serializer,
    ) {
    }
}

All config options

The following table shows the full list of config values supported by the factory. Constant refers to the name of the constant in the ConfigKey interface, and the SerializerBuilder method column refers to the method of the builder used for that config value. For further details, please check the method signatures and doc-blocks of the builder.

Constant Expected value SerializerBuilder method
ACCESSOR_STRATEGY container alias ->setAccessorStrategy()
EXPRESSION_EVALUATOR container alias ->setExpressionEvaluator()
TYPE_PARSER container alias ->setTypeParser()
ANNOTATION_READER container alias ->setAnnotationReader()
DEBUG bool ->setDebug()
CACHE_DIR string ->setCacheDir()
ADD_DEFAULT_HANDLERS true ->addDefaultHandlers()
HANDLERS array<container alias> ->configureHandlers()
ADD_DEFAULT_LISTENERS true ->addDefaultListeners()
LISTENERS array<container alias> ->configureListeners()
OBJECT_CONSTRUCTOR container alias ->setObjectConstructor()
PROPERTY_NAMING_STRATEGY container alias ->setPropertyNamingStrategy()
SERIALIZATION_VISITORS array<string, container alias> ->setSerializationVisitor()
DESERIALIZATION_VISITORS array<string, container alias> ->setDeserializationVisitor()
ADD_DEFAULT_SERIALIZATION_VISITORS true ->addDefaultSerializationVisitors()
ADD_DEFAULT_DESERIALIZATION_VISITORS true ->addDefaultDeserializationVisitors()
INCLUDE_INTERFACE_METADATA bool ->includeInterfaceMetadata()
METADATA_DIRS array<string, string> ->setMetadataDirs()
METADATA_DRIVER_FACTORY container alias ->setMetadataDriverFactory()
SERIALIZATION_CONTEXT_FACTORY container alias ->setSerializationContextFactory()
DESERIALIZATION_CONTEXT_FACTORY container alias ->setDeserializationContextFactory()
METADATA_CACHE container alias ->setMetadataCache()
DOC_BLOCK_TYPE_RESOLVER bool ->setDocBlockTypeResolver()
Notes:
  • The expected value container alias means that a string is expected, which is used in the container to retrieve an actual instance to set to the serializer builder. The actually needed type of the instance can be checked in the related method of the SerializerBuilder.
  • The serialization and deserialization visitors get added to the builder together with their format string. The config is expecting the format as key, and an alias to the visitor factory as value.
  • METADATA_DIRS expects the array key to be the namespace and the value to be the directory with the meta config files.
  • The factory does only support classes implementing the SubscribingHandlerInterface as handlers, and classes implementing the EventSubscriberInterface as listeners. It is not possible to use callables for these two cases.