Bundle for deserialization of API Responses or any other json data
$ composer require visual-craft/deserializer-bundle
- 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],
];
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);
- Basic usage
<?php
$this->deserializerBuilderFactory
->create(SomeDataClass::class)
->getDeserializer()
->deserialize($request->getContent())
;
- Configuring object to populate
<?php
// Retrieve from storage
$objectToPopulate = $repository->find(1);
$this->deserializerBuilderFactory
->create(SomeDataClass::class)
->setObjectToPopulate($objectToPopulate)
->getDeserializer()
->deserialize($request->getContent())
;
- 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())
;
MIT