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

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