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

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