Skip to content

Commit

Permalink
Merge pull request #1287 from gam6itko/master
Browse files Browse the repository at this point in the history
[DOCS] Add 'Deserialization Exclusion Strategy with Groups' topic
  • Loading branch information
goetas authored Feb 21, 2021
2 parents c089420 + f5f437e commit c5100ac
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
46 changes: 46 additions & 0 deletions doc/cookbook/exclusion_strategies.rst
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,52 @@ This would result in the following json::
]
}

Deserialization Exclusion Strategy with Groups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use ``@Groups`` to cut off unwanted properties while deserialization.

.. code-block:: php
use JMS\Serializer\Annotation\Groups;
class GroupsObject
{
/**
* @Groups({"foo"})
*/
public $foo;
/**
* @Groups({"foo","bar"})
*/
public $foobar;
/**
* @Groups({"bar", "Default"})
*/
public $bar;
/**
* @Type("string")
*/
public $none;
}
.. code-block:: php
$data = [
'foo' => 'foo',
'foobar' => 'foobar',
'bar' => 'bar',
'none' => 'none',
];
$context = DeserializationContext::create()->setGroups(['foo']);
$object = $serializer->fromArray($data, GroupsObject::class, $context);
// $object->foo is 'foo'
// $object->foobar is 'foobar'
// $object->bar is null
// $object->none is null
Limiting serialization depth of some properties
-----------------------------------------------
You can limit the depth of what will be serialized in a property with the
Expand Down
77 changes: 77 additions & 0 deletions tests/Deserializer/BaseDeserializationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Deserializer;

use JMS\Serializer\DeserializationContext;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Tests\Fixtures\GroupsObject;
use PHPUnit\Framework\TestCase;

class BaseDeserializationTest extends TestCase
{
/**
* @dataProvider dataDeserializerGroupExclusion
*/
public function testDeserializerGroupExclusion(array $data, array $groups, array $expected): void
{
$serializer = SerializerBuilder::create()->build();
$context = DeserializationContext::create()->setGroups($groups);
$object = $serializer->fromArray($data, GroupsObject::class, $context);
self::assertSame($expected, $serializer->toArray($object));
}

public function dataDeserializerGroupExclusion(): iterable
{
$data = [
'foo' => 'foo',
'foobar' => 'foobar',
'bar' => 'bar',
'none' => 'none',
];

yield [
$data,
['Default'],
[
'bar' => 'bar',
'none' => 'none',
],
];

yield [
$data,
['foo'],
[
'foo' => 'foo',
'foobar' => 'foobar',
],
];

yield [
$data,
['bar'],
[
'foobar' => 'foobar',
'bar' => 'bar',
],
];

yield [
$data,
['foo', 'bar'],
[
'foo' => 'foo',
'foobar' => 'foobar',
'bar' => 'bar',
],
];

yield [
$data,
['you_shall_not_pass'],
[],
];
}
}

0 comments on commit c5100ac

Please sign in to comment.