vendor/doctrine/doctrine-bundle/DependencyInjection/DoctrineExtension.php line 471

Open in your IDE?
  1. <?php
  2. namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection;
  3. use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
  4. use Doctrine\Bundle\DoctrineBundle\CacheWarmer\DoctrineMetadataCacheWarmer;
  5. use Doctrine\Bundle\DoctrineBundle\Command\Proxy\ImportDoctrineCommand;
  6. use Doctrine\Bundle\DoctrineBundle\Dbal\ManagerRegistryAwareConnectionProvider;
  7. use Doctrine\Bundle\DoctrineBundle\Dbal\RegexSchemaAssetFilter;
  8. use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\IdGeneratorPass;
  9. use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
  10. use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
  11. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface;
  12. use Doctrine\DBAL\Connection;
  13. use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
  14. use Doctrine\DBAL\Logging\LoggerChain;
  15. use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
  16. use Doctrine\DBAL\Tools\Console\ConnectionProvider;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Doctrine\ORM\Id\AbstractIdGenerator;
  19. use Doctrine\ORM\Proxy\Autoloader;
  20. use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
  21. use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand;
  22. use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
  23. use Doctrine\ORM\UnitOfWork;
  24. use LogicException;
  25. use Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension;
  26. use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
  27. use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator;
  28. use Symfony\Bridge\Doctrine\Messenger\DoctrineClearEntityManagerWorkerSubscriber;
  29. use Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware;
  30. use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
  31. use Symfony\Bridge\Doctrine\SchemaListener\DoctrineDbalCacheAdapterSchemaSubscriber;
  32. use Symfony\Bridge\Doctrine\SchemaListener\MessengerTransportDoctrineSchemaSubscriber;
  33. use Symfony\Bridge\Doctrine\SchemaListener\PdoCacheAdapterDoctrineSchemaSubscriber;
  34. use Symfony\Bridge\Doctrine\SchemaListener\RememberMeTokenProviderDoctrineSchemaSubscriber;
  35. use Symfony\Bridge\Doctrine\Validator\DoctrineLoader;
  36. use Symfony\Component\Cache\Adapter\ArrayAdapter;
  37. use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
  38. use Symfony\Component\Config\FileLocator;
  39. use Symfony\Component\DependencyInjection\Alias;
  40. use Symfony\Component\DependencyInjection\ChildDefinition;
  41. use Symfony\Component\DependencyInjection\ContainerBuilder;
  42. use Symfony\Component\DependencyInjection\Definition;
  43. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  44. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  45. use Symfony\Component\DependencyInjection\Reference;
  46. use Symfony\Component\Form\AbstractType;
  47. use Symfony\Component\Messenger\Bridge\Doctrine\Transport\DoctrineTransportFactory;
  48. use Symfony\Component\Messenger\MessageBusInterface;
  49. use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
  50. use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
  51. use function array_intersect_key;
  52. use function array_keys;
  53. use function class_exists;
  54. use function interface_exists;
  55. use function is_dir;
  56. use function method_exists;
  57. use function reset;
  58. use function sprintf;
  59. use function str_replace;
  60. /**
  61.  * DoctrineExtension is an extension for the Doctrine DBAL and ORM library.
  62.  */
  63. class DoctrineExtension extends AbstractDoctrineExtension
  64. {
  65.     /** @var string */
  66.     private $defaultConnection;
  67.     /**
  68.      * {@inheritDoc}
  69.      */
  70.     public function load(array $configsContainerBuilder $container)
  71.     {
  72.         $configuration $this->getConfiguration($configs$container);
  73.         $config        $this->processConfiguration($configuration$configs);
  74.         if (! empty($config['dbal'])) {
  75.             $this->dbalLoad($config['dbal'], $container);
  76.             $this->loadMessengerServices($container);
  77.         }
  78.         if (empty($config['orm'])) {
  79.             return;
  80.         }
  81.         if (empty($config['dbal'])) {
  82.             throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.');
  83.         }
  84.         $this->ormLoad($config['orm'], $container);
  85.     }
  86.     /**
  87.      * Loads the DBAL configuration.
  88.      *
  89.      * Usage example:
  90.      *
  91.      *      <doctrine:dbal id="myconn" dbname="sfweb" user="root" />
  92.      *
  93.      * @param array<string, mixed> $config    An array of configuration settings
  94.      * @param ContainerBuilder     $container A ContainerBuilder instance
  95.      */
  96.     protected function dbalLoad(array $configContainerBuilder $container)
  97.     {
  98.         $loader = new XmlFileLoader($container, new FileLocator(__DIR__ '/../Resources/config'));
  99.         $loader->load('dbal.xml');
  100.         $chainLogger $container->getDefinition('doctrine.dbal.logger.chain');
  101.         $logger      = new Reference('doctrine.dbal.logger');
  102.         $chainLogger->addArgument([$logger]);
  103.         if (class_exists(ImportCommand::class)) {
  104.             $container->register('doctrine.database_import_command'ImportDoctrineCommand::class)
  105.                 ->addTag('console.command', ['command' => 'doctrine:database:import']);
  106.         }
  107.         if (empty($config['default_connection'])) {
  108.             $keys                         array_keys($config['connections']);
  109.             $config['default_connection'] = reset($keys);
  110.         }
  111.         $this->defaultConnection $config['default_connection'];
  112.         $container->setAlias('database_connection'sprintf('doctrine.dbal.%s_connection'$this->defaultConnection));
  113.         $container->getAlias('database_connection')->setPublic(true);
  114.         $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager'$this->defaultConnection), false));
  115.         $container->setParameter('doctrine.dbal.connection_factory.types'$config['types']);
  116.         $connections = [];
  117.         foreach (array_keys($config['connections']) as $name) {
  118.             $connections[$name] = sprintf('doctrine.dbal.%s_connection'$name);
  119.         }
  120.         $container->setParameter('doctrine.connections'$connections);
  121.         $container->setParameter('doctrine.default_connection'$this->defaultConnection);
  122.         foreach ($config['connections'] as $name => $connection) {
  123.             $this->loadDbalConnection($name$connection$container);
  124.         }
  125.     }
  126.     /**
  127.      * Loads a configured DBAL connection.
  128.      *
  129.      * @param string               $name       The name of the connection
  130.      * @param array<string, mixed> $connection A dbal connection configuration.
  131.      * @param ContainerBuilder     $container  A ContainerBuilder instance
  132.      */
  133.     protected function loadDbalConnection($name, array $connectionContainerBuilder $container)
  134.     {
  135.         $configuration $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration'$name), new ChildDefinition('doctrine.dbal.connection.configuration'));
  136.         $logger        null;
  137.         if ($connection['logging']) {
  138.             $logger = new Reference('doctrine.dbal.logger');
  139.         }
  140.         unset($connection['logging']);
  141.         $dataCollectorDefinition $container->getDefinition('data_collector.doctrine');
  142.         $dataCollectorDefinition->replaceArgument(1$connection['profiling_collect_schema_errors']);
  143.         if ($connection['profiling']) {
  144.             $profilingAbstractId $connection['profiling_collect_backtrace'] ?
  145.                 'doctrine.dbal.logger.backtrace' :
  146.                 'doctrine.dbal.logger.profiling';
  147.             $profilingLoggerId $profilingAbstractId '.' $name;
  148.             $container->setDefinition($profilingLoggerId, new ChildDefinition($profilingAbstractId));
  149.             $profilingLogger = new Reference($profilingLoggerId);
  150.             $dataCollectorDefinition->addMethodCall('addLogger', [$name$profilingLogger]);
  151.             if ($logger !== null) {
  152.                 $chainLogger $container->register(
  153.                     'doctrine.dbal.logger.chain',
  154.                     LoggerChain::class
  155.                 );
  156.                 $chainLogger->addArgument([$logger$profilingLogger]);
  157.                 $loggerId 'doctrine.dbal.logger.chain.' $name;
  158.                 $container->setDefinition($loggerId$chainLogger);
  159.                 $logger = new Reference($loggerId);
  160.             } else {
  161.                 $logger $profilingLogger;
  162.             }
  163.         }
  164.         unset(
  165.             $connection['profiling'],
  166.             $connection['profiling_collect_backtrace'],
  167.             $connection['profiling_collect_schema_errors']
  168.         );
  169.         if (isset($connection['auto_commit'])) {
  170.             $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]);
  171.         }
  172.         unset($connection['auto_commit']);
  173.         if (isset($connection['schema_filter']) && $connection['schema_filter']) {
  174.             $definition = new Definition(RegexSchemaAssetFilter::class, [$connection['schema_filter']]);
  175.             $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]);
  176.             $container->setDefinition(sprintf('doctrine.dbal.%s_regex_schema_filter'$name), $definition);
  177.         }
  178.         unset($connection['schema_filter']);
  179.         if ($logger) {
  180.             $configuration->addMethodCall('setSQLLogger', [$logger]);
  181.         }
  182.         // event manager
  183.         $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager'$name), new ChildDefinition('doctrine.dbal.connection.event_manager'));
  184.         // connection
  185.         $options $this->getConnectionOptions($connection);
  186.         $connectionId sprintf('doctrine.dbal.%s_connection'$name);
  187.         $def $container
  188.             ->setDefinition($connectionId, new ChildDefinition('doctrine.dbal.connection'))
  189.             ->setPublic(true)
  190.             ->setArguments([
  191.                 $options,
  192.                 new Reference(sprintf('doctrine.dbal.%s_connection.configuration'$name)),
  193.                 new Reference(sprintf('doctrine.dbal.%s_connection.event_manager'$name)),
  194.                 $connection['mapping_types'],
  195.             ]);
  196.         $container
  197.             ->registerAliasForArgument($connectionIdConnection::class, sprintf('%sConnection'$name))
  198.             ->setPublic(false);
  199.         // Set class in case "wrapper_class" option was used to assist IDEs
  200.         if (isset($options['wrapperClass'])) {
  201.             $def->setClass($options['wrapperClass']);
  202.         }
  203.         if (! empty($connection['use_savepoints'])) {
  204.             $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]);
  205.         }
  206.         // Create a shard_manager for this connection
  207.         if (isset($options['shards'])) {
  208.             $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference($connectionId)]);
  209.             $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager'$name), $shardManagerDefinition);
  210.         }
  211.         // dbal < 2.11 BC layer
  212.         if (! interface_exists(ConnectionProvider::class)) {
  213.             return;
  214.         }
  215.         $container->setDefinition(
  216.             ManagerRegistryAwareConnectionProvider::class,
  217.             new Definition(ManagerRegistryAwareConnectionProvider::class, [$container->getDefinition('doctrine')])
  218.         );
  219.     }
  220.     /**
  221.      * @param array<string, mixed> $connection
  222.      *
  223.      * @return mixed[]
  224.      */
  225.     protected function getConnectionOptions(array $connection): array
  226.     {
  227.         $options $connection;
  228.         $connectionDefaults = [
  229.             'host' => 'localhost',
  230.             'port' => null,
  231.             'user' => 'root',
  232.             'password' => null,
  233.         ];
  234.         if ($options['override_url'] ?? false) {
  235.             $options['connection_override_options'] = array_intersect_key($options, ['dbname' => null] + $connectionDefaults);
  236.         }
  237.         unset($options['override_url']);
  238.         $options += $connectionDefaults;
  239.         foreach (['shards''replicas''slaves'] as $connectionKey) {
  240.             foreach (array_keys($options[$connectionKey]) as $name) {
  241.                 $options[$connectionKey][$name] += $connectionDefaults;
  242.             }
  243.         }
  244.         if (isset($options['platform_service'])) {
  245.             $options['platform'] = new Reference($options['platform_service']);
  246.             unset($options['platform_service']);
  247.         }
  248.         unset($options['mapping_types']);
  249.         if (isset($options['shard_choser_service'])) {
  250.             $options['shard_choser'] = new Reference($options['shard_choser_service']);
  251.             unset($options['shard_choser_service']);
  252.         }
  253.         foreach (
  254.             [
  255.                 'options' => 'driverOptions',
  256.                 'driver_class' => 'driverClass',
  257.                 'wrapper_class' => 'wrapperClass',
  258.                 'keep_slave' => 'keepReplica',
  259.                 'keep_replica' => 'keepReplica',
  260.                 'replicas' => 'replica',
  261.                 'shard_choser' => 'shardChoser',
  262.                 'shard_manager_class' => 'shardManagerClass',
  263.                 'server_version' => 'serverVersion',
  264.                 'default_table_options' => 'defaultTableOptions',
  265.             ] as $old => $new
  266.         ) {
  267.             if (! isset($options[$old])) {
  268.                 continue;
  269.             }
  270.             $options[$new] = $options[$old];
  271.             unset($options[$old]);
  272.         }
  273.         if (! empty($options['slaves']) && ! empty($options['replica']) && ! empty($options['shards'])) {
  274.             throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together');
  275.         }
  276.         if (! empty($options['slaves']) || ! empty($options['replica'])) {
  277.             $nonRewrittenKeys = [
  278.                 'driver' => true,
  279.                 'driverOptions' => true,
  280.                 'driverClass' => true,
  281.                 'wrapperClass' => true,
  282.                 'keepSlave' => true,
  283.                 'keepReplica' => true,
  284.                 'shardChoser' => true,
  285.                 'platform' => true,
  286.                 'slaves' => true,
  287.                 'master' => true,
  288.                 'primary' => true,
  289.                 'replica' => true,
  290.                 'shards' => true,
  291.                 'serverVersion' => true,
  292.                 'defaultTableOptions' => true,
  293.                 // included by safety but should have been unset already
  294.                 'logging' => true,
  295.                 'profiling' => true,
  296.                 'mapping_types' => true,
  297.                 'platform_service' => true,
  298.             ];
  299.             foreach ($options as $key => $value) {
  300.                 if (isset($nonRewrittenKeys[$key])) {
  301.                     continue;
  302.                 }
  303.                 $options['primary'][$key] = $value;
  304.                 unset($options[$key]);
  305.             }
  306.             if (empty($options['wrapperClass'])) {
  307.                 // Change the wrapper class only if user did not configure custom one.
  308.                 $options['wrapperClass'] = PrimaryReadReplicaConnection::class;
  309.             }
  310.         } else {
  311.             unset($options['slaves'], $options['replica']);
  312.         }
  313.         if (! empty($options['shards'])) {
  314.             $nonRewrittenKeys = [
  315.                 'driver' => true,
  316.                 'driverOptions' => true,
  317.                 'driverClass' => true,
  318.                 'wrapperClass' => true,
  319.                 'keepSlave' => true,
  320.                 'keepReplica' => true,
  321.                 'shardChoser' => true,
  322.                 'platform' => true,
  323.                 'slaves' => true,
  324.                 'replica' => true,
  325.                 'global' => true,
  326.                 'shards' => true,
  327.                 'serverVersion' => true,
  328.                 'defaultTableOptions' => true,
  329.                 // included by safety but should have been unset already
  330.                 'logging' => true,
  331.                 'profiling' => true,
  332.                 'mapping_types' => true,
  333.                 'platform_service' => true,
  334.                 'shardManagerClass' => true,
  335.             ];
  336.             foreach ($options as $key => $value) {
  337.                 if (isset($nonRewrittenKeys[$key])) {
  338.                     continue;
  339.                 }
  340.                 $options['global'][$key] = $value;
  341.                 unset($options[$key]);
  342.             }
  343.             if (empty($options['wrapperClass'])) {
  344.                 // Change the wrapper class only if the user does not already forced using a custom one.
  345.                 $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection';
  346.             }
  347.             if (empty($options['shardManagerClass'])) {
  348.                 // Change the shard manager class only if the user does not already forced using a custom one.
  349.                 $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager';
  350.             }
  351.         } else {
  352.             unset($options['shards']);
  353.         }
  354.         return $options;
  355.     }
  356.     /**
  357.      * Loads the Doctrine ORM configuration.
  358.      *
  359.      * Usage example:
  360.      *
  361.      *     <doctrine:orm id="mydm" connection="myconn" />
  362.      *
  363.      * @param array<string, mixed> $config    An array of configuration settings
  364.      * @param ContainerBuilder     $container A ContainerBuilder instance
  365.      */
  366.     protected function ormLoad(array $configContainerBuilder $container)
  367.     {
  368.         if (! class_exists(UnitOfWork::class)) {
  369.             throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.');
  370.         }
  371.         $loader = new XmlFileLoader($container, new FileLocator(__DIR__ '/../Resources/config'));
  372.         $loader->load('orm.xml');
  373.         if (class_exists(AbstractType::class)) {
  374.             $container->getDefinition('form.type.entity')->addTag('kernel.reset', ['method' => 'reset']);
  375.         }
  376.         // available in Symfony 5.4 and higher
  377.         if (! class_exists(DoctrineDbalCacheAdapterSchemaSubscriber::class)) {
  378.             $container->removeDefinition('doctrine.orm.listeners.doctrine_dbal_cache_adapter_schema_subscriber');
  379.         }
  380.         // available in Symfony 5.1 and up to Symfony 5.4 (deprecated)
  381.         if (! class_exists(PdoCacheAdapterDoctrineSchemaSubscriber::class)) {
  382.             $container->removeDefinition('doctrine.orm.listeners.pdo_cache_adapter_doctrine_schema_subscriber');
  383.         }
  384.         // available in Symfony 5.3 and higher
  385.         if (! class_exists(RememberMeTokenProviderDoctrineSchemaSubscriber::class)) {
  386.             $container->removeDefinition('doctrine.orm.listeners.doctrine_token_provider_schema_subscriber');
  387.         }
  388.         if (! class_exists(UlidGenerator::class)) {
  389.             $container->removeDefinition('doctrine.ulid_generator');
  390.         }
  391.         if (! class_exists(UuidGenerator::class)) {
  392.             $container->removeDefinition('doctrine.uuid_generator');
  393.         }
  394.         // not available in Doctrine ORM 3.0 and higher
  395.         if (! class_exists(ConvertMappingCommand::class)) {
  396.             $container->removeDefinition('doctrine.mapping_convert_command');
  397.         }
  398.         if (! class_exists(EnsureProductionSettingsCommand::class)) {
  399.             $container->removeDefinition('doctrine.ensure_production_settings_command');
  400.         }
  401.         if (! class_exists(ClassMetadataExporter::class)) {
  402.             $container->removeDefinition('doctrine.mapping_import_command');
  403.         }
  404.         $entityManagers = [];
  405.         foreach (array_keys($config['entity_managers']) as $name) {
  406.             $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager'$name);
  407.         }
  408.         $container->setParameter('doctrine.entity_managers'$entityManagers);
  409.         if (empty($config['default_entity_manager'])) {
  410.             $tmp                              array_keys($entityManagers);
  411.             $config['default_entity_manager'] = reset($tmp);
  412.         }
  413.         $container->setParameter('doctrine.default_entity_manager'$config['default_entity_manager']);
  414.         $options = ['auto_generate_proxy_classes''proxy_dir''proxy_namespace'];
  415.         foreach ($options as $key) {
  416.             $container->setParameter('doctrine.orm.' $key$config[$key]);
  417.         }
  418.         $container->setAlias('doctrine.orm.entity_manager'$defaultEntityManagerDefinitionId sprintf('doctrine.orm.%s_entity_manager'$config['default_entity_manager']));
  419.         $container->getAlias('doctrine.orm.entity_manager')->setPublic(true);
  420.         $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles'));
  421.         foreach ($config['entity_managers'] as $name => $entityManager) {
  422.             $entityManager['name'] = $name;
  423.             $this->loadOrmEntityManager($entityManager$container);
  424.             if (interface_exists(PropertyInfoExtractorInterface::class)) {
  425.                 $this->loadPropertyInfoExtractor($name$container);
  426.             }
  427.             if (! interface_exists(LoaderInterface::class)) {
  428.                 continue;
  429.             }
  430.             $this->loadValidatorLoader($name$container);
  431.         }
  432.         if ($config['resolve_target_entities']) {
  433.             $def $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
  434.             foreach ($config['resolve_target_entities'] as $name => $implementation) {
  435.                 $def->addMethodCall('addResolveTargetEntity', [
  436.                     $name,
  437.                     $implementation,
  438.                     [],
  439.                 ]);
  440.             }
  441.             $def->addTag('doctrine.event_subscriber');
  442.         }
  443.         $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class)
  444.             ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
  445.         $container->registerForAutoconfiguration(EventSubscriberInterface::class)
  446.             ->addTag('doctrine.event_subscriber');
  447.         $container->registerForAutoconfiguration(AbstractIdGenerator::class)
  448.             ->addTag(IdGeneratorPass::ID_GENERATOR_TAG);
  449.         if (method_exists($container'registerAttributeForAutoconfiguration')) {
  450.             $container->registerAttributeForAutoconfiguration(AsEntityListener::class, static function (ChildDefinition $definitionAsEntityListener $attribute) {
  451.                 $definition->addTag('doctrine.orm.entity_listener', [
  452.                     'event'          => $attribute->event,
  453.                     'method'         => $attribute->method,
  454.                     'lazy'           => $attribute->lazy,
  455.                     'entity_manager' => $attribute->entityManager,
  456.                 ]);
  457.             });
  458.         }
  459.         /** @see DoctrineBundle::boot() */
  460.         $container->getDefinition($defaultEntityManagerDefinitionId)
  461.             ->addTag('container.preload', [
  462.                 'class' => Autoloader::class,
  463.             ]);
  464.     }
  465.     /**
  466.      * Loads a configured ORM entity manager.
  467.      *
  468.      * @param array<string, mixed> $entityManager A configured ORM entity manager.
  469.      * @param ContainerBuilder     $container     A ContainerBuilder instance
  470.      */
  471.     protected function loadOrmEntityManager(array $entityManagerContainerBuilder $container)
  472.     {
  473.         $ormConfigDef $container->setDefinition(sprintf('doctrine.orm.%s_configuration'$entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));
  474.         $ormConfigDef->addTag(IdGeneratorPass::CONFIGURATION_TAG);
  475.         $this->loadOrmEntityManagerMappingInformation($entityManager$ormConfigDef$container);
  476.         $this->loadOrmCacheDrivers($entityManager$container);
  477.         if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
  478.             $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver'$entityManager['name']), $entityManager['entity_listener_resolver']);
  479.         } else {
  480.             $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
  481.             $definition->addArgument(new Reference('service_container'));
  482.             $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver'$entityManager['name']), $definition);
  483.         }
  484.         $methods = [
  485.             'setMetadataCache' => new Reference(sprintf('doctrine.orm.%s_metadata_cache'$entityManager['name'])),
  486.             'setQueryCacheImpl' => new Reference(sprintf('doctrine.orm.%s_query_cache'$entityManager['name'])),
  487.             'setResultCacheImpl' => new Reference(sprintf('doctrine.orm.%s_result_cache'$entityManager['name'])),
  488.             'setMetadataDriverImpl' => new Reference('doctrine.orm.' $entityManager['name'] . '_metadata_driver'),
  489.             'setProxyDir' => '%doctrine.orm.proxy_dir%',
  490.             'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
  491.             'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
  492.             'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
  493.             'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
  494.             'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
  495.             'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
  496.             'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver'$entityManager['name'])),
  497.         ];
  498.         $listenerId        sprintf('doctrine.orm.%s_listeners.attach_entity_listeners'$entityManager['name']);
  499.         $listenerDef       $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
  500.         $listenerTagParams = ['event' => 'loadClassMetadata'];
  501.         if (isset($entityManager['connection'])) {
  502.             $listenerTagParams['connection'] = $entityManager['connection'];
  503.         }
  504.         $listenerDef->addTag('doctrine.event_listener'$listenerTagParams);
  505.         if (isset($entityManager['second_level_cache'])) {
  506.             $this->loadOrmSecondLevelCache($entityManager$ormConfigDef$container);
  507.         }
  508.         if ($entityManager['repository_factory']) {
  509.             $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
  510.         }
  511.         foreach ($methods as $method => $arg) {
  512.             $ormConfigDef->addMethodCall($method, [$arg]);
  513.         }
  514.         foreach ($entityManager['hydrators'] as $name => $class) {
  515.             $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name$class]);
  516.         }
  517.         if (! empty($entityManager['dql'])) {
  518.             foreach ($entityManager['dql']['string_functions'] as $name => $function) {
  519.                 $ormConfigDef->addMethodCall('addCustomStringFunction', [$name$function]);
  520.             }
  521.             foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
  522.                 $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name$function]);
  523.             }
  524.             foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
  525.                 $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name$function]);
  526.             }
  527.         }
  528.         $enabledFilters    = [];
  529.         $filtersParameters = [];
  530.         foreach ($entityManager['filters'] as $name => $filter) {
  531.             $ormConfigDef->addMethodCall('addFilter', [$name$filter['class']]);
  532.             if ($filter['enabled']) {
  533.                 $enabledFilters[] = $name;
  534.             }
  535.             if (! $filter['parameters']) {
  536.                 continue;
  537.             }
  538.             $filtersParameters[$name] = $filter['parameters'];
  539.         }
  540.         $managerConfiguratorName sprintf('doctrine.orm.%s_manager_configurator'$entityManager['name']);
  541.         $container
  542.             ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
  543.             ->replaceArgument(0$enabledFilters)
  544.             ->replaceArgument(1$filtersParameters);
  545.         if (! isset($entityManager['connection'])) {
  546.             $entityManager['connection'] = $this->defaultConnection;
  547.         }
  548.         $entityManagerId sprintf('doctrine.orm.%s_entity_manager'$entityManager['name']);
  549.         $container
  550.             ->setDefinition($entityManagerId, new ChildDefinition('doctrine.orm.entity_manager.abstract'))
  551.             ->setPublic(true)
  552.             ->setArguments([
  553.                 new Reference(sprintf('doctrine.dbal.%s_connection'$entityManager['connection'])),
  554.                 new Reference(sprintf('doctrine.orm.%s_configuration'$entityManager['name'])),
  555.             ])
  556.             ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);
  557.         $container
  558.             ->registerAliasForArgument($entityManagerIdEntityManagerInterface::class, sprintf('%sEntityManager'$entityManager['name']))
  559.             ->setPublic(false);
  560.         $container->setAlias(
  561.             sprintf('doctrine.orm.%s_entity_manager.event_manager'$entityManager['name']),
  562.             new Alias(sprintf('doctrine.dbal.%s_connection.event_manager'$entityManager['connection']), false)
  563.         );
  564.         if (! isset($entityManager['entity_listeners'])) {
  565.             return;
  566.         }
  567.         $entities $entityManager['entity_listeners']['entities'];
  568.         foreach ($entities as $entityListenerClass => $entity) {
  569.             foreach ($entity['listeners'] as $listenerClass => $listener) {
  570.                 foreach ($listener['events'] as $listenerEvent) {
  571.                     $listenerEventName $listenerEvent['type'];
  572.                     $listenerMethod    $listenerEvent['method'];
  573.                     $listenerDef->addMethodCall('addEntityListener', [
  574.                         $entityListenerClass,
  575.                         $listenerClass,
  576.                         $listenerEventName,
  577.                         $listenerMethod,
  578.                     ]);
  579.                 }
  580.             }
  581.         }
  582.     }
  583.     /**
  584.      * Loads an ORM entity managers bundle mapping information.
  585.      *
  586.      * There are two distinct configuration possibilities for mapping information:
  587.      *
  588.      * 1. Specify a bundle and optionally details where the entity and mapping information reside.
  589.      * 2. Specify an arbitrary mapping location.
  590.      *
  591.      * @param array<string, mixed> $entityManager A configured ORM entity manager
  592.      * @param Definition           $ormConfigDef  A Definition instance
  593.      * @param ContainerBuilder     $container     A ContainerBuilder instance
  594.      *
  595.      * @example
  596.      *
  597.      *  doctrine.orm:
  598.      *     mappings:
  599.      *         MyBundle1: ~
  600.      *         MyBundle2: yml
  601.      *         MyBundle3: { type: annotation, dir: Entities/ }
  602.      *         MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
  603.      *         MyBundle5: { type: attribute, dir: Entities/ }
  604.      *         MyBundle6:
  605.      *             type: yml
  606.      *             dir: bundle-mappings/
  607.      *             alias: BundleAlias
  608.      *         arbitrary_key:
  609.      *             type: xml
  610.      *             dir: %kernel.project_dir%/src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities
  611.      *             prefix: DoctrineExtensions\Entities\
  612.      *             alias: DExt
  613.      *
  614.      * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
  615.      * in the mappings key everything except alias is a required argument.
  616.      */
  617.     protected function loadOrmEntityManagerMappingInformation(array $entityManagerDefinition $ormConfigDefContainerBuilder $container)
  618.     {
  619.         // reset state of drivers and alias map. They are only used by this methods and children.
  620.         $this->drivers  = [];
  621.         $this->aliasMap = [];
  622.         $this->loadMappingInformation($entityManager$container);
  623.         $this->registerMappingDrivers($entityManager$container);
  624.         $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]);
  625.     }
  626.     /**
  627.      * Loads an ORM second level cache bundle mapping information.
  628.      *
  629.      * @param array<string, mixed> $entityManager A configured ORM entity manager
  630.      * @param Definition           $ormConfigDef  A Definition instance
  631.      * @param ContainerBuilder     $container     A ContainerBuilder instance
  632.      *
  633.      * @example
  634.      *  entity_managers:
  635.      *      default:
  636.      *          second_level_cache:
  637.      *              region_lifetime: 3600
  638.      *              region_lock_lifetime: 60
  639.      *              region_cache_driver: apc
  640.      *              log_enabled: true
  641.      *              regions:
  642.      *                  my_service_region:
  643.      *                      type: service
  644.      *                      service : "my_service_region"
  645.      *
  646.      *                  my_query_region:
  647.      *                      lifetime: 300
  648.      *                      cache_driver: array
  649.      *                      type: filelock
  650.      *
  651.      *                  my_entity_region:
  652.      *                      lifetime: 600
  653.      *                      cache_driver:
  654.      *                          type: apc
  655.      */
  656.     protected function loadOrmSecondLevelCache(array $entityManagerDefinition $ormConfigDefContainerBuilder $container)
  657.     {
  658.         $driverId null;
  659.         $enabled  $entityManager['second_level_cache']['enabled'];
  660.         if (isset($entityManager['second_level_cache']['region_cache_driver'])) {
  661.             $driverName 'second_level_cache.region_cache_driver';
  662.             $driverMap  $entityManager['second_level_cache']['region_cache_driver'];
  663.             $driverId   $this->loadCacheDriver($driverName$entityManager['name'], $driverMap$container);
  664.         }
  665.         $configId   sprintf('doctrine.orm.%s_second_level_cache.cache_configuration'$entityManager['name']);
  666.         $regionsId  sprintf('doctrine.orm.%s_second_level_cache.regions_configuration'$entityManager['name']);
  667.         $driverId   $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver'$entityManager['name']);
  668.         $configDef  $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%'));
  669.         $regionsDef $container
  670.             ->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%'))
  671.             ->setArguments([$entityManager['second_level_cache']['region_lifetime'], $entityManager['second_level_cache']['region_lock_lifetime']]);
  672.         $slcFactoryId sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory'$entityManager['name']);
  673.         $factoryClass $entityManager['second_level_cache']['factory'] ?? '%doctrine.orm.second_level_cache.default_cache_factory.class%';
  674.         $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]);
  675.         $slcFactoryDef $container
  676.             ->setDefinition($slcFactoryId$definition);
  677.         if (isset($entityManager['second_level_cache']['regions'])) {
  678.             foreach ($entityManager['second_level_cache']['regions'] as $name => $region) {
  679.                 $regionRef  null;
  680.                 $regionType $region['type'];
  681.                 if ($regionType === 'service') {
  682.                     $regionId  sprintf('doctrine.orm.%s_second_level_cache.region.%s'$entityManager['name'], $name);
  683.                     $regionRef = new Reference($region['service']);
  684.                     $container->setAlias($regionId, new Alias($region['service'], false));
  685.                 }
  686.                 if ($regionType === 'default' || $regionType === 'filelock') {
  687.                     $regionId   sprintf('doctrine.orm.%s_second_level_cache.region.%s'$entityManager['name'], $name);
  688.                     $driverName sprintf('second_level_cache.region.%s_driver'$name);
  689.                     $driverMap  $region['cache_driver'];
  690.                     $driverId   $this->loadCacheDriver($driverName$entityManager['name'], $driverMap$container);
  691.                     $regionRef  = new Reference($regionId);
  692.                     $container
  693.                         ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%'))
  694.                         ->setArguments([$name, new Reference($driverId), $region['lifetime']]);
  695.                 }
  696.                 if ($regionType === 'filelock') {
  697.                     $regionId sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock'$entityManager['name'], $name);
  698.                     $container
  699.                         ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%'))
  700.                         ->setArguments([$regionRef$region['lock_path'], $region['lock_lifetime']]);
  701.                     $regionRef = new Reference($regionId);
  702.                     $regionsDef->addMethodCall('getLockLifetime', [$name$region['lock_lifetime']]);
  703.                 }
  704.                 $regionsDef->addMethodCall('setLifetime', [$name$region['lifetime']]);
  705.                 $slcFactoryDef->addMethodCall('setRegion', [$regionRef]);
  706.             }
  707.         }
  708.         if ($entityManager['second_level_cache']['log_enabled']) {
  709.             $loggerChainId   sprintf('doctrine.orm.%s_second_level_cache.logger_chain'$entityManager['name']);
  710.             $loggerStatsId   sprintf('doctrine.orm.%s_second_level_cache.logger_statistics'$entityManager['name']);
  711.             $loggerChaingDef $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%'));
  712.             $loggerStatsDef  $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%'));
  713.             $loggerChaingDef->addMethodCall('setLogger', ['statistics'$loggerStatsDef]);
  714.             $configDef->addMethodCall('setCacheLogger', [$loggerChaingDef]);
  715.             foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) {
  716.                 $loggerId  sprintf('doctrine.orm.%s_second_level_cache.logger.%s'$entityManager['name'], $name);
  717.                 $loggerRef = new Reference($logger['service']);
  718.                 $container->setAlias($loggerId, new Alias($logger['service'], false));
  719.                 $loggerChaingDef->addMethodCall('setLogger', [$name$loggerRef]);
  720.             }
  721.         }
  722.         $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]);
  723.         $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]);
  724.         $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]);
  725.         $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]);
  726.     }
  727.     /**
  728.      * {@inheritDoc}
  729.      */
  730.     protected function getObjectManagerElementName($name): string
  731.     {
  732.         return 'doctrine.orm.' $name;
  733.     }
  734.     protected function getMappingObjectDefaultName(): string
  735.     {
  736.         return 'Entity';
  737.     }
  738.     protected function getMappingResourceConfigDirectory(?string $bundleDir null): string
  739.     {
  740.         if ($bundleDir !== null && is_dir($bundleDir '/config/doctrine')) {
  741.             return 'config/doctrine';
  742.         }
  743.         return 'Resources/config/doctrine';
  744.     }
  745.     protected function getMappingResourceExtension(): string
  746.     {
  747.         return 'orm';
  748.     }
  749.     /**
  750.      * {@inheritDoc}
  751.      */
  752.     protected function loadCacheDriver($cacheName$objectManagerName, array $cacheDriverContainerBuilder $container): string
  753.     {
  754.         $aliasId $this->getObjectManagerElementName(sprintf('%s_%s'$objectManagerName$cacheName));
  755.         switch ($cacheDriver['type'] ?? 'pool') {
  756.             case 'service':
  757.                 $serviceId $cacheDriver['id'];
  758.                 break;
  759.             case 'pool':
  760.                 $serviceId $cacheDriver['pool'] ?? $this->createArrayAdapterCachePool($container$objectManagerName$cacheName);
  761.                 break;
  762.             default:
  763.                 throw new \InvalidArgumentException(sprintf(
  764.                     'Unknown cache of type "%s" configured for cache "%s" in entity manager "%s".',
  765.                     $cacheDriver['type'],
  766.                     $cacheName,
  767.                     $objectManagerName
  768.                 ));
  769.         }
  770.         $container->setAlias($aliasId, new Alias($serviceIdfalse));
  771.         return $aliasId;
  772.     }
  773.     /**
  774.      * Loads a configured entity managers cache drivers.
  775.      *
  776.      * @param array<string, mixed> $entityManager A configured ORM entity manager.
  777.      */
  778.     protected function loadOrmCacheDrivers(array $entityManagerContainerBuilder $container)
  779.     {
  780.         if (isset($entityManager['metadata_cache_driver'])) {
  781.             $this->loadCacheDriver('metadata_cache'$entityManager['name'], $entityManager['metadata_cache_driver'], $container);
  782.         } else {
  783.             $this->createMetadataCache($entityManager['name'], $container);
  784.         }
  785.         $this->loadCacheDriver('result_cache'$entityManager['name'], $entityManager['result_cache_driver'], $container);
  786.         $this->loadCacheDriver('query_cache'$entityManager['name'], $entityManager['query_cache_driver'], $container);
  787.     }
  788.     private function createMetadataCache(string $objectManagerNameContainerBuilder $container): void
  789.     {
  790.         $aliasId $this->getObjectManagerElementName(sprintf('%s_%s'$objectManagerName'metadata_cache'));
  791.         $cacheId sprintf('cache.doctrine.orm.%s.%s'$objectManagerName'metadata');
  792.         $cache = new Definition(ArrayAdapter::class);
  793.         if (! $container->getParameter('kernel.debug')) {
  794.             $phpArrayFile         '%kernel.cache_dir%' sprintf('/doctrine/orm/%s_metadata.php'$objectManagerName);
  795.             $cacheWarmerServiceId $this->getObjectManagerElementName(sprintf('%s_%s'$objectManagerName'metadata_cache_warmer'));
  796.             $container->register($cacheWarmerServiceIdDoctrineMetadataCacheWarmer::class)
  797.                 ->setArguments([new Reference(sprintf('doctrine.orm.%s_entity_manager'$objectManagerName)), $phpArrayFile])
  798.                 ->addTag('kernel.cache_warmer', ['priority' => 1000]); // priority should be higher than ProxyCacheWarmer
  799.             $cache = new Definition(PhpArrayAdapter::class, [$phpArrayFile$cache]);
  800.         }
  801.         $container->setDefinition($cacheId$cache);
  802.         $container->setAlias($aliasId$cacheId);
  803.     }
  804.     /**
  805.      * Loads a property info extractor for each defined entity manager.
  806.      */
  807.     private function loadPropertyInfoExtractor(string $entityManagerNameContainerBuilder $container): void
  808.     {
  809.         $propertyExtractorDefinition $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor'$entityManagerName), DoctrineExtractor::class);
  810.         $argumentId                  sprintf('doctrine.orm.%s_entity_manager'$entityManagerName);
  811.         $propertyExtractorDefinition->addArgument(new Reference($argumentId));
  812.         $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]);
  813.         $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]);
  814.         $propertyExtractorDefinition->addTag('property_info.access_extractor', ['priority' => -999]);
  815.     }
  816.     /**
  817.      * Loads a validator loader for each defined entity manager.
  818.      */
  819.     private function loadValidatorLoader(string $entityManagerNameContainerBuilder $container): void
  820.     {
  821.         $validatorLoaderDefinition $container->register(sprintf('doctrine.orm.%s_entity_manager.validator_loader'$entityManagerName), DoctrineLoader::class);
  822.         $validatorLoaderDefinition->addArgument(new Reference(sprintf('doctrine.orm.%s_entity_manager'$entityManagerName)));
  823.         $validatorLoaderDefinition->addTag('validator.auto_mapper', ['priority' => -100]);
  824.     }
  825.     /**
  826.      * @param array<string, mixed> $objectManager
  827.      * @param string               $cacheName
  828.      *
  829.      * @psalm-suppress MoreSpecificImplementedParamType
  830.      */
  831.     public function loadObjectManagerCacheDriver(array $objectManagerContainerBuilder $container$cacheName)
  832.     {
  833.         $this->loadCacheDriver($cacheName$objectManager['name'], $objectManager[$cacheName '_driver'], $container);
  834.     }
  835.     public function getXsdValidationBasePath(): string
  836.     {
  837.         return __DIR__ '/../Resources/config/schema';
  838.     }
  839.     public function getNamespace(): string
  840.     {
  841.         return 'http://symfony.com/schema/dic/doctrine';
  842.     }
  843.     /**
  844.      * {@inheritDoc}
  845.      */
  846.     public function getConfiguration(array $configContainerBuilder $container): Configuration
  847.     {
  848.         return new Configuration((bool) $container->getParameter('kernel.debug'));
  849.     }
  850.     protected function getMetadataDriverClass(string $driverType): string
  851.     {
  852.         return '%' $this->getObjectManagerElementName('metadata.' $driverType '.class') . '%';
  853.     }
  854.     private function loadMessengerServices(ContainerBuilder $container): void
  855.     {
  856.         // If the Messenger component is installed and the doctrine transaction middleware is available, wire it:
  857.         /** @psalm-suppress UndefinedClass Optional dependency */
  858.         if (! interface_exists(MessageBusInterface::class) || ! class_exists(DoctrineTransactionMiddleware::class)) {
  859.             return;
  860.         }
  861.         $loader = new XmlFileLoader($container, new FileLocator(__DIR__ '/../Resources/config'));
  862.         $loader->load('messenger.xml');
  863.         if (! class_exists(DoctrineClearEntityManagerWorkerSubscriber::class)) {
  864.             $container->removeDefinition('doctrine.orm.messenger.event_subscriber.doctrine_clear_entity_manager');
  865.         }
  866.         // available in Symfony 5.1 and higher
  867.         if (! class_exists(MessengerTransportDoctrineSchemaSubscriber::class)) {
  868.             $container->removeDefinition('doctrine.orm.messenger.doctrine_schema_subscriber');
  869.         }
  870.         $transportFactoryDefinition $container->getDefinition('messenger.transport.doctrine.factory');
  871.         if (! class_exists(DoctrineTransportFactory::class)) {
  872.             // If symfony/messenger < 5.1
  873.             if (! class_exists(\Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransportFactory::class)) {
  874.                 // Dont add the tag
  875.                 return;
  876.             }
  877.             $transportFactoryDefinition->setClass(\Symfony\Component\Messenger\Transport\Doctrine\DoctrineTransportFactory::class);
  878.         }
  879.         $transportFactoryDefinition->addTag('messenger.transport_factory');
  880.     }
  881.     private function createArrayAdapterCachePool(ContainerBuilder $containerstring $objectManagerNamestring $cacheName): string
  882.     {
  883.         $id sprintf('cache.doctrine.orm.%s.%s'$objectManagerNamestr_replace('_cache'''$cacheName));
  884.         $poolDefinition $container->register($idArrayAdapter::class);
  885.         $poolDefinition->addTag('cache.pool');
  886.         $container->setDefinition($id$poolDefinition);
  887.         return $id;
  888.     }
  889. }