vendor/symfony/doctrine-bridge/DependencyInjection/AbstractDoctrineExtension.php line 433

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bridge\Doctrine\DependencyInjection;
  11. use Symfony\Component\Config\Resource\GlobResource;
  12. use Symfony\Component\DependencyInjection\Alias;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. use Symfony\Component\HttpKernel\DependencyInjection\Extension;
  17. /**
  18.  * This abstract classes groups common code that Doctrine Object Manager extensions (ORM, MongoDB, CouchDB) need.
  19.  *
  20.  * @author Benjamin Eberlei <kontakt@beberlei.de>
  21.  */
  22. abstract class AbstractDoctrineExtension extends Extension
  23. {
  24.     /**
  25.      * Used inside metadata driver method to simplify aggregation of data.
  26.      */
  27.     protected $aliasMap = [];
  28.     /**
  29.      * Used inside metadata driver method to simplify aggregation of data.
  30.      */
  31.     protected $drivers = [];
  32.     /**
  33.      * @param array $objectManager A configured object manager
  34.      *
  35.      * @throws \InvalidArgumentException
  36.      */
  37.     protected function loadMappingInformation(array $objectManager, ContainerBuilder $container)
  38.     {
  39.         if ($objectManager['auto_mapping']) {
  40.             // automatically register bundle mappings
  41.             foreach (array_keys($container->getParameter('kernel.bundles')) as $bundle) {
  42.                 if (!isset($objectManager['mappings'][$bundle])) {
  43.                     $objectManager['mappings'][$bundle] = [
  44.                         'mapping' => true,
  45.                         'is_bundle' => true,
  46.                     ];
  47.                 }
  48.             }
  49.         }
  50.         foreach ($objectManager['mappings'] as $mappingName => $mappingConfig) {
  51.             if (null !== $mappingConfig && false === $mappingConfig['mapping']) {
  52.                 continue;
  53.             }
  54.             $mappingConfig = array_replace([
  55.                 'dir' => false,
  56.                 'type' => false,
  57.                 'prefix' => false,
  58.             ], (array) $mappingConfig);
  59.             $mappingConfig['dir'] = $container->getParameterBag()->resolveValue($mappingConfig['dir']);
  60.             // a bundle configuration is detected by realizing that the specified dir is not absolute and existing
  61.             if (!isset($mappingConfig['is_bundle'])) {
  62.                 $mappingConfig['is_bundle'] = !is_dir($mappingConfig['dir']);
  63.             }
  64.             if ($mappingConfig['is_bundle']) {
  65.                 $bundle = null;
  66.                 $bundleMetadata = null;
  67.                 foreach ($container->getParameter('kernel.bundles') as $name => $class) {
  68.                     if ($mappingName === $name) {
  69.                         $bundle = new \ReflectionClass($class);
  70.                         $bundleMetadata = $container->getParameter('kernel.bundles_metadata')[$name];
  71.                         break;
  72.                     }
  73.                 }
  74.                 if (null === $bundle) {
  75.                     throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled.', $mappingName));
  76.                 }
  77.                 $mappingConfig = $this->getMappingDriverBundleConfigDefaults($mappingConfig, $bundle, $container, $bundleMetadata['path']);
  78.                 if (!$mappingConfig) {
  79.                     continue;
  80.                 }
  81.             } elseif (!$mappingConfig['type']) {
  82.                 $mappingConfig['type'] = $this->detectMappingType($mappingConfig['dir'], $container);
  83.             }
  84.             $this->assertValidMappingConfiguration($mappingConfig, $objectManager['name']);
  85.             $this->setMappingDriverConfig($mappingConfig, $mappingName);
  86.             $this->setMappingDriverAlias($mappingConfig, $mappingName);
  87.         }
  88.     }
  89.     /**
  90.      * Register the alias for this mapping driver.
  91.      *
  92.      * Aliases can be used in the Query languages of all the Doctrine object managers to simplify writing tasks.
  93.      */
  94.     protected function setMappingDriverAlias(array $mappingConfig, string $mappingName)
  95.     {
  96.         if (isset($mappingConfig['alias'])) {
  97.             $this->aliasMap[$mappingConfig['alias']] = $mappingConfig['prefix'];
  98.         } else {
  99.             $this->aliasMap[$mappingName] = $mappingConfig['prefix'];
  100.         }
  101.     }
  102.     /**
  103.      * Register the mapping driver configuration for later use with the object managers metadata driver chain.
  104.      *
  105.      * @throws \InvalidArgumentException
  106.      */
  107.     protected function setMappingDriverConfig(array $mappingConfig, string $mappingName)
  108.     {
  109.         $mappingDirectory = $mappingConfig['dir'];
  110.         if (!is_dir($mappingDirectory)) {
  111.             throw new \InvalidArgumentException(sprintf('Invalid Doctrine mapping path given. Cannot load Doctrine mapping/bundle named "%s".', $mappingName));
  112.         }
  113.         $this->drivers[$mappingConfig['type']][$mappingConfig['prefix']] = realpath($mappingDirectory) ?: $mappingDirectory;
  114.     }
  115.     /**
  116.      * If this is a bundle controlled mapping all the missing information can be autodetected by this method.
  117.      *
  118.      * Returns false when autodetection failed, an array of the completed information otherwise.
  119.      *
  120.      * @return array|false
  121.      */
  122.     protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \ReflectionClass $bundle, ContainerBuilder $container, string $bundleDir = null): array|false
  123.     {
  124.         $bundleDir ??= \dirname($bundle->getFileName());
  125.         if (!$bundleConfig['type']) {
  126.             $bundleConfig['type'] = $this->detectMetadataDriver($bundleDir, $container);
  127.         }
  128.         if (!$bundleConfig['type']) {
  129.             // skip this bundle, no mapping information was found.
  130.             return false;
  131.         }
  132.         if (!$bundleConfig['dir']) {
  133.             if (\in_array($bundleConfig['type'], ['annotation', 'staticphp', 'attribute'])) {
  134.                 $bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingObjectDefaultName();
  135.             } else {
  136.                 $bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingResourceConfigDirectory($bundleDir);
  137.             }
  138.         } else {
  139.             $bundleConfig['dir'] = $bundleDir.'/'.$bundleConfig['dir'];
  140.         }
  141.         if (!$bundleConfig['prefix']) {
  142.             $bundleConfig['prefix'] = $bundle->getNamespaceName().'\\'.$this->getMappingObjectDefaultName();
  143.         }
  144.         return $bundleConfig;
  145.     }
  146.     /**
  147.      * Register all the collected mapping information with the object manager by registering the appropriate mapping drivers.
  148.      */
  149.     protected function registerMappingDrivers(array $objectManager, ContainerBuilder $container)
  150.     {
  151.         // configure metadata driver for each bundle based on the type of mapping files found
  152.         if ($container->hasDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'))) {
  153.             $chainDriverDef = $container->getDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'));
  154.         } else {
  155.             $chainDriverDef = new Definition($this->getMetadataDriverClass('driver_chain'));
  156.             $chainDriverDef->setPublic(false);
  157.         }
  158.         foreach ($this->drivers as $driverType => $driverPaths) {
  159.             $mappingService = $this->getObjectManagerElementName($objectManager['name'].'_'.$driverType.'_metadata_driver');
  160.             if ($container->hasDefinition($mappingService)) {
  161.                 $mappingDriverDef = $container->getDefinition($mappingService);
  162.                 $args = $mappingDriverDef->getArguments();
  163.                 if ('annotation' == $driverType) {
  164.                     $args[1] = array_merge(array_values($driverPaths), $args[1]);
  165.                 } else {
  166.                     $args[0] = array_merge(array_values($driverPaths), $args[0]);
  167.                 }
  168.                 $mappingDriverDef->setArguments($args);
  169.             } elseif ('attribute' === $driverType) {
  170.                 $mappingDriverDef = new Definition($this->getMetadataDriverClass($driverType), [
  171.                     array_values($driverPaths),
  172.                 ]);
  173.             } elseif ('annotation' == $driverType) {
  174.                 $mappingDriverDef = new Definition($this->getMetadataDriverClass($driverType), [
  175.                     new Reference($this->getObjectManagerElementName('metadata.annotation_reader')),
  176.                     array_values($driverPaths),
  177.                 ]);
  178.             } else {
  179.                 $mappingDriverDef = new Definition($this->getMetadataDriverClass($driverType), [
  180.                     array_values($driverPaths),
  181.                 ]);
  182.             }
  183.             $mappingDriverDef->setPublic(false);
  184.             if (str_contains($mappingDriverDef->getClass(), 'yml') || str_contains($mappingDriverDef->getClass(), 'xml')) {
  185.                 $mappingDriverDef->setArguments([array_flip($driverPaths)]);
  186.                 $mappingDriverDef->addMethodCall('setGlobalBasename', ['mapping']);
  187.             }
  188.             $container->setDefinition($mappingService, $mappingDriverDef);
  189.             foreach ($driverPaths as $prefix => $driverPath) {
  190.                 $chainDriverDef->addMethodCall('addDriver', [new Reference($mappingService), $prefix]);
  191.             }
  192.         }
  193.         $container->setDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'), $chainDriverDef);
  194.     }
  195.     /**
  196.      * Assertion if the specified mapping information is valid.
  197.      *
  198.      * @throws \InvalidArgumentException
  199.      */
  200.     protected function assertValidMappingConfiguration(array $mappingConfig, string $objectManagerName)
  201.     {
  202.         if (!$mappingConfig['type'] || !$mappingConfig['dir'] || !$mappingConfig['prefix']) {
  203.             throw new \InvalidArgumentException(sprintf('Mapping definitions for Doctrine manager "%s" require at least the "type", "dir" and "prefix" options.', $objectManagerName));
  204.         }
  205.         if (!is_dir($mappingConfig['dir'])) {
  206.             throw new \InvalidArgumentException(sprintf('Specified non-existing directory "%s" as Doctrine mapping source.', $mappingConfig['dir']));
  207.         }
  208.         if (!\in_array($mappingConfig['type'], ['xml', 'yml', 'annotation', 'php', 'staticphp', 'attribute'])) {
  209.             throw new \InvalidArgumentException(sprintf('Can only configure "xml", "yml", "annotation", "php", "staticphp" or "attribute" through the DoctrineBundle. Use your own bundle to configure other metadata drivers. You can register them by adding a new driver to the "%s" service definition.', $this->getObjectManagerElementName($objectManagerName.'_metadata_driver')));
  210.         }
  211.     }
  212.     /**
  213.      * Detects what metadata driver to use for the supplied directory.
  214.      */
  215.     protected function detectMetadataDriver(string $dir, ContainerBuilder $container): ?string
  216.     {
  217.         $configPath = $this->getMappingResourceConfigDirectory($dir);
  218.         $extension = $this->getMappingResourceExtension();
  219.         if (glob($dir.'/'.$configPath.'/*.'.$extension.'.xml', \GLOB_NOSORT)) {
  220.             $driver = 'xml';
  221.         } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.yml', \GLOB_NOSORT)) {
  222.             $driver = 'yml';
  223.         } elseif (glob($dir.'/'.$configPath.'/*.'.$extension.'.php', \GLOB_NOSORT)) {
  224.             $driver = 'php';
  225.         } else {
  226.             // add the closest existing directory as a resource
  227.             $resource = $dir.'/'.$configPath;
  228.             while (!is_dir($resource)) {
  229.                 $resource = \dirname($resource);
  230.             }
  231.             $container->fileExists($resource, false);
  232.             if ($container->fileExists($dir.'/'.$this->getMappingObjectDefaultName(), false)) {
  233.                 return $this->detectMappingType($dir, $container);
  234.             }
  235.             return null;
  236.         }
  237.         $container->fileExists($dir.'/'.$configPath, false);
  238.         return $driver;
  239.     }
  240.     /**
  241.      * Detects what mapping type to use for the supplied directory.
  242.      *
  243.      * @return string A mapping type 'attribute' or 'annotation'
  244.      */
  245.     private function detectMappingType(string $directory, ContainerBuilder $container): string
  246.     {
  247.         $type = 'attribute';
  248.         $glob = new GlobResource($directory, '*', true);
  249.         $container->addResource($glob);
  250.         $quotedMappingObjectName = preg_quote($this->getMappingObjectDefaultName(), '/');
  251.         foreach ($glob as $file) {
  252.             $content = file_get_contents($file);
  253.             if (preg_match('/^#\[.*'.$quotedMappingObjectName.'\b/m', $content)) {
  254.                 break;
  255.             }
  256.             if (preg_match('/^ \* @.*'.$quotedMappingObjectName.'\b/m', $content)) {
  257.                 $type = 'annotation';
  258.                 break;
  259.             }
  260.         }
  261.         return $type;
  262.     }
  263.     /**
  264.      * Loads a configured object manager metadata, query or result cache driver.
  265.      *
  266.      * @throws \InvalidArgumentException in case of unknown driver type
  267.      */
  268.     protected function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, string $cacheName)
  269.     {
  270.         $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName.'_driver'], $container);
  271.     }
  272.     /**
  273.      * Loads a cache driver.
  274.      *
  275.      * @throws \InvalidArgumentException
  276.      */
  277.     protected function loadCacheDriver(string $cacheName, string $objectManagerName, array $cacheDriver, ContainerBuilder $container): string
  278.     {
  279.         $cacheDriverServiceId = $this->getObjectManagerElementName($objectManagerName.'_'.$cacheName);
  280.         switch ($cacheDriver['type']) {
  281.             case 'service':
  282.                 $container->setAlias($cacheDriverServiceId, new Alias($cacheDriver['id'], false));
  283.                 return $cacheDriverServiceId;
  284.             case 'memcached':
  285.                 $memcachedClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.memcached.class').'%';
  286.                 $memcachedInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.memcached_instance.class').'%';
  287.                 $memcachedHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.memcached_host').'%';
  288.                 $memcachedPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.memcached_port').'%';
  289.                 $cacheDef = new Definition($memcachedClass);
  290.                 $memcachedInstance = new Definition($memcachedInstanceClass);
  291.                 $memcachedInstance->addMethodCall('addServer', [
  292.                     $memcachedHost, $memcachedPort,
  293.                 ]);
  294.                 $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManagerName)), $memcachedInstance);
  295.                 $cacheDef->addMethodCall('setMemcached', [new Reference($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManagerName)))]);
  296.                 break;
  297.              case 'redis':
  298.                 $redisClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.redis.class').'%';
  299.                 $redisInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.redis_instance.class').'%';
  300.                 $redisHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.redis_host').'%';
  301.                 $redisPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.redis_port').'%';
  302.                 $cacheDef = new Definition($redisClass);
  303.                 $redisInstance = new Definition($redisInstanceClass);
  304.                 $redisInstance->addMethodCall('connect', [
  305.                     $redisHost, $redisPort,
  306.                 ]);
  307.                 $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManagerName)), $redisInstance);
  308.                 $cacheDef->addMethodCall('setRedis', [new Reference($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManagerName)))]);
  309.                 break;
  310.             case 'apc':
  311.             case 'apcu':
  312.             case 'array':
  313.             case 'xcache':
  314.             case 'wincache':
  315.             case 'zenddata':
  316.                 $cacheDef = new Definition('%'.$this->getObjectManagerElementName(sprintf('cache.%s.class', $cacheDriver['type'])).'%');
  317.                 break;
  318.             default:
  319.                 throw new \InvalidArgumentException(sprintf('"%s" is an unrecognized Doctrine cache driver.', $cacheDriver['type']));
  320.         }
  321.         $cacheDef->setPublic(false);
  322.         if (!isset($cacheDriver['namespace'])) {
  323.             // generate a unique namespace for the given application
  324.             if ($container->hasParameter('cache.prefix.seed')) {
  325.                 $seed = $container->getParameterBag()->resolveValue($container->getParameter('cache.prefix.seed'));
  326.             } else {
  327.                 $seed = '_'.$container->getParameter('kernel.project_dir');
  328.                 $seed .= '.'.$container->getParameter('kernel.container_class');
  329.             }
  330.             $namespace = 'sf_'.$this->getMappingResourceExtension().'_'.$objectManagerName.'_'.ContainerBuilder::hash($seed);
  331.             $cacheDriver['namespace'] = $namespace;
  332.         }
  333.         $cacheDef->addMethodCall('setNamespace', [$cacheDriver['namespace']]);
  334.         $container->setDefinition($cacheDriverServiceId, $cacheDef);
  335.         return $cacheDriverServiceId;
  336.     }
  337.     /**
  338.      * Returns a modified version of $managerConfigs.
  339.      *
  340.      * The manager called $autoMappedManager will map all bundles that are not mapped by other managers.
  341.      */
  342.     protected function fixManagersAutoMappings(array $managerConfigs, array $bundles): array
  343.     {
  344.         if ($autoMappedManager = $this->validateAutoMapping($managerConfigs)) {
  345.             foreach (array_keys($bundles) as $bundle) {
  346.                 foreach ($managerConfigs as $manager) {
  347.                     if (isset($manager['mappings'][$bundle])) {
  348.                         continue 2;
  349.                     }
  350.                 }
  351.                 $managerConfigs[$autoMappedManager]['mappings'][$bundle] = [
  352.                     'mapping' => true,
  353.                     'is_bundle' => true,
  354.                 ];
  355.             }
  356.             $managerConfigs[$autoMappedManager]['auto_mapping'] = false;
  357.         }
  358.         return $managerConfigs;
  359.     }
  360.     /**
  361.      * Prefixes the relative dependency injection container path with the object manager prefix.
  362.      *
  363.      * @example $name is 'entity_manager' then the result would be 'doctrine.orm.entity_manager'
  364.      */
  365.     abstract protected function getObjectManagerElementName(string $name): string;
  366.     /**
  367.      * Noun that describes the mapped objects such as Entity or Document.
  368.      *
  369.      * Will be used for autodetection of persistent objects directory.
  370.      */
  371.     abstract protected function getMappingObjectDefaultName(): string;
  372.     /**
  373.      * Relative path from the bundle root to the directory where mapping files reside.
  374.      */
  375.     abstract protected function getMappingResourceConfigDirectory(string $bundleDir = null): string;
  376.     /**
  377.      * Extension used by the mapping files.
  378.      */
  379.     abstract protected function getMappingResourceExtension(): string;
  380.     /**
  381.      * The class name used by the various mapping drivers.
  382.      */
  383.     abstract protected function getMetadataDriverClass(string $driverType): string;
  384.     /**
  385.      * Search for a manager that is declared as 'auto_mapping' = true.
  386.      *
  387.      * @throws \LogicException
  388.      */
  389.     private function validateAutoMapping(array $managerConfigs): ?string
  390.     {
  391.         $autoMappedManager = null;
  392.         foreach ($managerConfigs as $name => $manager) {
  393.             if (!$manager['auto_mapping']) {
  394.                 continue;
  395.             }
  396.             if (null !== $autoMappedManager) {
  397.                 throw new \LogicException(sprintf('You cannot enable "auto_mapping" on more than one manager at the same time (found in "%s" and "%s"").', $autoMappedManager, $name));
  398.             }
  399.             $autoMappedManager = $name;
  400.         }
  401.         return $autoMappedManager;
  402.     }
  403. }