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

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