jojo1981/jms-serializer-handlers

Handlers for the JMS Serializer

6.0.0 2023-02-06 09:46 UTC

This package is auto-updated.

Last update: 2024-12-06 13:44:12 UTC


README

Build Status Coverage Status Latest Stable Version Total Downloads License

Author: Joost Nijhuis <jnijhuis81@gmail.com>

This library is an extension for the jms/serializer package and contains custom handlers which add support to work with some 3th party libraries. More information about JMS Serializer Handlers can be found here.

This library adds support for:

  • instances of Jojo1981\TypedCollection\Collection from the package jojo1981/typed-collection.

Installation

Library

git clone https://github.com/jojo1981/jms-serializer-handlers.git

Composer

Install PHP Composer

composer require jojo1981/jms-serializer-handlers

Usage

<?php

use JMS\Serializer\Accessor\DefaultAccessorStrategy;
use JMS\Serializer\Construction\UnserializeObjectConstructor;
use JMS\Serializer\Handler\HandlerRegistry;
use JMS\Serializer\Naming\CamelCaseNamingStrategy;
use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
use JMS\Serializer\SerializerBuilder;
use Jojo1981\JmsSerializerHandlers\TypedCollectionAccessorStrategyDecorator;
use Jojo1981\JmsSerializerHandlers\TypedCollectionObjectConstructorDecorator;
use Jojo1981\JmsSerializerHandlers\TypedCollectionSerializationHandler;
use Jojo1981\JmsSerializerHandlers\TypedSetSerializationHandler;
use Jojo1981\JmsSerializerHandlers\UnionSerializationHandler;

require 'vendor/autoload.php';

$propertyNamingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
$accessorStrategy = new TypedCollectionAccessorStrategyDecorator(new DefaultAccessorStrategy());

$serializer = (new SerializerBuilder())
    ->setDebug(true)
    ->setCacheDir(__DIR__ . '/var/cache/serializer')
    ->setAccessorStrategy($accessorStrategy)
    ->setPropertyNamingStrategy($propertyNamingStrategy)
    ->addDefaultHandlers()
    ->configureHandlers(static function (HandlerRegistry $handlerRegistry): void {
        $handlerRegistry->registerSubscribingHandler(new TypedCollectionSerializationHandler());
        $handlerRegistry->registerSubscribingHandler(new TypedSetSerializationHandler());
        $handlerRegistry->registerSubscribingHandler(new UnionSerializationHandler());
    })
    ->setObjectConstructor(new TypedCollectionObjectConstructorDecorator(new UnserializeObjectConstructor()))
    ->build();