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

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