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

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