Skip to content

Commit 7fa3daa

Browse files
committed
feature #19723 [Serializer] Mention AbstractNormalizer::FILTER_BOOL (alexandre-daubois)
This PR was merged into the 7.1 branch. Discussion ---------- [Serializer] Mention `AbstractNormalizer::FILTER_BOOL` Fix #19682 Commits ------- dc57552 [Serializer] Mention `AbstractNormalizer::FILTER_BOOL`
2 parents 149d21a + dc57552 commit 7fa3daa

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

components/serializer.rst

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

703-
Serializing Boolean Attributes
704-
------------------------------
703+
.. _serializing-boolean-attributes:
704+
705+
Handling Boolean Attributes And Values
706+
--------------------------------------
707+
708+
During Serialization
709+
~~~~~~~~~~~~~~~~~~~~
705710

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

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

0 commit comments

Comments
 (0)