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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Not setting the `unionTriesEachClass` configuration option (`union_tries_each_class` in the bundle) is deprecated, it will default to `true` in 11.0
- Find the target of the object mapper from the `#[Map(source: ...)]` attribute of the target class
(Symfony 8.1 reverse class map) in the bundle
- Pass the `#[Map]` attribute being applied to the ObjectMapper transforms implementing
`MappingAwareTransformCallableInterface` (Symfony 8.2)
- Add the `objectMapperNestedTransformReceivesSource` configuration option (bundle:
`object_mapper_nested_transform_receives_source`): the class-level ObjectMapper transform of a nested object receives
this object, the parent source and the parent target, like Symfony

### Deprecated
- Not setting the `objectMapperNestedTransformReceivesSource` configuration option is deprecated, it defaults to `false`
and 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
- Ignore the class-level `#[Map]` attributes declaring another target when the object mapper is given a target, like
Symfony, instead of applying their transform
- Inject the object mapper into the ObjectMapper transforms implementing `ObjectMapperAwareInterface`, so
`MapCollection` maps its items with the AutoMapper
- ObjectMapper property transforms now receive the target object instead of `null`, like Symfony

## [10.3.0] - 2026-09-16

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_', discriminatorTypeFromObject: false, unionTriesEachClass: false),
new Configuration(classPrefix: 'BenchDefault_', discriminatorTypeFromObject: false, unionTriesEachClass: false, objectMapperNestedTransformReceivesSource: 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_', discriminatorTypeFromObject: false, unionTriesEachClass: false),
new Configuration(classPrefix: 'BenchEval_', discriminatorTypeFromObject: false, unionTriesEachClass: false, objectMapperNestedTransformReceivesSource: false),
);
}

Expand All @@ -84,6 +84,7 @@ classPrefix: 'BenchNoCtor_',
constructorStrategy: ConstructorStrategy::NEVER,
discriminatorTypeFromObject: false,
unionTriesEachClass: false,
objectMapperNestedTransformReceivesSource: false,
),
cacheDirectory: self::cacheDir('no_constructor'),
);
Expand All @@ -102,6 +103,7 @@ classPrefix: 'BenchNoAttr_',
mapPrivateProperties: false,
discriminatorTypeFromObject: false,
unionTriesEachClass: false,
objectMapperNestedTransformReceivesSource: false,
),
cacheDirectory: self::cacheDir('no_attribute'),
);
Expand All @@ -121,6 +123,7 @@ classPrefix: 'BenchNoCheck_',
groupChecking: false,
discriminatorTypeFromObject: false,
unionTriesEachClass: false,
objectMapperNestedTransformReceivesSource: false,
),
cacheDirectory: self::cacheDir('no_checking'),
);
Expand Down
4 changes: 4 additions & 0 deletions docs/bundle/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ automapper:
serializer_attributes: true
api_platform: false
object_mapper: false
object_mapper_nested_transform_receives_source: true
name_converter: null
mapping:
paths:
Expand Down Expand Up @@ -97,6 +98,9 @@ indicate if we use the attribute of the symfony/serializer during the mapping, t
inject extra data (json ld) in the mappers when we map a Resource class to or from an array.
* `object_mapper` (default: `false`): A boolean which indicate if we use attributes from the symfony/object-mapper
component to configure the mapping, and use AutoMapper as an implementation for `ObjectMapperInterface`
* `object_mapper_nested_transform_receives_source` (default: `null`, which means `false` and is deprecated, will be `true`
in 11.0): Give to the class-level `transform` of the `#[Map]` attribute of a nested object this nested object, the parent
source and the parent target, like the Symfony Object Mapper, instead of a new target instance, the nested object and `null`;
* `doctrine` (default: `false`): A boolean which indicate if we want to use service from doctrine to extract more
information about the classes, and use doctrine to fetch existing objects. It will use by default the `doctrine.orm.entity_manager`
service if present, will then try to use the `doctrine_mongodb.odm.document_manager` service, or throw an exception if none of them
Expand Down
9 changes: 9 additions & 0 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ $configuration = new Configuration(
extractTypesFromGetter: false,
discriminatorTypeFromObject: false,
unionTriesEachClass: false,
objectMapperNestedTransformReceivesSource: true,
);
$autoMapper = AutoMapper::create(configuration: $configuration);
```
Expand Down Expand Up @@ -115,3 +116,11 @@ of the union is tried in order, and the first one whose constructor arguments ar
this option is `false`, the same class of the union is always used. See [Property Type](../mapping/type.md#union-of-classes).

Not setting this option is deprecated: set it explicitly to `true` to opt in, or to `false` to keep the current behavior.

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

Only used with the [Object Mapper integration](../bundle/object-mapper.md). When set to true, the class-level `transform`
of the `#[Map]` attribute of a nested object receives, like with the Symfony Object Mapper, this nested object as value,
the parent source and the parent target. Otherwise, it receives a new target instance, the nested object and `null`.
The transform of the root object always receives a new target instance, the source and `null`.
Not setting this option is deprecated, set it explicitly.
16 changes: 16 additions & 0 deletions src/AttributeReference/Reference.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,22 @@ public function __construct(
) {
}

/**
* AttributeInstance::get($attributeClassName, $reference, $index).
*/
public function getAttributeExpression(): Expr
{
return new Expr\StaticCall(
new Name\FullyQualified(AttributeInstance::class),
'get',
[
new Arg(new Scalar\String_($this->attributeClassName)),
new Arg($this->getReferenceExpression()),
new Arg(new Scalar\Int_($this->attributeIndex)),
]
);
}

public function getReferenceExpression(): Expr
{
if ($this->methodName) {
Expand Down
20 changes: 20 additions & 0 deletions src/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
*/
public bool $unionTriesEachClass;

/**
* @see self::__construct()
*/
public ?bool $objectMapperNestedTransformReceivesSource;

public function __construct(
/**
* Class prefix used to prefix the class name of the generated mappers.
Expand Down Expand Up @@ -76,6 +81,14 @@ public function __construct(
public bool $groupChecking = true,
?bool $discriminatorTypeFromObject = null,
?bool $unionTriesEachClass = null,
/*
* Like the Symfony ObjectMapper, give to the class-level ObjectMapper transform of a nested object this nested
* object as value, with the parent source and the parent target, instead of a new target instance, the nested
* object and null.
*
* Not setting it is deprecated, it defaults to false and will default to true in 11.0.
*/
?bool $objectMapperNestedTransformReceivesSource = 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');
Expand All @@ -90,5 +103,12 @@ public function __construct(
}

$this->unionTriesEachClass = $unionTriesEachClass;

if (null === $objectMapperNestedTransformReceivesSource) {
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.', 'objectMapperNestedTransformReceivesSource');
$objectMapperNestedTransformReceivesSource = false;
}

$this->objectMapperNestedTransformReceivesSource = $objectMapperNestedTransformReceivesSource;
}
}
2 changes: 1 addition & 1 deletion src/EventListener/ObjectMapper/MapListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected function getTransformerFromMapAttribute(string $class, Map $attribute,
$transformer = new CallableTransformer($transformerCallable, $fromSource, !$fromSource);
}
} elseif (\is_string($transformerCallable) && class_exists($transformerCallable) && is_subclass_of($transformerCallable, TransformCallableInterface::class)) {
$transformer = new ServiceLocatorTransformer($transformerCallable);
$transformer = new ServiceLocatorTransformer($transformerCallable, $reference);
} elseif (\is_string($transformerCallable)) {
try {
$expression = $this->expressionLanguage->compile($transformerCallable, ['value' => 'source', 'context']);
Expand Down
8 changes: 5 additions & 3 deletions src/EventListener/ObjectMapper/MapSourceListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,17 @@ public function __invoke(GenerateMapperEvent $event): void
}

$mapAttribute = null;
$mapAttributeReference = null;
$hasAnyMapAttribute = false;

foreach ($event->mapperMetadata->sourceReflectionClass->getAttributes(Map::class) as $sourceAttribute) {
foreach ($event->mapperMetadata->sourceReflectionClass->getAttributes(Map::class) as $mapAttributeIndex => $sourceAttribute) {
/** @var Map $attribute */
$attribute = $sourceAttribute->newInstance();
$hasAnyMapAttribute = true;

if (!$attribute->target || $attribute->target === $event->mapperMetadata->target || is_subclass_of($event->mapperMetadata->target, $attribute->target)) {
$mapAttribute = $attribute;
$mapAttributeReference = new Reference(Map::class, $mapAttributeIndex, $event->mapperMetadata->sourceReflectionClass->getName());
break;
}
}
Expand Down Expand Up @@ -115,11 +117,11 @@ public function __invoke(GenerateMapperEvent $event): void
$callableName = null;

if (\is_callable($mapAttribute->transform, false, $callableName)) {
$event->provider = new Provider(Provider::TYPE_CALLABLE, $callableName, true);
$event->provider = new Provider(Provider::TYPE_CALLABLE, $callableName, true, $mapAttributeReference, true);
}

if (\is_string($mapAttribute->transform) && $this->serviceLocator->has($mapAttribute->transform)) {
$event->provider = new Provider(Provider::TYPE_SERVICE_CALLABLE, $mapAttribute->transform, true);
$event->provider = new Provider(Provider::TYPE_SERVICE_CALLABLE, $mapAttribute->transform, true, $mapAttributeReference, true);
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/EventListener/ObjectMapper/MapTargetListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ public function __invoke(GenerateMapperEvent $event): void
}

$mapAttribute = null;
$mapAttributeReference = null;
$hasAnyMapAttribute = false;

foreach ($event->mapperMetadata->targetReflectionClass->getAttributes(Map::class) as $targetAttribute) {
foreach ($event->mapperMetadata->targetReflectionClass->getAttributes(Map::class) as $mapAttributeIndex => $targetAttribute) {
/** @var Map $attribute */
$attribute = $targetAttribute->newInstance();
$hasAnyMapAttribute = true;

if (!$attribute->source || $attribute->source === $event->mapperMetadata->source || is_subclass_of($event->mapperMetadata->source, $attribute->source)) {
$mapAttribute = $attribute;
$mapAttributeReference = new Reference(Map::class, $mapAttributeIndex, $event->mapperMetadata->targetReflectionClass->getName());
}
}

Expand Down Expand Up @@ -79,11 +81,11 @@ public function __invoke(GenerateMapperEvent $event): void
$callableName = null;

if (\is_callable($mapAttribute->transform, false, $callableName)) {
$event->provider = new Provider(Provider::TYPE_CALLABLE, $callableName, true);
$event->provider = new Provider(Provider::TYPE_CALLABLE, $callableName, true, $mapAttributeReference);
}

if (\is_string($mapAttribute->transform) && $this->serviceLocator->has($mapAttribute->transform)) {
$event->provider = new Provider(Provider::TYPE_SERVICE_CALLABLE, $mapAttribute->transform, true);
$event->provider = new Provider(Provider::TYPE_SERVICE_CALLABLE, $mapAttribute->transform, true, $mapAttributeReference);
}
}
}
Expand Down
87 changes: 77 additions & 10 deletions src/Generator/MapMethodStatementsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\VarExporter\LazyObjectInterface;

use function AutoMapper\PhpParser\create_expr_array_item;

/**
* @internal
*/
Expand All @@ -35,6 +37,7 @@ public function __construct(
DiscriminatorStatementsGenerator $discriminatorStatementsGeneratorTarget,
CachedReflectionStatementsGenerator $cachedReflectionStatementsGenerator,
ExpressionLanguage $expressionLanguage,
private bool $objectMapperNestedTransformReceivesSource = false,
) {
$propertyConditionGenerator = new PropertyConditionsGenerator($expressionLanguage);

Expand Down Expand Up @@ -114,9 +117,10 @@ public function getStatements(GeneratorMetadata $metadata, array $duplicatedStat
$statements = [...$statements, ...$this->initializeTargetFromProvider($metadata)];
}

$statements = [...$statements, ...$this->setObjectMapperParent($metadata)];
$statements = [...$statements, ...$this->createObjectStatementsGenerator->generate($metadata, $variableRegistry, $callDoConstruct)];

$addedDependenciesStatements = $this->handleDependencies($metadata);
$addedDependenciesStatements = [...$this->handleDependencies($metadata), ...$this->setObjectMapperParent($metadata)];

if (\count($duplicatedStatements) > 0 && \count($metadata->getPropertiesInConstructor())) {
/**
Expand Down Expand Up @@ -424,20 +428,41 @@ private function initializeTargetFromProvider(GeneratorMetadata $metadata): arra
$variableRegistry = $metadata->variableRegistry;

if ($metadata->provider->isFromObjectMapper) {
// When the provider is from the ObjectMapper, we call it with 3 arguments
/*
* $result ?? (new ReflectionClass($metadata->mapperMetadata->target))->newInstanceWithoutConstructor();
* Replicate the symfony/object-mapper calling convention with 3 arguments: the value is a new target object.
*
* transform($result ?? (new \ReflectionClass($target))->newInstanceWithoutConstructor(), $value, null)
*/
$newTarget = new Expr\BinaryOp\Coalesce($variableRegistry->getResult(), new Expr\MethodCall(
new Expr\New_(new Name\FullyQualified(\ReflectionClass::class), [
new Arg(new Scalar\String_($metadata->mapperMetadata->target)),
]),
'newInstanceWithoutConstructor'
));
$args = [
new Arg(new Expr\BinaryOp\Coalesce($variableRegistry->getResult(), new Expr\MethodCall(
new Expr\New_(new Name\FullyQualified(\ReflectionClass::class), [
new Arg(new Scalar\String_($metadata->mapperMetadata->target)),
]),
'newInstanceWithoutConstructor'
))),
new Arg($newTarget),
new Arg($variableRegistry->getSourceInput()),
new Arg(new Expr\ConstFetch(new Name('null'))),
];

if ($metadata->provider->isFromObjectMapperSource && $this->objectMapperNestedTransformReceivesSource) {
/*
* Like symfony/object-mapper, the transform declared on the class of a nested object receives this object,
* the parent source and the parent target, given by the parent mapper. A root object keeps a new target.
*
* transform(
* isset($context['object_mapper_parent']) ? $value : $newTarget,
* $context['object_mapper_parent'][0] ?? $value,
* $context['object_mapper_parent'][1] ?? null,
* )
*/
$parent = new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::OBJECT_MAPPER_PARENT));
$args = [
new Arg(new Expr\Ternary(new Expr\Isset_([$parent]), $variableRegistry->getSourceInput(), $newTarget)),
new Arg(new Expr\BinaryOp\Coalesce(new Expr\ArrayDimFetch($parent, new Scalar\Int_(0)), $variableRegistry->getSourceInput())),
new Arg(new Expr\BinaryOp\Coalesce(new Expr\ArrayDimFetch($parent, new Scalar\Int_(1)), new Expr\ConstFetch(new Name('null')))),
];
}
} else {
$args = [
new Arg(new Scalar\String_($metadata->mapperMetadata->target)),
Expand Down Expand Up @@ -471,9 +496,10 @@ private function initializeTargetFromProvider(GeneratorMetadata $metadata): arra
]);

if ($metadata->provider->isFromObjectMapper) {
// TransformCaller::call($this->serviceLocator->get($metadata->provider), ..., $context);
// TransformCaller::call($this->serviceLocator->get($metadata->provider), AttributeInstance::get(...), ..., $context);
$providerExpression = new Expr\StaticCall(new Name\FullyQualified(TransformCaller::class), 'call', [
new Arg($serviceExpression),
new Arg($metadata->provider->reference?->getAttributeExpression() ?? new Expr\ConstFetch(new Name('null'))),
...$args,
new Arg($variableRegistry->getContext()),
]);
Expand Down Expand Up @@ -580,4 +606,45 @@ private function handleDependencies(GeneratorMetadata $metadata): array

return $addedDependenciesStatements;
}

/**
* Gives the source and the target to the nested objects whose class declares an ObjectMapper transform.
*
* ```php
* $context['object_mapper_parent'] = [$value, $result];
* ```
*
* @return Stmt[]
*/
private function setObjectMapperParent(GeneratorMetadata $metadata): array
{
if (!$this->objectMapperNestedTransformReceivesSource) {
return [];
}

$hasNestedTransform = false;

foreach ($metadata->getDependencies() as $dependency) {
if ($dependency->metadata->provider?->isFromObjectMapperSource) {
$hasNestedTransform = true;
break;
}
}

if (!$hasNestedTransform) {
return [];
}

$variableRegistry = $metadata->variableRegistry;

return [
new Stmt\Expression(new Expr\Assign(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::OBJECT_MAPPER_PARENT)),
new Expr\Array_([
create_expr_array_item($variableRegistry->getSourceInput()),
create_expr_array_item(new Expr\BinaryOp\Coalesce($variableRegistry->getResult(), new Expr\ConstFetch(new Name('null')))),
]),
)),
];
}
}
Loading