AbstractDoctrineExtension.php 21 KB

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