Skip to content

Metadata

Discriminator map

Polymorphism: the class of the data is selected by the value of a field.

Every option is shown in each metadata source: choose the tab of the source you use. When a source cannot express an option, its tab says what is used instead.

The map is declared on a base class or an interface.

use TypeLang\Mapper\Mapping\DiscriminatorMap;
#[DiscriminatorMap(field: 'type', map: [
'circle' => Circle::class,
'square' => Square::class,
])]
abstract class Shape {}
final class Circle extends Shape
{
public float $radius;
}
final class Square extends Shape
{
public float $side;
}
$mapper->denormalize(['type' => 'circle', 'radius' => 2], Shape::class);
// Circle { radius: 2.0 }

The otherwise type is used when the tag is missing or unknown.

use TypeLang\Mapper\Mapping\DiscriminatorMap;
#[DiscriminatorMap(field: 'type', map: [
'circle' => Circle::class,
], otherwise: UnknownShape::class)]
abstract class Shape {}
final class Circle extends Shape
{
public float $radius;
}
final class UnknownShape extends Shape {}
$mapper->denormalize(['type' => 'oval'], Shape::class); // UnknownShape {}

The tag of the class is written as the first field. A subclass that is not in the map, such as a proxy, takes the tag of its nearest parent in the map.

use TypeLang\Mapper\Mapping\DiscriminatorMap;
#[DiscriminatorMap(field: 'type', map: ['circle' => Circle::class])]
abstract class Shape {}
class Circle extends Shape
{
public float $radius = 1.5;
}
final class CircleProxy extends Circle {}
$mapper->normalize(new Circle(), Shape::class);
// ['type' => 'circle', 'radius' => 1.5]
$mapper->normalize(new CircleProxy(), Shape::class);
// ['type' => 'circle', 'radius' => 1.5]
$mapper->normalize(new Circle()); // ['radius' => 1.5]

A class with its own property named as the tag field writes that property, the tag is not added.