DoctrineExtension.php 45 KB

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