vendor/doctrine/doctrine-bundle/src/DependencyInjection/DoctrineExtension.php line 615

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