PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php

https://bitbucket.org/arturoblack/tomoyo
PHP | 398 lines | 262 code | 29 blank | 107 comment | 24 complexity | afa575df1458703256edeba96c78d041 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause, Apache-2.0, LGPL-2.1, CC-BY-3.0, LGPL-3.0
  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\HttpKernel\DependencyInjection\Extension;
  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\Config\Resource\FileResource;
  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. * @var array
  28. */
  29. protected $aliasMap = array();
  30. /**
  31. * Used inside metadata driver method to simplify aggregation of data.
  32. *
  33. * @var array
  34. */
  35. protected $drivers = array();
  36. /**
  37. * @param array $objectManager A configured object manager.
  38. * @param ContainerBuilder $container A ContainerBuilder instance
  39. */
  40. protected function loadMappingInformation(array $objectManager, ContainerBuilder $container)
  41. {
  42. if ($objectManager['auto_mapping']) {
  43. // automatically register bundle mappings
  44. foreach (array_keys($container->getParameter('kernel.bundles')) as $bundle) {
  45. if (!isset($objectManager['mappings'][$bundle])) {
  46. $objectManager['mappings'][$bundle] = null;
  47. }
  48. }
  49. }
  50. foreach ($objectManager['mappings'] as $mappingName => $mappingConfig) {
  51. if (null !== $mappingConfig && false === $mappingConfig['mapping']) {
  52. continue;
  53. }
  54. $mappingConfig = array_replace(array(
  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. foreach ($container->getParameter('kernel.bundles') as $name => $class) {
  67. if ($mappingName === $name) {
  68. $bundle = new \ReflectionClass($class);
  69. break;
  70. }
  71. }
  72. if (null === $bundle) {
  73. throw new \InvalidArgumentException(sprintf('Bundle "%s" does not exist or it is not enabled.', $mappingName));
  74. }
  75. $mappingConfig = $this->getMappingDriverBundleConfigDefaults($mappingConfig, $bundle, $container);
  76. if (!$mappingConfig) {
  77. continue;
  78. }
  79. }
  80. $this->assertValidMappingConfiguration($mappingConfig, $objectManager['name']);
  81. $this->setMappingDriverConfig($mappingConfig, $mappingName);
  82. $this->setMappingDriverAlias($mappingConfig, $mappingName);
  83. }
  84. }
  85. /**
  86. * Register the alias for this mapping driver.
  87. *
  88. * Aliases can be used in the Query languages of all the Doctrine object managers to simplify writing tasks.
  89. *
  90. * @param array $mappingConfig
  91. * @param string $mappingName
  92. */
  93. protected function setMappingDriverAlias($mappingConfig, $mappingName)
  94. {
  95. if (isset($mappingConfig['alias'])) {
  96. $this->aliasMap[$mappingConfig['alias']] = $mappingConfig['prefix'];
  97. } else {
  98. $this->aliasMap[$mappingName] = $mappingConfig['prefix'];
  99. }
  100. }
  101. /**
  102. * Register the mapping driver configuration for later use with the object managers metadata driver chain.
  103. *
  104. * @param array $mappingConfig
  105. * @param string $mappingName
  106. */
  107. protected function setMappingDriverConfig(array $mappingConfig, $mappingName)
  108. {
  109. if (is_dir($mappingConfig['dir'])) {
  110. $this->drivers[$mappingConfig['type']][$mappingConfig['prefix']] = realpath($mappingConfig['dir']);
  111. } else {
  112. throw new \InvalidArgumentException(sprintf('Invalid Doctrine mapping path given. Cannot load Doctrine mapping/bundle named "%s".', $mappingName));
  113. }
  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. * @param array $bundleConfig
  121. * @param \ReflectionClass $bundle
  122. * @param ContainerBuilder $container A ContainerBuilder instance
  123. *
  124. * @return array|false
  125. */
  126. protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \ReflectionClass $bundle, ContainerBuilder $container)
  127. {
  128. $bundleDir = dirname($bundle->getFilename());
  129. if (!$bundleConfig['type']) {
  130. $bundleConfig['type'] = $this->detectMetadataDriver($bundleDir, $container);
  131. }
  132. if (!$bundleConfig['type']) {
  133. // skip this bundle, no mapping information was found.
  134. return false;
  135. }
  136. if (!$bundleConfig['dir']) {
  137. if (in_array($bundleConfig['type'], array('annotation', 'staticphp'))) {
  138. $bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingObjectDefaultName();
  139. } else {
  140. $bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingResourceConfigDirectory();
  141. }
  142. } else {
  143. $bundleConfig['dir'] = $bundleDir.'/'.$bundleConfig['dir'];
  144. }
  145. if (!$bundleConfig['prefix']) {
  146. $bundleConfig['prefix'] = $bundle->getNamespaceName().'\\'.$this->getMappingObjectDefaultName();
  147. }
  148. return $bundleConfig;
  149. }
  150. /**
  151. * Register all the collected mapping information with the object manager by registering the appropriate mapping drivers.
  152. *
  153. * @param array $objectManager
  154. * @param ContainerBuilder $container A ContainerBuilder instance
  155. */
  156. protected function registerMappingDrivers($objectManager, ContainerBuilder $container)
  157. {
  158. // configure metadata driver for each bundle based on the type of mapping files found
  159. if ($container->hasDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'))) {
  160. $chainDriverDef = $container->getDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'));
  161. } else {
  162. $chainDriverDef = new Definition('%'.$this->getObjectManagerElementName('metadata.driver_chain.class%'));
  163. $chainDriverDef->setPublic(false);
  164. }
  165. foreach ($this->drivers as $driverType => $driverPaths) {
  166. $mappingService = $this->getObjectManagerElementName($objectManager['name'].'_'.$driverType.'_metadata_driver');
  167. if ($container->hasDefinition($mappingService)) {
  168. $mappingDriverDef = $container->getDefinition($mappingService);
  169. $args = $mappingDriverDef->getArguments();
  170. if ($driverType == 'annotation') {
  171. $args[1] = array_merge(array_values($driverPaths), $args[1]);
  172. } else {
  173. $args[0] = array_merge(array_values($driverPaths), $args[0]);
  174. }
  175. $mappingDriverDef->setArguments($args);
  176. } elseif ($driverType == 'annotation') {
  177. $mappingDriverDef = new Definition('%'.$this->getObjectManagerElementName('metadata.'.$driverType.'.class%'), array(
  178. new Reference($this->getObjectManagerElementName('metadata.annotation_reader')),
  179. array_values($driverPaths)
  180. ));
  181. } else {
  182. $mappingDriverDef = new Definition('%'.$this->getObjectManagerElementName('metadata.'.$driverType.'.class%'), array(
  183. array_values($driverPaths)
  184. ));
  185. }
  186. $mappingDriverDef->setPublic(false);
  187. if (false !== strpos($mappingDriverDef->getClass(), 'yml') || false !== strpos($mappingDriverDef->getClass(), 'xml')) {
  188. $mappingDriverDef->setArguments(array(array_flip($driverPaths)));
  189. $mappingDriverDef->addMethodCall('setGlobalBasename', array('mapping'));
  190. }
  191. $container->setDefinition($mappingService, $mappingDriverDef);
  192. foreach ($driverPaths as $prefix => $driverPath) {
  193. $chainDriverDef->addMethodCall('addDriver', array(new Reference($mappingService), $prefix));
  194. }
  195. }
  196. $container->setDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'), $chainDriverDef);
  197. }
  198. /**
  199. * Assertion if the specified mapping information is valid.
  200. *
  201. * @param array $mappingConfig
  202. * @param string $objectManagerName
  203. */
  204. protected function assertValidMappingConfiguration(array $mappingConfig, $objectManagerName)
  205. {
  206. if (!$mappingConfig['type'] || !$mappingConfig['dir'] || !$mappingConfig['prefix']) {
  207. throw new \InvalidArgumentException(sprintf('Mapping definitions for Doctrine manager "%s" require at least the "type", "dir" and "prefix" options.', $objectManagerName));
  208. }
  209. if (!is_dir($mappingConfig['dir'])) {
  210. throw new \InvalidArgumentException(sprintf('Specified non-existing directory "%s" as Doctrine mapping source.', $mappingConfig['dir']));
  211. }
  212. if (!in_array($mappingConfig['type'], array('xml', 'yml', 'annotation', 'php', 'staticphp'))) {
  213. throw new \InvalidArgumentException(sprintf('Can only configure "xml", "yml", "annotation", "php" or '.
  214. '"staticphp" through the DoctrineBundle. Use your own bundle to configure other metadata drivers. '.
  215. 'You can register them by adding a a new driver to the '.
  216. '"%s" service definition.', $this->getObjectManagerElementName($objectManagerName.'.metadata_driver')
  217. ));
  218. }
  219. }
  220. /**
  221. * Detects what metadata driver to use for the supplied directory.
  222. *
  223. * @param string $dir A directory path
  224. * @param ContainerBuilder $container A ContainerBuilder instance
  225. *
  226. * @return string|null A metadata driver short name, if one can be detected
  227. */
  228. protected function detectMetadataDriver($dir, ContainerBuilder $container)
  229. {
  230. // add the closest existing directory as a resource
  231. $configPath = $this->getMappingResourceConfigDirectory();
  232. $resource = $dir.'/'.$configPath;
  233. while (!is_dir($resource)) {
  234. $resource = dirname($resource);
  235. }
  236. $container->addResource(new FileResource($resource));
  237. $extension = $this->getMappingResourceExtension();
  238. if (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.xml')) && count($files)) {
  239. return 'xml';
  240. } elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.yml')) && count($files)) {
  241. return 'yml';
  242. } elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.php')) && count($files)) {
  243. return 'php';
  244. }
  245. // add the directory itself as a resource
  246. $container->addResource(new FileResource($dir));
  247. if (is_dir($dir.'/'.$this->getMappingObjectDefaultName())) {
  248. return 'annotation';
  249. }
  250. return null;
  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. $cacheDriver = $objectManager[$cacheName.'_driver'];
  264. $cacheDriverService = $this->getObjectManagerElementName($objectManager['name'] . '_' . $cacheName);
  265. switch ($cacheDriver['type']) {
  266. case 'service':
  267. $container->setAlias($cacheDriverService, new Alias($cacheDriver['id'], false));
  268. return;
  269. case 'memcache':
  270. $memcacheClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.memcache.class').'%';
  271. $memcacheInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.memcache_instance.class').'%';
  272. $memcacheHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.memcache_host').'%';
  273. $memcachePort = !empty($cacheDriver['port']) || (isset($cacheDriver['port']) && $cacheDriver['port'] === 0) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.memcache_port').'%';
  274. $cacheDef = new Definition($memcacheClass);
  275. $memcacheInstance = new Definition($memcacheInstanceClass);
  276. $memcacheInstance->addMethodCall('connect', array(
  277. $memcacheHost, $memcachePort
  278. ));
  279. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_memcache_instance', $objectManager['name'])), $memcacheInstance);
  280. $cacheDef->addMethodCall('setMemcache', array(new Reference($this->getObjectManagerElementName(sprintf('%s_memcache_instance', $objectManager['name'])))));
  281. break;
  282. case 'memcached':
  283. $memcachedClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.memcached.class').'%';
  284. $memcachedInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.memcached_instance.class').'%';
  285. $memcachedHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.memcached_host').'%';
  286. $memcachedPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.memcached_port').'%';
  287. $cacheDef = new Definition($memcachedClass);
  288. $memcachedInstance = new Definition($memcachedInstanceClass);
  289. $memcachedInstance->addMethodCall('addServer', array(
  290. $memcachedHost, $memcachedPort
  291. ));
  292. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManager['name'])), $memcachedInstance);
  293. $cacheDef->addMethodCall('setMemcached', array(new Reference($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManager['name'])))));
  294. break;
  295. case 'redis':
  296. $redisClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.redis.class').'%';
  297. $redisInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.redis_instance.class').'%';
  298. $redisHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.redis_host').'%';
  299. $redisPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.redis_port').'%';
  300. $cacheDef = new Definition($redisClass);
  301. $redisInstance = new Definition($redisInstanceClass);
  302. $redisInstance->addMethodCall('connect', array(
  303. $redisHost, $redisPort
  304. ));
  305. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManager['name'])), $redisInstance);
  306. $cacheDef->addMethodCall('setRedis', array(new Reference($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManager['name'])))));
  307. break;
  308. case 'apc':
  309. case 'array':
  310. case 'xcache':
  311. case 'wincache':
  312. case 'zenddata':
  313. $cacheDef = new Definition('%'.$this->getObjectManagerElementName(sprintf('cache.%s.class', $cacheDriver['type'])).'%');
  314. break;
  315. default:
  316. throw new \InvalidArgumentException(sprintf('"%s" is an unrecognized Doctrine cache driver.', $cacheDriver['type']));
  317. }
  318. $cacheDef->setPublic(false);
  319. // generate a unique namespace for the given application
  320. $namespace = 'sf2'.$this->getMappingResourceExtension().'_'.$objectManager['name'].'_'.md5($container->getParameter('kernel.root_dir').$container->getParameter('kernel.environment'));
  321. $cacheDef->addMethodCall('setNamespace', array($namespace));
  322. $container->setDefinition($cacheDriverService, $cacheDef);
  323. }
  324. /**
  325. * Prefixes the relative dependency injection container path with the object manager prefix.
  326. *
  327. * @example $name is 'entity_manager' then the result would be 'doctrine.orm.entity_manager'
  328. *
  329. * @param string $name
  330. * @return string
  331. */
  332. abstract protected function getObjectManagerElementName($name);
  333. /**
  334. * Noun that describes the mapped objects such as Entity or Document.
  335. *
  336. * Will be used for autodetection of persistent objects directory.
  337. *
  338. * @return string
  339. */
  340. abstract protected function getMappingObjectDefaultName();
  341. /**
  342. * Relative path from the bundle root to the directory where mapping files reside.
  343. *
  344. * @return string
  345. */
  346. abstract protected function getMappingResourceConfigDirectory();
  347. /**
  348. * Extension used by the mapping files.
  349. *
  350. * @return string
  351. */
  352. abstract protected function getMappingResourceExtension();
  353. }