From f5f437ebc0d3c61968de20b0f42bb6ba44266dd9 Mon Sep 17 00:00:00 2001 From: Alexander Strizhak Date: Fri, 19 Feb 2021 16:26:01 +0300 Subject: [PATCH] [DOCS] Add 'Deserialization Exclusion Strategy with Groups' topic to cookbook.rst --- doc/cookbook/exclusion_strategies.rst | 46 +++++++++++ .../Deserializer/BaseDeserializationTest.php | 77 +++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 tests/Deserializer/BaseDeserializationTest.php diff --git a/doc/cookbook/exclusion_strategies.rst b/doc/cookbook/exclusion_strategies.rst index 03fd95245..90dab33dd 100644 --- a/doc/cookbook/exclusion_strategies.rst +++ b/doc/cookbook/exclusion_strategies.rst @@ -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 diff --git a/tests/Deserializer/BaseDeserializationTest.php b/tests/Deserializer/BaseDeserializationTest.php new file mode 100644 index 000000000..b059f57dc --- /dev/null +++ b/tests/Deserializer/BaseDeserializationTest.php @@ -0,0 +1,77 @@ +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'], + [], + ]; + } +}