4
4
How to Create your Custom Context Builder
5
5
=========================================
6
6
7
+ .. versionadded :: 6.1
8
+
9
+ Context builders were introduced in Symfony 6.1.
10
+
7
11
The :doc: `Serializer Component </components/serializer >` uses Normalizers
8
12
and Encoders to transform any data to any data-structure (e.g. JSON).
9
- That serialization process could be configured thanks to a
13
+ That serialization process can be configured thanks to a
10
14
:ref: `serialization context <serializer-context >`, which can be built thanks to
11
15
:ref: `context builders <component-serializer-context-builders >`.
12
16
13
- Each built-in normalizer/encoder has its related context builder.
14
- But, as an example, you may want to use custom context values
15
- for your :doc: `custom normalizers </serializer/custom_normalizer >`
16
- and create a custom context builder related to them.
17
+ Each built-in normalizer/encoder has its related context builder. However, you
18
+ may want to create a custom context builder for your
19
+ :doc: `custom normalizers </serializer/custom_normalizer >`.
17
20
18
- Creating a new context builder
21
+ Creating a new Context Builder
19
22
------------------------------
20
23
21
24
Let's imagine that you want to handle date denormalization differently if they
22
- are coming from a legacy system, by converting them to ``null `` if the serialized
25
+ are coming from a legacy system, by converting dates to ``null `` if the serialized
23
26
value is ``0000-00-00 ``. To do that you'll first have to create your normalizer::
24
27
25
28
// src/Serializer/ZeroDateTimeDenormalizer.php
@@ -51,14 +54,13 @@ value is ``0000-00-00``. To do that you'll first have to create your normalizer:
51
54
}
52
55
}
53
56
54
- You'll therefore be able to cast zero-ish dates to ``null `` during denormalization::
57
+ Now you can cast zero-ish dates to ``null `` during denormalization::
55
58
56
59
$legacyData = '{"updatedAt": "0000-00-00"}';
57
-
58
60
$serializer->deserialize($legacyData, MyModel::class, 'json', ['zero_datetime_to_null' => true]);
59
61
60
- Then, if you don't want other developers to have to remind the precise ``zero_date_to_null `` context key,
61
- you can create a dedicated context builder::
62
+ Now, to avoid having to remember about this specific ``zero_date_to_null ``
63
+ context key, you can create a dedicated context builder::
62
64
63
65
// src/Serializer/LegacyContextBuilder
64
66
namespace App\Serializer;
@@ -75,7 +77,7 @@ you can create a dedicated context builder::
75
77
}
76
78
}
77
79
78
- And finally use it to build the serialization context::
80
+ And finally, use it to build the serialization context::
79
81
80
82
$legacyData = '{"updatedAt": "0000-00-00"}';
81
83
0 commit comments