Skip to content

Visual-Craft/deserializer-bundle

Repository files navigation

VisualCraft Deserializer Bundle

Build Status Build Status

Bundle for deserialization of API Responses or any other json data

Installation

$ composer require visual-craft/deserializer-bundle
  1. Enable in kernel (Symfony 3.4)
<?php

public function registerBundles()
{
    $bundles = [
        // ...
        new VisualCraft\DeserializerBundle\VisualCraftDeserializerBundle(),
        // ...
    ];

Or add to bundles.php (Symfony 4.0+)

<?php

return [
    VisualCraft\DeserializerBundle\VisualCraftDeserializerBundle::class => ['all' => true],
];

Usage

Firstly, inject DeserializerBuilderFactory to your Controller (or service):

<?php

use VisualCraft\DeserializerBundle\DeserializerBuilderFactory;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SomeController extends Controller
{
    // ...
    public function __construct(DeserializerBuilderFactory $deserializerBuilderFactory)
    {
        $this->deserializerBuilderFactory = $deserializerBuilderFactory;
    }
// ...

Or using Service Locator:

<?php

use VisualCraft\DeserializerBundle\DeserializerBuilderFactory;

// ...

$deserializerBuilderFactory = $this->get(DeserializerBuilderFactory::class);
  1. Basic usage
<?php

$this->deserializerBuilderFactory
    ->create(SomeDataClass::class)
    ->getDeserializer()
    ->deserialize($request->getContent())
;
  1. Configuring object to populate
<?php

// Retrieve from storage
$objectToPopulate = $repository->find(1);
$this->deserializerBuilderFactory
    ->create(SomeDataClass::class)
    ->setObjectToPopulate($objectToPopulate)
    ->getDeserializer()
    ->deserialize($request->getContent())
;
  1. Other features example:
<?php

$this->deserializerBuilderFactory
    ->create(SomeDataClass::class)
    ->setValidationGroups(['validation_group'])
    // or:
    ->setValidationGroups(function($object) {
        // if (something)
        return ['validation_group'];
        // endif
    })
    ->setDeserializationGroups(['deserialization_group'])
    ->getDeserializer()
    ->deserialize($request->getContent())
;

License

MIT