Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
AutoMapper, and allow to pass default options to its reader and writer
- Add an `ignored_groups` context option, also mapped from the serializer `AbstractNormalizer::IGNORED_GROUPS`, to exclude the properties belonging to the given groups
- Add an `enable_default_groups` context option, also mapped from the serializer `AbstractNormalizer::ENABLE_DEFAULT_GROUPS`, to put the properties without groups in the `Default` and class short name groups
- Read the discriminator type from the object when several types of a `#[DiscriminatorMap]` map to its class
- Add a `discriminatorTypeFromObject` configuration option (`discriminator_type_from_object` in the bundle) to read the
discriminator type from the object when several types of a `#[DiscriminatorMap]` map to its class

### Deprecated
- Not setting the `discriminatorTypeFromObject` configuration option (`discriminator_type_from_object` in the bundle) is deprecated, it will default to `true` in 11.0

### Fixed
- Fix the deprecation triggered by the bundle on Symfony 8.2 about the event dispatcher service alias
Expand Down
7 changes: 5 additions & 2 deletions bench/src/Factory/MapperFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ final class MapperFactory
public static function autoMapper(): AutoMapperInterface
{
return self::$autoMappers['default'] ??= AutoMapper::create(
new Configuration(classPrefix: 'BenchDefault_'),
new Configuration(classPrefix: 'BenchDefault_', discriminatorTypeFromObject: false),
cacheDirectory: self::cacheDir('default'),
);
}
Expand All @@ -69,7 +69,7 @@ public static function autoMapper(): AutoMapperInterface
public static function autoMapperEval(): AutoMapperInterface
{
return self::$autoMappers['eval'] ??= AutoMapper::create(
new Configuration(classPrefix: 'BenchEval_'),
new Configuration(classPrefix: 'BenchEval_', discriminatorTypeFromObject: false),
);
}

Expand All @@ -82,6 +82,7 @@ public static function autoMapperNoConstructor(): AutoMapperInterface
new Configuration(
classPrefix: 'BenchNoCtor_',
constructorStrategy: ConstructorStrategy::NEVER,
discriminatorTypeFromObject: false,
),
cacheDirectory: self::cacheDir('no_constructor'),
);
Expand All @@ -98,6 +99,7 @@ public static function autoMapperNoAttributeChecking(): AutoMapperInterface
classPrefix: 'BenchNoAttr_',
attributeChecking: false,
mapPrivateProperties: false,
discriminatorTypeFromObject: false,
),
cacheDirectory: self::cacheDir('no_attribute'),
);
Expand All @@ -115,6 +117,7 @@ classPrefix: 'BenchNoCheck_',
attributeChecking: false,
mapPrivateProperties: false,
groupChecking: false,
discriminatorTypeFromObject: false,
),
cacheDirectory: self::cacheDir('no_checking'),
);
Expand Down
2 changes: 2 additions & 0 deletions docs/bundle/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ automapper:
auto_register: true
map_private_properties: true
allow_readonly_target_to_populate: false
discriminator_type_from_object: false
remove_default_properties: true
normalizer:
enabled: false
Expand Down Expand Up @@ -64,6 +65,7 @@ automapper:
* `map_private_properties` (default: `true`): If the mapper should map private properties;
* `allow_readonly_target_to_populate` (default: `false`): Will throw an exception if you use a readonly class as target
to populate if set to `false`.
* `discriminator_type_from_object` (default: `false`, will be `true` in 11.0): When several types of a discriminator map share the class of the source object, write the type held by the object instead of the first one. Not setting it is deprecated;
* `remove_default_properties` (default: `false`): Before 9.4 when renaming a property, the mapper would keep the old
property name in the target object which resulted in a duplicated property, this option will remove the default properties
from the target object when mapping and will always be true in next major version, you should set it to `true` to avoid
Expand Down
10 changes: 10 additions & 0 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ $configuration = new Configuration(
reloadStrategy: \AutoMapper\Loader\FileReloadStrategy::ON_CHANGE,
allowExtraProperties: false,
extractTypesFromGetter: false,
discriminatorTypeFromObject: false,
);
$autoMapper = AutoMapper::create(configuration: $configuration);
```
Expand Down Expand Up @@ -98,3 +99,12 @@ the source or the target implements the `ArrayAccess` interface.
When set to true, the generated mappers will used the return type of the getters to determine the type of the property
even when writing to the property. This can be useful with covariance when the getter return a more specific type than the
setter.

* `discriminatorTypeFromObject` (default: `false`, will be `true` in 11.0)

When several types of a serializer `#[DiscriminatorMap]` map to the class of the source object, the type held by the
discriminator property of the object is written, like the Symfony Serializer does since 8.2. The property is read by
reflection, whatever its visibility. When the value is not one of the types of the class, or when this option is
`false`, the first type of the class is written.

Not setting this option is deprecated: set it explicitly to `true` to opt in, or to `false` to keep the current behavior.
26 changes: 26 additions & 0 deletions docs/mapping/serializer.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,29 @@ abstract class Pet
public $name;
}
```

When several types map to the same class, the first one is written by default. Enable the `discriminatorTypeFromObject`
configuration option (`discriminator_type_from_object` in the bundle) to read the type from the discriminator property
of the object, like the Symfony Serializer does since 8.2: the property is read by reflection, whatever its visibility,
and the first type is still used when the value is not one of the types of the class.

```php
#[DiscriminatorMap(typeProperty: 'type', mapping: [
'cat' => Cat::class,
'kitten' => Cat::class,
'dog' => Dog::class,
])]
abstract class Pet
{
}

class Cat extends Pet
{
public function __construct(
public string $type = 'cat',
) {
}
}

$autoMapper->map(new Cat(type: 'kitten'), 'array'); // ['type' => 'kitten'] with the option enabled
```
13 changes: 13 additions & 0 deletions src/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@

final readonly class Configuration
{
/**
* When several types of a serializer discriminator map share the class of the source object, write the type held
* by the discriminator property of the object, instead of the first type of the class.
*/
public bool $discriminatorTypeFromObject;

public function __construct(
/**
* Class prefix used to prefix the class name of the generated mappers.
Expand Down Expand Up @@ -62,6 +68,13 @@ public function __construct(
* Make mapper group aware, configure this to false when there is no groups behavior in your mapping, saving a lot of times.
*/
public bool $groupChecking = true,
?bool $discriminatorTypeFromObject = null,
) {
if (null === $discriminatorTypeFromObject) {
trigger_deprecation('jolicode/automapper', '10.4', 'Not setting the "%s" configuration option is deprecated, it defaults to false and will default to true in 11.0. Set it explicitly.', 'discriminatorTypeFromObject');
$discriminatorTypeFromObject = false;
}

$this->discriminatorTypeFromObject = $discriminatorTypeFromObject;
}
}
23 changes: 14 additions & 9 deletions src/EventListener/Symfony/ClassDiscriminatorListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

namespace AutoMapper\EventListener\Symfony;

use AutoMapper\Configuration;
use AutoMapper\Event\GenerateMapperEvent;
use AutoMapper\Event\PropertyMetadataEvent;
use AutoMapper\Event\SourcePropertyMetadata;
use AutoMapper\Event\TargetPropertyMetadata;
use AutoMapper\Metadata\Discriminator;
use AutoMapper\Transformer\DiscriminatorTypeTransformer;
use AutoMapper\Transformer\FixedValueTransformer;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
Expand All @@ -20,6 +22,7 @@
{
public function __construct(
private ClassDiscriminatorResolverInterface $classDiscriminator,
private Configuration $configuration,
) {
}

Expand All @@ -29,14 +32,11 @@ public function __invoke(GenerateMapperEvent $event): void
$classDiscriminatorMappingTarget = $this->getMappingForClass($event->mapperMetadata->target);

if ($classDiscriminatorMappingSource) {
$sourceType = null;

foreach ($classDiscriminatorMappingSource->getTypesMapping() as $type => $class) {
if ($class === $event->mapperMetadata->source) {
$sourceType = $type;
break;
}
}
$sourceTypes = array_keys(array_filter(
$classDiscriminatorMappingSource->getTypesMapping(),
static fn (mixed $class) => $class === $event->mapperMetadata->source,
));
$sourceType = $sourceTypes[0] ?? null;

if (null === $sourceType) {
// It means the source is a parent class or interface of the mapped types
Expand All @@ -54,7 +54,12 @@ public function __invoke(GenerateMapperEvent $event): void
mapperMetadata: $event->mapperMetadata,
source: $sourceProperty,
target: $targetProperty,
transformer: $sourceType ? new FixedValueTransformer($sourceType) : null,
transformer: match (true) {
null === $sourceType => null,
// Several types map to the source class, the type carried by the object picks one of them
\count($sourceTypes) > 1 && $this->configuration->discriminatorTypeFromObject => new DiscriminatorTypeTransformer($property, array_map(strval(...), $sourceTypes), $sourceType),
default => new FixedValueTransformer($sourceType),
},
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/MetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ public static function create(
$eventDispatcher->addListener(PropertyMetadataEvent::class, new SerializerMaxDepthListener($classMetadataFactory));
$eventDispatcher->addListener(PropertyMetadataEvent::class, new SerializerGroupListener($classMetadataFactory));
$eventDispatcher->addListener(PropertyMetadataEvent::class, new SerializerIgnoreListener($classMetadataFactory));
$eventDispatcher->addListener(GenerateMapperEvent::class, new ClassDiscriminatorListener(new ClassDiscriminatorFromClassMetadata($classMetadataFactory)));
$eventDispatcher->addListener(GenerateMapperEvent::class, new ClassDiscriminatorListener(new ClassDiscriminatorFromClassMetadata($classMetadataFactory), $configuration));
} elseif (null !== $nameConverter) {
$eventDispatcher->addListener(PropertyMetadataEvent::class, new NameConverterListener($nameConverter));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
* auto_register: bool,
* map_private_properties: bool,
* allow_readonly_target_to_populate: bool,
* discriminator_type_from_object: bool|null,
* normalizer: array{
* enabled: bool,
* only_registered_mapping: bool,
Expand Down Expand Up @@ -96,6 +97,7 @@ public function load(array $configs, ContainerBuilder $container): void
->setArgument('$autoRegister', $config['auto_register'])
->setArgument('$mapPrivateProperties', $config['map_private_properties'])
->setArgument('$allowReadOnlyTargetToPopulate', $config['allow_readonly_target_to_populate'])
->setArgument('$discriminatorTypeFromObject', $config['discriminator_type_from_object'])
->setArgument('$reloadStrategy', $reloadStrategy = FileReloadStrategy::from($config['loader']['reload_strategy'] ?? (
$container->getParameter('kernel.debug') ? FileReloadStrategy::ALWAYS->value : FileReloadStrategy::NEVER->value
)))
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->booleanNode('auto_register')->defaultTrue()->end()
->booleanNode('map_private_properties')->defaultFalse()->end()
->booleanNode('allow_readonly_target_to_populate')->defaultFalse()->end()
->booleanNode('discriminator_type_from_object')->defaultNull()->end()
->arrayNode('normalizer')
->children()
->booleanNode('enabled')->defaultFalse()->end()
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Bundle/Resources/config/event_serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use AutoMapper\Event\GenerateMapperEvent;
use AutoMapper\Event\PropertyMetadataEvent;
use AutoMapper\Configuration;
use AutoMapper\EventListener\Symfony\ClassDiscriminatorListener;
use AutoMapper\EventListener\Symfony\NameConverterListener;
use AutoMapper\EventListener\Symfony\SerializerGroupListener;
Expand All @@ -29,7 +30,7 @@
->tag('kernel.event_listener', ['event' => PropertyMetadataEvent::class, 'priority' => -64])

->set(ClassDiscriminatorListener::class)
->args([service('automapper.mapping.class_discriminator_from_class_metadata')])
->args([service('automapper.mapping.class_discriminator_from_class_metadata'), service(Configuration::class)])
->tag('kernel.event_listener', ['event' => GenerateMapperEvent::class, 'priority' => -64])

->set('automapper.mapping.class_discriminator_from_class_metadata', ClassDiscriminatorFromClassMetadata::class)
Expand Down
100 changes: 100 additions & 0 deletions src/Transformer/DiscriminatorTypeTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Transformer;

use AutoMapper\Generator\UniqueVariableScope;
use AutoMapper\Metadata\PropertyMetadata;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;

use function AutoMapper\PhpParser\create_expr_array_item;
use function AutoMapper\PhpParser\create_scalar_int;

/**
* Writes the discriminator type of an object whose class is mapped by several types.
*
* The type carried by the object is used when it is one of the types of its class, otherwise the default type is used.
* Like the Symfony Serializer, the discriminator property is read by reflection, whatever its visibility.
*
* ```php
* try {
* $value = (new \ReflectionProperty($source, 'type'))->getValue($source);
* } catch (\ReflectionException|\Error) {
* $value = null;
* }
* $value = $value instanceof \BackedEnum ? $value->value : $value;
* (\is_string($value) || \is_int($value)) && \in_array((string) $value, ['type_a', 'type_b'], true) ? (string) $value : 'type_a'
* ```
*
* @internal
*/
final readonly class DiscriminatorTypeTransformer implements TransformerInterface, AllowNullValueTransformerInterface
{
/**
* @param list<string> $types
*/
public function __construct(
private string $property,
private array $types,
private string|int $defaultType,
) {
}

public function transform(Expr $input, Expr $target, PropertyMetadata $propertyMapping, UniqueVariableScope $uniqueVariableScope, Expr $source, ?Expr $existingValue = null): array
{
$value = new Expr\Variable($uniqueVariableScope->getUniqueName('discriminatorType'));

$statements = [
new Stmt\TryCatch(
[
new Stmt\Expression(new Expr\Assign($value, new Expr\MethodCall(
new Expr\New_(new Name\FullyQualified(\ReflectionProperty::class), [
new Arg($source),
new Arg(new Scalar\String_($this->property)),
]),
'getValue',
[new Arg($source)],
))),
],
[
new Stmt\Catch_(
[new Name\FullyQualified(\ReflectionException::class), new Name\FullyQualified(\Error::class)],
null,
[new Stmt\Expression(new Expr\Assign($value, new Expr\ConstFetch(new Name('null'))))],
),
],
),
new Stmt\Expression(new Expr\Assign($value, new Expr\Ternary(
new Expr\Instanceof_($value, new Name\FullyQualified(\BackedEnum::class)),
new Expr\PropertyFetch($value, 'value'),
$value,
))),
];

$output = new Expr\Ternary(
new Expr\BinaryOp\BooleanAnd(
new Expr\BinaryOp\BooleanOr(
new Expr\FuncCall(new Name('is_string'), [new Arg($value)]),
new Expr\FuncCall(new Name('is_int'), [new Arg($value)]),
),
new Expr\FuncCall(new Name('in_array'), [
new Arg(new Expr\Cast\String_($value)),
new Arg(new Expr\Array_(array_map(
static fn (string $type) => create_expr_array_item(new Scalar\String_($type)),
$this->types,
))),
new Arg(new Expr\ConstFetch(new Name('true'))),
]),
),
new Expr\Cast\String_($value),
\is_int($this->defaultType) ? create_scalar_int($this->defaultType) : new Scalar\String_($this->defaultType),
);

return [$output, $statements];
}
}
2 changes: 2 additions & 0 deletions tests/AutoMapperBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static function buildAutoMapper(
EventDispatcherInterface $eventDispatcher = new EventDispatcher(),
?ObjectManager $objectManager = null,
array $extraServices = [],
bool $discriminatorTypeFromObject = false,
): AutoMapper {
$skipCacheRemove = $_SERVER['SKIP_CACHE_REMOVE'] ?? false;

Expand All @@ -44,6 +45,7 @@ classPrefix: $classPrefix,
dateTimeFormat: $dateTimeFormat,
mapPrivateProperties: $mapPrivatePropertiesAndMethod,
allowReadOnlyTargetToPopulate: $allowReadOnlyTargetToPopulate,
discriminatorTypeFromObject: $discriminatorTypeFromObject,
);

return AutoMapper::create(
Expand Down
Loading