Skip to content

Feature: Doctrine Provider #253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ tools/phpstan/cache/
cache/
site/
.build/
.castor*
.castor*
tests/Doctrine/db.sqlite
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
},
"require-dev": {
"api-platform/core": "^3.0.4 || ^4",
"doctrine/annotations": "~1.0",
"doctrine/annotations": "^2.0",
"doctrine/doctrine-bundle": "^2.15",
"doctrine/collections": "^2.2",
"doctrine/inflector": "^2.0",
"doctrine/orm": "^3.3",
Copy link
Collaborator

@nikophil nikophil Aug 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so this feature won't be tested with orm 2 (there are still a lot of them in the wild) ?

"matthiasnoback/symfony-dependency-injection-test": "^5.1",
"moneyphp/money": "^3.3.2",
"phpunit/phpunit": "^9.0",
Expand Down
10 changes: 10 additions & 0 deletions src/AutoMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
use AutoMapper\Loader\FileLoader;
use AutoMapper\Metadata\MetadataFactory;
use AutoMapper\Metadata\MetadataRegistry;
use AutoMapper\Provider\Doctrine\DoctrineProvider;
use AutoMapper\Provider\ProviderInterface;
use AutoMapper\Provider\ProviderRegistry;
use AutoMapper\Symfony\ExpressionLanguageProvider;
use AutoMapper\Transformer\PropertyTransformer\PropertyTransformerInterface;
use AutoMapper\Transformer\PropertyTransformer\PropertyTransformerRegistry;
use AutoMapper\Transformer\TransformerFactoryInterface;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
Expand Down Expand Up @@ -148,6 +150,7 @@ public static function create(
EventDispatcherInterface $eventDispatcher = new EventDispatcher(),
iterable $providers = [],
bool $removeDefaultProperties = false,
?EntityManagerInterface $entityManager = null,
): AutoMapperInterface {
if (\count($transformerFactories) > 0) {
trigger_deprecation('jolicode/automapper', '9.0', 'The "$transformerFactories" property will be removed in version 10.0, AST transformer factories must be included within AutoMapper.', __METHOD__);
Expand Down Expand Up @@ -176,6 +179,12 @@ public static function create(
$classDiscriminatorFromClassMetadata = new ClassDiscriminatorFromClassMetadata($classMetadataFactory);
}

$providers = iterator_to_array($providers);

if (null !== $entityManager) {
$providers[] = new DoctrineProvider($entityManager);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we can't surcharge this provider and its static ? is there any way we could provide it with configuration so we can surcharge it ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the DX method to create the automapper, you will be able to surcharge it in symfony like always, or just don't pass the entity manager and pass your own provider

}

$customTransformerRegistry = new PropertyTransformerRegistry($propertyTransformers);
$metadataRegistry = new MetadataRegistry($configuration);
$providerRegistry = new ProviderRegistry($providers);
Expand All @@ -192,6 +201,7 @@ public static function create(
$expressionLanguage,
$eventDispatcher,
$removeDefaultProperties,
$entityManager,
);

$mapperGenerator = new MapperGenerator(
Expand Down
29 changes: 29 additions & 0 deletions src/EventListener/Doctrine/DoctrineIdentifierListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace AutoMapper\EventListener\Doctrine;

use AutoMapper\Event\PropertyMetadataEvent;
use Doctrine\ORM\EntityManagerInterface;

final readonly class DoctrineIdentifierListener
{
public function __construct(
private EntityManagerInterface $entityManager
) {
}

public function __invoke(PropertyMetadataEvent $event): void
{
if ($event->mapperMetadata->target === 'array' || !$this->entityManager->getMetadataFactory()->hasMetadataFor($event->mapperMetadata->target)) {
return;
}

$metadata = $this->entityManager->getClassMetadata($event->mapperMetadata->target);

if ($metadata->isIdentifier($event->target->property)) {
$event->identifier = true;
}
}
}
26 changes: 26 additions & 0 deletions src/EventListener/Doctrine/DoctrineProviderListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace AutoMapper\EventListener\Doctrine;

use AutoMapper\Event\GenerateMapperEvent;
use AutoMapper\Provider\Doctrine\DoctrineProvider;
use Doctrine\ORM\EntityManagerInterface;

final readonly class DoctrineProviderListener
{
public function __construct(
private EntityManagerInterface $entityManager
) {
}

public function __invoke(GenerateMapperEvent $event): void
{
if ($event->mapperMetadata->target === 'array' || !$this->entityManager->getMetadataFactory()->hasMetadataFor($event->mapperMetadata->target)) {
return;
}

$event->provider = DoctrineProvider::class;
}
}
5 changes: 5 additions & 0 deletions src/GeneratedMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ public function registerMappers(AutoMapperRegistryInterface $registry): void
{
}

public function getTargetIdentifiers(mixed $value): mixed
{
return null;
}

public function getSourceHash(mixed $value): ?string
{
return null;
Expand Down
148 changes: 147 additions & 1 deletion src/Generator/IdentifierHashGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@

namespace AutoMapper\Generator;

use AutoMapper\Extractor\ReadAccessor;
use AutoMapper\Metadata\GeneratorMetadata;
use AutoMapper\Transformer\IdentifierHashInterface;
use PhpParser\Builder;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;

Expand All @@ -16,7 +20,7 @@
/**
* @return list<Stmt>
*/
public function getStatements(GeneratorMetadata $metadata, bool $fromSource): array
private function getStatements(GeneratorMetadata $metadata, bool $fromSource): array
{
$identifiers = [];

Expand Down Expand Up @@ -97,4 +101,146 @@ public function getStatements(GeneratorMetadata $metadata, bool $fromSource): ar

return $statements;
}

/**
* Create the getSourceHash method for this mapper.
*
* ```php
* public function getSourceHash(mixed $source, mixed $target): ?string {
* ... // statements
* }
* ```
*/
public function getSourceHashMethod(GeneratorMetadata $metadata): ?Stmt\ClassMethod
{
$stmts = $this->getStatements($metadata, true);

if (empty($stmts)) {
return null;
}

return (new Builder\Method('getSourceHash'))
->makePublic()
->setReturnType('?string')
->addParam(new Param(
var: new Expr\Variable('value'),
type: new Name('mixed'))
)
->addStmts($stmts)
->getNode();
}

/**
* Create the getTargetHash method for this mapper.
*
* ```php
* public function getTargetHash(mixed $source, mixed $target): ?string {
* ... // statements
* }
* ```
*/
public function getTargetHashMethod(GeneratorMetadata $metadata): ?Stmt\ClassMethod
{
$stmts = $this->getStatements($metadata, false);

if (empty($stmts)) {
return null;
}

return (new Builder\Method('getTargetHash'))
->makePublic()
->setReturnType('?string')
->addParam(new Param(
var: new Expr\Variable('value'),
type: new Name('mixed'))
)
->addStmts($stmts)
->getNode();
}

/**
* Create the getTargetIdentifiers method for this mapper.
*
* ```php
* public function getTargetIdentifiers(mixed $source): mixed {
* ... // statements
* }
* ```
*/
public function getTargetIdentifiersMethod(GeneratorMetadata $metadata): ?Stmt\ClassMethod
{
$identifiers = [];

foreach ($metadata->propertiesMetadata as $propertyMetadata) {
if (!$propertyMetadata->identifier) {
continue;
}

if (null === $propertyMetadata->source->accessor) {
continue;
}

$identifiers[] = $propertyMetadata;
}

if (empty($identifiers)) {
return null;
}

$isUnique = \count($identifiers) === 1;

$identifiersVariable = new Expr\Variable('identifiers');
$valueVariable = new Expr\Variable('value');
$statements = [];

if (!$isUnique) {
$statements[] = new Stmt\Expression(new Expr\Assign($identifiersVariable, new Expr\Array_()));
}

// foreach property we check
foreach ($identifiers as $property) {
/** @var ReadAccessor $accessor */
$accessor = $property->source->accessor;

// check if the source is defined
if ($property->source->checkExists) {
$statements[] = new Stmt\If_($accessor->getIsUndefinedExpression($valueVariable), [
'stmts' => [
new Stmt\Return_(new Expr\ConstFetch(new Name('null'))),
],
]);
}

$fieldValueExpr = $accessor->getExpression($valueVariable);
$transformer = $property->transformer;

if ($transformer instanceof IdentifierHashInterface) {
$fieldValueExpr = $transformer->getIdentifierExpression($fieldValueExpr);
}

if ($isUnique) {
$statements[] = new Stmt\Return_($fieldValueExpr);
} else {
$statements[] = new Stmt\Expression(new Expr\Assign(
new Expr\ArrayDimFetch($identifiersVariable, new Scalar\String_($property->target->property)),
$fieldValueExpr
));
}
}

// return hash as string
if (!$isUnique) {
$statements[] = new Stmt\Return_($identifiersVariable);
}

return (new Builder\Method('getTargetIdentifiers'))
->makePublic()
->setReturnType('mixed')
->addParam(new Param(
var: new Expr\Variable('value'),
type: new Name('mixed'))
)
->addStmts($statements)
->getNode();
}
}
3 changes: 3 additions & 0 deletions src/Generator/MapMethodStatementsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,9 @@ private function initializeTargetFromProvider(GeneratorMetadata $metadata): arra
new Arg(new Scalar\String_($metadata->mapperMetadata->target)),
new Arg($variableRegistry->getSourceInput()),
new Arg($variableRegistry->getContext()),
new Arg(new Expr\MethodCall(new Expr\Variable('this'), 'getTargetIdentifiers', [
new Arg(new Expr\Variable('value')),
])),
]),
)
);
Expand Down
64 changes: 6 additions & 58 deletions src/Generator/MapperGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,18 @@ public function generate(GeneratorMetadata $metadata): array
->addStmt($this->mapMethod($metadata))
->addStmt($this->registerMappersMethod($metadata));

if ($sourceHashMethod = $this->getSourceHashMethod($metadata)) {
if ($sourceHashMethod = $this->identifierHashGenerator->getSourceHashMethod($metadata)) {
$builder->addStmt($sourceHashMethod);
}

if ($targetHashMethod = $this->getTargetHashMethod($metadata)) {
if ($targetHashMethod = $this->identifierHashGenerator->getTargetHashMethod($metadata)) {
$builder->addStmt($targetHashMethod);
}

if ($targetIdentifierMethod = $this->identifierHashGenerator->getTargetIdentifiersMethod($metadata)) {
$builder->addStmt($targetIdentifierMethod);
}

$statements[] = $builder->getNode();

return $statements;
Expand Down Expand Up @@ -174,60 +178,4 @@ private function registerMappersMethod(GeneratorMetadata $metadata): Stmt\ClassM
->addStmts($this->injectMapperMethodStatementsGenerator->getStatements($param, $metadata))
->getNode();
}

/**
* Create the getSourceHash method for this mapper.
*
* ```php
* public function getSourceHash(mixed $source, mixed $target): ?string {
* ... // statements
* }
* ```
*/
private function getSourceHashMethod(GeneratorMetadata $metadata): ?Stmt\ClassMethod
{
$stmts = $this->identifierHashGenerator->getStatements($metadata, true);

if (empty($stmts)) {
return null;
}

return (new Builder\Method('getSourceHash'))
->makePublic()
->setReturnType('?string')
->addParam(new Param(
var: new Expr\Variable('value'),
type: new Name('mixed'))
)
->addStmts($stmts)
->getNode();
}

/**
* Create the getTargetHash method for this mapper.
*
* ```php
* public function getSourceHash(mixed $source, mixed $target): ?string {
* ... // statements
* }
* ```
*/
private function getTargetHashMethod(GeneratorMetadata $metadata): ?Stmt\ClassMethod
{
$stmts = $this->identifierHashGenerator->getStatements($metadata, false);

if (empty($stmts)) {
return null;
}

return (new Builder\Method('getTargetHash'))
->makePublic()
->setReturnType('?string')
->addParam(new Param(
var: new Expr\Variable('value'),
type: new Name('mixed'))
)
->addStmts($stmts)
->getNode();
}
}
Loading