Skip to content

Commit 455bd0a

Browse files
[Serializer] Mention AbstractNormalizer::FILTER_BOOL
1 parent 7ac32e7 commit 455bd0a

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

components/serializer.rst

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -700,8 +700,11 @@ deserializing objects::
700700
$serialized = $serializer->serialize(new Person('Kévin'), 'json');
701701
// {"customer_name": "Kévin"}
702702

703-
Serializing Boolean Attributes
704-
------------------------------
703+
Handling Boolean Attributes And Values
704+
--------------------------------------
705+
706+
During Serialization
707+
~~~~~~~~~~~~~~~~~~~~
705708

706709
If you are using isser methods (methods prefixed by ``is``, like
707710
``App\Model\Person::isSportsperson()``), the Serializer component will
@@ -710,6 +713,34 @@ automatically detect and use it to serialize related attributes.
710713
The ``ObjectNormalizer`` also takes care of methods starting with ``has``, ``get``,
711714
and ``can``.
712715

716+
During Deserialization
717+
~~~~~~~~~~~~~~~~~~~~~~
718+
719+
PHP considers many different values as true or false. For example, the
720+
strings ``true``, ``1``, and ``yes`` are considered true, while
721+
``false``, ``0``, and ``no`` are considered false.
722+
723+
When deserializing, the Serializer component can take care of this
724+
automatically. This can be done by using the ``AbstractNormalizer::FILTER_BOOL``
725+
context option::
726+
727+
use Acme\Person;
728+
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
729+
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
730+
use Symfony\Component\Serializer\Serializer;
731+
732+
$normalizer = new ObjectNormalizer();
733+
$serializer = new Serializer([$normalizer]);
734+
735+
$data = $serializer->denormalize(['sportsperson' => 'yes'], Person::class, context: [AbstractNormalizer::FILTER_BOOL => true]);
736+
737+
This context makes the deserialization process behave like the
738+
:phpfunction:`filter_var` function with the ``FILTER_VALIDATE_BOOL`` flag.
739+
740+
.. versionadded:: 7.1
741+
742+
The ``AbstractNormalizer::FILTER_BOOL`` context option was introduced in Symfony 7.1.
743+
713744
Using Callbacks to Serialize Properties with Object Instances
714745
-------------------------------------------------------------
715746

0 commit comments

Comments
 (0)