Skip to content

Commit dbd19ba

Browse files
committed
add docs for UnionDiscriminator
1 parent 34439ca commit dbd19ba

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

doc/reference/annotations.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ JMS serializer now supports PHP 8 attributes, with a few caveats:
99
- There is an edge case when setting this exact serialization group ``#[Groups(['value' => 'any value here'])]``.
1010
(when there is only one item in th serialization groups array and has as key ``value`` the attribute will not work as expected,
1111
please use the alternative syntax ``#[Groups(groups: ['value' => 'any value here'])]`` that works with no issues),
12+
- Some support for unions exists. For unions of primitive types, the system will try to resolve them automatically. For
13+
classes that contain union attributes, the ``#[UnionDiscriminator]`` attribute must be used to specify the type of the union.
1214

1315
Converting your annotations to attributes
1416
-----------------------------------------
@@ -384,6 +386,31 @@ to the least super type:
384386
385387
`groups` is optional and is used as exclusion policy.
386388
389+
#[UnionDiscriminator]
390+
391+
This attribute allows deserialization of unions. The ``#[UnionDiscriminator]`` attribute has to be applied
392+
to an attribute that can be one of many types.
393+
394+
.. code-block :: php
395+
396+
class Vehicle {
397+
#[UnionDiscriminator(field: 'typeDiscriminator')]
398+
private Manual|Automatic $transmission;
399+
}
400+
401+
In the case of this example, both Manual and Automatic should contain a string attribute named `typeDiscriminator`. If the `typeDiscriminator` field
402+
will always contain the fully qualified clasname, then the appropriate type will be selected for deserialization.
403+
404+
If, however, the field contains a string that is not the fully qualified classname, then the `map` option can be used to map the
405+
string to the appropriate class.
406+
407+
.. code-block :: php
408+
409+
class Vehicle {
410+
#[UnionDiscriminator(field: 'type', map: ['manual' => 'FullyQualified/Path/Manual', 'automatic' => 'FullyQualified/Path/Automatic'])]
411+
private Manual|Automatic $transmission;
412+
}
413+
387414
#[Type]
388415
~~~~~~~
389416
This attribute can be defined on a property to specify the type of that property.

0 commit comments

Comments
 (0)