PageRenderTime 36ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

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

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