-
-
Save miguelvilata/178936043849f9114c5e9835a4de4b88 to your computer and use it in GitHub Desktop.
Compiler pass to declare a repository as service for each declared doctrine entity in a symfony application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class RegisterRepositoriesForAllEntitiesPass implements CompilerPassInterface | |
{ | |
/** {@inheritdoc} */ | |
public function process(ContainerBuilder $container) | |
{ | |
/** @var MappingDriver $metadata */ | |
$metadata = $container->get($this->mappingDriverServiceName()); | |
$entityManagerReference = new Reference('doctrine.orm.entity_manager'); | |
Assert::isInstanceOf($metadata, MappingDriver::class); | |
$allClassNames = $metadata->getAllClassNames(); | |
$repositoryDefinitions = array_combine( | |
array_map(static function (string $entity): string { | |
return $entity.'.repository'; | |
}, $allClassNames), | |
array_map( | |
static function (string $entity) use ($entityManagerReference): Definition { | |
$definition = new Definition(EntityRepository::class); | |
$definition->setFactory([$entityManagerReference, 'getRepository']); | |
$definition->setArgument(0, $entity); | |
return $definition; | |
}, | |
$allClassNames | |
) | |
); | |
Assert::isArray($repositoryDefinitions); | |
$container->addDefinitions($repositoryDefinitions); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment