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

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. * @phpstan-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 $configs, ContainerBuilder $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($configuration, array_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 $config, ContainerBuilder $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(0, array_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 $definition, AsMiddleware $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, $connWithBacktrace, array_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 $connection, ContainerBuilder $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($connectionId, Connection::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 $config, ContainerBuilder $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. $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name);
  483. }
  484. $container->setParameter('doctrine.entity_managers', $entityManagers);
  485. if (empty($config['default_entity_manager'])) {
  486. $tmp = array_keys($entityManagers);
  487. $config['default_entity_manager'] = reset($tmp);
  488. }
  489. $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']);
  490. if ($config['enable_lazy_ghost_objects'] ?? false) {
  491. // available in Symfony 6.2 and higher
  492. if (! trait_exists(LazyGhostTrait::class)) {
  493. throw new LogicException(
  494. 'Lazy ghost objects cannot be enabled because the "symfony/var-exporter" library'
  495. . ' version 6.2 or higher is not installed. Please run "composer require symfony/var-exporter:^6.2".',
  496. );
  497. }
  498. if (! class_exists(RuntimeReflectionProperty::class)) {
  499. throw new LogicException(
  500. 'Lazy ghost objects cannot be enabled because the "doctrine/persistence" library'
  501. . ' version 3.1 or higher is not installed. Please run "composer update doctrine/persistence".',
  502. );
  503. }
  504. } elseif (! method_exists(ProxyFactory::class, 'resetUninitializedProxy')) {
  505. throw new LogicException(
  506. 'Lazy ghost objects cannot be disabled for ORM 3.',
  507. );
  508. } elseif (PHP_VERSION_ID >= 80100) {
  509. trigger_deprecation('doctrine/doctrine-bundle', '2.11', 'Not setting "doctrine.orm.enable_lazy_ghost_objects" to true is deprecated.');
  510. }
  511. $options = ['auto_generate_proxy_classes', 'enable_lazy_ghost_objects', 'proxy_dir', 'proxy_namespace'];
  512. foreach ($options as $key) {
  513. $container->setParameter('doctrine.orm.' . $key, $config[$key]);
  514. }
  515. $container->setAlias('doctrine.orm.entity_manager', $defaultEntityManagerDefinitionId = sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager']));
  516. $container->getAlias('doctrine.orm.entity_manager')->setPublic(true);
  517. $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles'));
  518. foreach ($config['entity_managers'] as $name => $entityManager) {
  519. $entityManager['name'] = $name;
  520. $this->loadOrmEntityManager($entityManager, $container);
  521. if (interface_exists(PropertyInfoExtractorInterface::class)) {
  522. $this->loadPropertyInfoExtractor($name, $container);
  523. }
  524. if (! interface_exists(LoaderInterface::class)) {
  525. continue;
  526. }
  527. $this->loadValidatorLoader($name, $container);
  528. }
  529. if ($config['resolve_target_entities']) {
  530. $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
  531. foreach ($config['resolve_target_entities'] as $name => $implementation) {
  532. $def->addMethodCall('addResolveTargetEntity', [
  533. $name,
  534. $implementation,
  535. [],
  536. ]);
  537. }
  538. $def
  539. ->addTag('doctrine.event_listener', ['event' => Events::loadClassMetadata])
  540. ->addTag('doctrine.event_listener', ['event' => Events::onClassMetadataNotFound]);
  541. }
  542. $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class)
  543. ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
  544. $container->registerForAutoconfiguration(EventSubscriberInterface::class)
  545. ->addTag('doctrine.event_subscriber');
  546. $container->registerForAutoconfiguration(AbstractIdGenerator::class)
  547. ->addTag(IdGeneratorPass::ID_GENERATOR_TAG);
  548. $container->registerAttributeForAutoconfiguration(AsEntityListener::class, static function (ChildDefinition $definition, AsEntityListener $attribute) {
  549. $definition->addTag('doctrine.orm.entity_listener', [
  550. 'event' => $attribute->event,
  551. 'method' => $attribute->method,
  552. 'lazy' => $attribute->lazy,
  553. 'entity_manager' => $attribute->entityManager,
  554. 'entity' => $attribute->entity,
  555. 'priority' => $attribute->priority,
  556. ]);
  557. });
  558. $container->registerAttributeForAutoconfiguration(AsDoctrineListener::class, static function (ChildDefinition $definition, AsDoctrineListener $attribute) {
  559. $definition->addTag('doctrine.event_listener', [
  560. 'event' => $attribute->event,
  561. 'priority' => $attribute->priority,
  562. 'connection' => $attribute->connection,
  563. ]);
  564. });
  565. /** @see DoctrineBundle::boot() */
  566. $container->getDefinition($defaultEntityManagerDefinitionId)
  567. ->addTag('container.preload', [
  568. 'class' => Autoloader::class,
  569. ]);
  570. }
  571. /**
  572. * Loads a configured ORM entity manager.
  573. *
  574. * @param array<string, mixed> $entityManager A configured ORM entity manager.
  575. * @param ContainerBuilder $container A ContainerBuilder instance
  576. */
  577. protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container)
  578. {
  579. $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));
  580. $ormConfigDef->addTag(IdGeneratorPass::CONFIGURATION_TAG);
  581. $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container);
  582. $this->loadOrmCacheDrivers($entityManager, $container);
  583. if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
  584. $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']);
  585. } else {
  586. $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
  587. $definition->addArgument(new Reference('service_container'));
  588. $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition);
  589. }
  590. $methods = [
  591. 'setMetadataCache' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])),
  592. 'setQueryCache' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])),
  593. 'setResultCache' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])),
  594. 'setMetadataDriverImpl' => new Reference('doctrine.orm.' . $entityManager['name'] . '_metadata_driver'),
  595. 'setProxyDir' => '%doctrine.orm.proxy_dir%',
  596. 'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
  597. 'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
  598. 'setSchemaIgnoreClasses' => $entityManager['schema_ignore_classes'],
  599. 'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
  600. 'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
  601. 'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
  602. 'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
  603. 'setTypedFieldMapper' => new Reference($entityManager['typed_field_mapper']),
  604. 'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])),
  605. 'setLazyGhostObjectEnabled' => '%doctrine.orm.enable_lazy_ghost_objects%',
  606. 'setIdentityGenerationPreferences' => $entityManager['identity_generation_preferences'],
  607. ];
  608. if (! method_exists(OrmConfiguration::class, 'setLazyGhostObjectEnabled')) {
  609. unset($methods['setLazyGhostObjectEnabled']);
  610. }
  611. $listenerId = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']);
  612. $listenerDef = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
  613. $listenerTagParams = ['event' => 'loadClassMetadata'];
  614. if (isset($entityManager['connection'])) {
  615. $listenerTagParams['connection'] = $entityManager['connection'];
  616. }
  617. $listenerDef->addTag('doctrine.event_listener', $listenerTagParams);
  618. if (isset($entityManager['second_level_cache'])) {
  619. $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container);
  620. }
  621. if ($entityManager['repository_factory']) {
  622. $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
  623. }
  624. foreach ($methods as $method => $arg) {
  625. $ormConfigDef->addMethodCall($method, [$arg]);
  626. }
  627. foreach ($entityManager['hydrators'] as $name => $class) {
  628. $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]);
  629. }
  630. if (! empty($entityManager['dql'])) {
  631. foreach ($entityManager['dql']['string_functions'] as $name => $function) {
  632. $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]);
  633. }
  634. foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
  635. $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]);
  636. }
  637. foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
  638. $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]);
  639. }
  640. }
  641. $enabledFilters = [];
  642. $filtersParameters = [];
  643. foreach ($entityManager['filters'] as $name => $filter) {
  644. $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]);
  645. if ($filter['enabled']) {
  646. $enabledFilters[] = $name;
  647. }
  648. if (! $filter['parameters']) {
  649. continue;
  650. }
  651. $filtersParameters[$name] = $filter['parameters'];
  652. }
  653. $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']);
  654. $container
  655. ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
  656. ->replaceArgument(0, $enabledFilters)
  657. ->replaceArgument(1, $filtersParameters);
  658. if (! isset($entityManager['connection'])) {
  659. $entityManager['connection'] = $this->defaultConnection;
  660. }
  661. $entityManagerId = sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']);
  662. $container
  663. ->setDefinition($entityManagerId, new ChildDefinition('doctrine.orm.entity_manager.abstract'))
  664. ->setPublic(true)
  665. ->setArguments([
  666. new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])),
  667. new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])),
  668. new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection'])),
  669. ])
  670. ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);
  671. $container
  672. ->registerAliasForArgument($entityManagerId, EntityManagerInterface::class, sprintf('%sEntityManager', $entityManager['name']))
  673. ->setPublic(false);
  674. $container->setAlias(
  675. sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']),
  676. new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false),
  677. );
  678. if (! isset($entityManager['entity_listeners'])) {
  679. return;
  680. }
  681. $entities = $entityManager['entity_listeners']['entities'];
  682. foreach ($entities as $entityListenerClass => $entity) {
  683. foreach ($entity['listeners'] as $listenerClass => $listener) {
  684. foreach ($listener['events'] as $listenerEvent) {
  685. $listenerEventName = $listenerEvent['type'];
  686. $listenerMethod = $listenerEvent['method'];
  687. $listenerDef->addMethodCall('addEntityListener', [
  688. $entityListenerClass,
  689. $listenerClass,
  690. $listenerEventName,
  691. $listenerMethod,
  692. ]);
  693. }
  694. }
  695. }
  696. }
  697. /**
  698. * Loads an ORM entity managers bundle mapping information.
  699. *
  700. * There are two distinct configuration possibilities for mapping information:
  701. *
  702. * 1. Specify a bundle and optionally details where the entity and mapping information reside.
  703. * 2. Specify an arbitrary mapping location.
  704. *
  705. * @param array<string, mixed> $entityManager A configured ORM entity manager
  706. * @param Definition $ormConfigDef A Definition instance
  707. * @param ContainerBuilder $container A ContainerBuilder instance
  708. *
  709. * @example
  710. *
  711. * doctrine.orm:
  712. * mappings:
  713. * MyBundle1: ~
  714. * MyBundle2: yml
  715. * MyBundle3: { type: annotation, dir: Entities/ }
  716. * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
  717. * MyBundle5: { type: attribute, dir: Entities/ }
  718. * MyBundle6:
  719. * type: yml
  720. * dir: bundle-mappings/
  721. * alias: BundleAlias
  722. * arbitrary_key:
  723. * type: xml
  724. * dir: %kernel.project_dir%/src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities
  725. * prefix: DoctrineExtensions\Entities\
  726. * alias: DExt
  727. *
  728. * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
  729. * in the mappings key everything except alias is a required argument.
  730. */
  731. protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
  732. {
  733. // reset state of drivers and alias map. They are only used by this methods and children.
  734. $this->drivers = [];
  735. $this->aliasMap = [];
  736. $this->loadMappingInformation($entityManager, $container);
  737. $this->registerMappingDrivers($entityManager, $container);
  738. $container->getDefinition($this->getObjectManagerElementName($entityManager['name'] . '_metadata_driver'));
  739. /** @psalm-suppress NoValue $this->drivers is set by $this->loadMappingInformation() call */
  740. foreach (array_keys($this->drivers) as $driverType) {
  741. $mappingService = $this->getObjectManagerElementName($entityManager['name'] . '_' . $driverType . '_metadata_driver');
  742. $mappingDriverDef = $container->getDefinition($mappingService);
  743. $args = $mappingDriverDef->getArguments();
  744. if ($driverType === 'annotation') {
  745. $args[2] = $entityManager['report_fields_where_declared'];
  746. } elseif ($driverType === 'attribute') {
  747. $args[1] = $entityManager['report_fields_where_declared'];
  748. } elseif ($driverType === 'xml') {
  749. $args[1] ??= SimplifiedXmlDriver::DEFAULT_FILE_EXTENSION;
  750. $args[2] = $entityManager['validate_xml_mapping'];
  751. } else {
  752. continue;
  753. }
  754. $mappingDriverDef->setArguments($args);
  755. }
  756. $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]);
  757. }
  758. /**
  759. * Loads an ORM second level cache bundle mapping information.
  760. *
  761. * @param array<string, mixed> $entityManager A configured ORM entity manager
  762. * @param Definition $ormConfigDef A Definition instance
  763. * @param ContainerBuilder $container A ContainerBuilder instance
  764. *
  765. * @example
  766. * entity_managers:
  767. * default:
  768. * second_level_cache:
  769. * region_lifetime: 3600
  770. * region_lock_lifetime: 60
  771. * region_cache_driver: apc
  772. * log_enabled: true
  773. * regions:
  774. * my_service_region:
  775. * type: service
  776. * service : "my_service_region"
  777. *
  778. * my_query_region:
  779. * lifetime: 300
  780. * cache_driver: array
  781. * type: filelock
  782. *
  783. * my_entity_region:
  784. * lifetime: 600
  785. * cache_driver:
  786. * type: apc
  787. */
  788. protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
  789. {
  790. $driverId = null;
  791. $enabled = $entityManager['second_level_cache']['enabled'];
  792. if (isset($entityManager['second_level_cache']['region_cache_driver'])) {
  793. $driverName = 'second_level_cache.region_cache_driver';
  794. $driverMap = $entityManager['second_level_cache']['region_cache_driver'];
  795. $driverId = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
  796. }
  797. $configId = sprintf('doctrine.orm.%s_second_level_cache.cache_configuration', $entityManager['name']);
  798. $regionsId = sprintf('doctrine.orm.%s_second_level_cache.regions_configuration', $entityManager['name']);
  799. $driverId = $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver', $entityManager['name']);
  800. $configDef = $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%'));
  801. $regionsDef = $container
  802. ->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%'))
  803. ->setArguments([$entityManager['second_level_cache']['region_lifetime'], $entityManager['second_level_cache']['region_lock_lifetime']]);
  804. $slcFactoryId = sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory', $entityManager['name']);
  805. $factoryClass = $entityManager['second_level_cache']['factory'] ?? '%doctrine.orm.second_level_cache.default_cache_factory.class%';
  806. $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]);
  807. $slcFactoryDef = $container
  808. ->setDefinition($slcFactoryId, $definition);
  809. if (isset($entityManager['second_level_cache']['regions'])) {
  810. foreach ($entityManager['second_level_cache']['regions'] as $name => $region) {
  811. $regionRef = null;
  812. $regionType = $region['type'];
  813. if ($regionType === 'service') {
  814. $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
  815. $regionRef = new Reference($region['service']);
  816. $container->setAlias($regionId, new Alias($region['service'], false));
  817. }
  818. if ($regionType === 'default' || $regionType === 'filelock') {
  819. $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
  820. $driverName = sprintf('second_level_cache.region.%s_driver', $name);
  821. $driverMap = $region['cache_driver'];
  822. $driverId = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
  823. $regionRef = new Reference($regionId);
  824. $container
  825. ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%'))
  826. ->setArguments([$name, new Reference($driverId), $region['lifetime']]);
  827. }
  828. if ($regionType === 'filelock') {
  829. $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock', $entityManager['name'], $name);
  830. $container
  831. ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%'))
  832. ->setArguments([$regionRef, $region['lock_path'], $region['lock_lifetime']]);
  833. $regionRef = new Reference($regionId);
  834. $regionsDef->addMethodCall('getLockLifetime', [$name, $region['lock_lifetime']]);
  835. }
  836. $regionsDef->addMethodCall('setLifetime', [$name, $region['lifetime']]);
  837. $slcFactoryDef->addMethodCall('setRegion', [$regionRef]);
  838. }
  839. }
  840. if ($entityManager['second_level_cache']['log_enabled']) {
  841. $loggerChainId = sprintf('doctrine.orm.%s_second_level_cache.logger_chain', $entityManager['name']);
  842. $loggerStatsId = sprintf('doctrine.orm.%s_second_level_cache.logger_statistics', $entityManager['name']);
  843. $loggerChaingDef = $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%'));
  844. $loggerStatsDef = $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%'));
  845. $loggerChaingDef->addMethodCall('setLogger', ['statistics', $loggerStatsDef]);
  846. $configDef->addMethodCall('setCacheLogger', [$loggerChaingDef]);
  847. foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) {
  848. $loggerId = sprintf('doctrine.orm.%s_second_level_cache.logger.%s', $entityManager['name'], $name);
  849. $loggerRef = new Reference($logger['service']);
  850. $container->setAlias($loggerId, new Alias($logger['service'], false));
  851. $loggerChaingDef->addMethodCall('setLogger', [$name, $loggerRef]);
  852. }
  853. }
  854. $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]);
  855. $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]);
  856. $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]);
  857. $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]);
  858. }
  859. /**
  860. * {@inheritDoc}
  861. */
  862. protected function getObjectManagerElementName($name): string
  863. {
  864. return 'doctrine.orm.' . $name;
  865. }
  866. protected function getMappingObjectDefaultName(): string
  867. {
  868. return 'Entity';
  869. }
  870. protected function getMappingResourceConfigDirectory(?string $bundleDir = null): string
  871. {
  872. if ($bundleDir !== null && is_dir($bundleDir . '/config/doctrine')) {
  873. return 'config/doctrine';
  874. }
  875. return 'Resources/config/doctrine';
  876. }
  877. protected function getMappingResourceExtension(): string
  878. {
  879. return 'orm';
  880. }
  881. /**
  882. * {@inheritDoc}
  883. */
  884. protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheDriver, ContainerBuilder $container): string
  885. {
  886. $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, $cacheName));
  887. switch ($cacheDriver['type'] ?? 'pool') {
  888. case 'service':
  889. $serviceId = $cacheDriver['id'];
  890. break;
  891. case 'pool':
  892. $serviceId = $cacheDriver['pool'] ?? $this->createArrayAdapterCachePool($container, $objectManagerName, $cacheName);
  893. break;
  894. default:
  895. throw new InvalidArgumentException(sprintf(
  896. 'Unknown cache of type "%s" configured for cache "%s" in entity manager "%s".',
  897. $cacheDriver['type'],
  898. $cacheName,
  899. $objectManagerName,
  900. ));
  901. }
  902. $container->setAlias($aliasId, new Alias($serviceId, false));
  903. return $aliasId;
  904. }
  905. /**
  906. * Loads a configured entity managers cache drivers.
  907. *
  908. * @param array<string, mixed> $entityManager A configured ORM entity manager.
  909. */
  910. protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container)
  911. {
  912. if (isset($entityManager['metadata_cache_driver'])) {
  913. $this->loadCacheDriver('metadata_cache', $entityManager['name'], $entityManager['metadata_cache_driver'], $container);
  914. } else {
  915. $this->createMetadataCache($entityManager['name'], $container);
  916. }
  917. $this->loadCacheDriver('result_cache', $entityManager['name'], $entityManager['result_cache_driver'], $container);
  918. $this->loadCacheDriver('query_cache', $entityManager['name'], $entityManager['query_cache_driver'], $container);
  919. }
  920. private function createMetadataCache(string $objectManagerName, ContainerBuilder $container): void
  921. {
  922. $aliasId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, 'metadata_cache'));
  923. $cacheId = sprintf('cache.doctrine.orm.%s.%s', $objectManagerName, 'metadata');
  924. $cache = new Definition(ArrayAdapter::class);
  925. if (! $container->getParameter('kernel.debug')) {
  926. $phpArrayFile = '%kernel.cache_dir%' . sprintf('/doctrine/orm/%s_metadata.php', $objectManagerName);
  927. $cacheWarmerServiceId = $this->getObjectManagerElementName(sprintf('%s_%s', $objectManagerName, 'metadata_cache_warmer'));
  928. $container->register($cacheWarmerServiceId, DoctrineMetadataCacheWarmer::class)
  929. ->setArguments([new Reference(sprintf('doctrine.orm.%s_entity_manager', $objectManagerName)), $phpArrayFile])
  930. ->addTag('kernel.cache_warmer', ['priority' => 1000]); // priority should be higher than ProxyCacheWarmer
  931. $cache = new Definition(PhpArrayAdapter::class, [$phpArrayFile, $cache]);
  932. }
  933. $container->setDefinition($cacheId, $cache);
  934. $container->setAlias($aliasId, $cacheId);
  935. }
  936. /**
  937. * Loads a property info extractor for each defined entity manager.
  938. */
  939. private function loadPropertyInfoExtractor(string $entityManagerName, ContainerBuilder $container): void
  940. {
  941. $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor', $entityManagerName), DoctrineExtractor::class);
  942. $argumentId = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName);
  943. $propertyExtractorDefinition->addArgument(new Reference($argumentId));
  944. $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]);
  945. $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]);
  946. $propertyExtractorDefinition->addTag('property_info.access_extractor', ['priority' => -999]);
  947. }
  948. /**
  949. * Loads a validator loader for each defined entity manager.
  950. */
  951. private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container): void
  952. {
  953. $validatorLoaderDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.validator_loader', $entityManagerName), DoctrineLoader::class);
  954. $validatorLoaderDefinition->addArgument(new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)));
  955. $validatorLoaderDefinition->addTag('validator.auto_mapper', ['priority' => -100]);
  956. }
  957. public function getXsdValidationBasePath(): string
  958. {
  959. return __DIR__ . '/../../config/schema';
  960. }
  961. public function getNamespace(): string
  962. {
  963. return 'http://symfony.com/schema/dic/doctrine';
  964. }
  965. /**
  966. * {@inheritDoc}
  967. */
  968. public function getConfiguration(array $config, ContainerBuilder $container): Configuration
  969. {
  970. return new Configuration((bool) $container->getParameter('kernel.debug'));
  971. }
  972. protected function getMetadataDriverClass(string $driverType): string
  973. {
  974. switch ($driverType) {
  975. case 'driver_chain':
  976. return MappingDriverChain::class;
  977. case 'annotation':
  978. if (! class_exists(AnnotationDriver::class)) {
  979. throw new LogicException('The annotation driver is only available in doctrine/orm v2.');
  980. }
  981. return AnnotationDriver::class;
  982. case 'xml':
  983. return SimplifiedXmlDriver::class;
  984. case 'yml':
  985. /* @phpstan-ignore class.notFound */
  986. return SimplifiedYamlDriver::class;
  987. case 'php':
  988. /* @phpstan-ignore class.notFound */
  989. return class_exists(PHPDriver::class) ? PHPDriver::class : LegacyPHPDriver::class;
  990. case 'staticphp':
  991. /* @phpstan-ignore class.notFound */
  992. return class_exists(StaticPHPDriver::class) ? StaticPHPDriver::class : LegacyStaticPHPDriver::class;
  993. case 'attribute':
  994. return AttributeDriver::class;
  995. default:
  996. throw new LogicException(sprintf('Unknown "%s" metadata driver type.', $driverType));
  997. }
  998. }
  999. private function loadMessengerServices(ContainerBuilder $container): void
  1000. {
  1001. // If the Messenger component is installed, wire it:
  1002. if (! interface_exists(MessageBusInterface::class)) {
  1003. return;
  1004. }
  1005. $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
  1006. $loader->load('messenger.xml');
  1007. // available in Symfony 6.3
  1008. $container->removeDefinition('doctrine.orm.messenger.doctrine_schema_' . (class_exists(MessengerTransportDoctrineSchemaListener::class) ? 'subscriber' : 'listener'));
  1009. /**
  1010. * The Doctrine transport component (symfony/doctrine-messenger) is optional.
  1011. * Remove service definition, if it is not available
  1012. */
  1013. if (class_exists(DoctrineTransportFactory::class)) {
  1014. return;
  1015. }
  1016. $container->removeDefinition('messenger.transport.doctrine.factory');
  1017. $container->removeDefinition('doctrine.orm.messenger.doctrine_schema_subscriber');
  1018. $container->removeDefinition('doctrine.orm.messenger.doctrine_schema_listener');
  1019. }
  1020. private function createArrayAdapterCachePool(ContainerBuilder $container, string $objectManagerName, string $cacheName): string
  1021. {
  1022. $id = sprintf('cache.doctrine.orm.%s.%s', $objectManagerName, str_replace('_cache', '', $cacheName));
  1023. $poolDefinition = $container->register($id, ArrayAdapter::class);
  1024. $poolDefinition->addTag('cache.pool');
  1025. $container->setDefinition($id, $poolDefinition);
  1026. return $id;
  1027. }
  1028. /**
  1029. * @param string[] $connWithLogging
  1030. * @param string[] $connWithProfiling
  1031. * @param string[] $connWithBacktrace
  1032. * @param string[] $connWithTtl
  1033. */
  1034. private function registerDbalMiddlewares(
  1035. ContainerBuilder $container,
  1036. array $connWithLogging,
  1037. array $connWithProfiling,
  1038. array $connWithBacktrace,
  1039. array $connWithTtl
  1040. ): void {
  1041. $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
  1042. $loader->load('middlewares.xml');
  1043. $loggingMiddlewareAbstractDef = $container->getDefinition('doctrine.dbal.logging_middleware');
  1044. foreach ($connWithLogging as $connName) {
  1045. $loggingMiddlewareAbstractDef->addTag('doctrine.middleware', ['connection' => $connName, 'priority' => 10]);
  1046. }
  1047. $container->getDefinition('doctrine.debug_data_holder')->replaceArgument(0, $connWithBacktrace);
  1048. $debugMiddlewareAbstractDef = $container->getDefinition('doctrine.dbal.debug_middleware');
  1049. foreach ($connWithProfiling as $connName) {
  1050. $debugMiddlewareAbstractDef
  1051. ->addTag('doctrine.middleware', ['connection' => $connName, 'priority' => 10]);
  1052. }
  1053. $idleConnectionMiddlewareAbstractDef = $container->getDefinition('doctrine.dbal.idle_connection_middleware');
  1054. foreach ($connWithTtl as $connName) {
  1055. $idleConnectionMiddlewareAbstractDef
  1056. ->addTag('doctrine.middleware', ['connection' => $connName, 'priority' => 10]);
  1057. }
  1058. }
  1059. }