PageRenderTime 35ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/gencer/symfony
PHP | 432 lines | 276 code | 34 blank | 122 comment | 25 complexity | 233b8fb2134dd7b2ff0d4726328d72a7 MD5 | raw file
  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. }
  260. /**
  261. * Loads a configured object manager metadata, query or result cache driver.
  262. *
  263. * @param array $objectManager A configured object manager.
  264. * @param ContainerBuilder $container A ContainerBuilder instance.
  265. * @param string $cacheName
  266. *
  267. * @throws \InvalidArgumentException In case of unknown driver type.
  268. */
  269. protected function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName)
  270. {
  271. $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName.'_driver'], $container);
  272. }
  273. /**
  274. * Loads a cache driver.
  275. *
  276. * @param string $cacheDriverServiceId The cache driver name.
  277. * @param string $objectManagerName The object manager name.
  278. * @param array $cacheDriver The cache driver mapping.
  279. * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container The ContainerBuilder instance.
  280. *
  281. * @return string
  282. *
  283. * @throws \InvalidArgumentException
  284. */
  285. protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheDriver, ContainerBuilder $container)
  286. {
  287. $cacheDriverServiceId = $this->getObjectManagerElementName($objectManagerName . '_' . $cacheName);
  288. switch ($cacheDriver['type']) {
  289. case 'service':
  290. $container->setAlias($cacheDriverServiceId, new Alias($cacheDriver['id'], false));
  291. return $cacheDriverServiceId;
  292. case 'memcache':
  293. $memcacheClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.memcache.class').'%';
  294. $memcacheInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.memcache_instance.class').'%';
  295. $memcacheHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.memcache_host').'%';
  296. $memcachePort = !empty($cacheDriver['port']) || (isset($cacheDriver['port']) && $cacheDriver['port'] === 0) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.memcache_port').'%';
  297. $cacheDef = new Definition($memcacheClass);
  298. $memcacheInstance = new Definition($memcacheInstanceClass);
  299. $memcacheInstance->addMethodCall('connect', array(
  300. $memcacheHost, $memcachePort
  301. ));
  302. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_memcache_instance', $objectManagerName)), $memcacheInstance);
  303. $cacheDef->addMethodCall('setMemcache', array(new Reference($this->getObjectManagerElementName(sprintf('%s_memcache_instance', $objectManagerName)))));
  304. break;
  305. case 'memcached':
  306. $memcachedClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.memcached.class').'%';
  307. $memcachedInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.memcached_instance.class').'%';
  308. $memcachedHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.memcached_host').'%';
  309. $memcachedPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.memcached_port').'%';
  310. $cacheDef = new Definition($memcachedClass);
  311. $memcachedInstance = new Definition($memcachedInstanceClass);
  312. $memcachedInstance->addMethodCall('addServer', array(
  313. $memcachedHost, $memcachedPort
  314. ));
  315. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManagerName)), $memcachedInstance);
  316. $cacheDef->addMethodCall('setMemcached', array(new Reference($this->getObjectManagerElementName(sprintf('%s_memcached_instance', $objectManagerName)))));
  317. break;
  318. case 'redis':
  319. $redisClass = !empty($cacheDriver['class']) ? $cacheDriver['class'] : '%'.$this->getObjectManagerElementName('cache.redis.class').'%';
  320. $redisInstanceClass = !empty($cacheDriver['instance_class']) ? $cacheDriver['instance_class'] : '%'.$this->getObjectManagerElementName('cache.redis_instance.class').'%';
  321. $redisHost = !empty($cacheDriver['host']) ? $cacheDriver['host'] : '%'.$this->getObjectManagerElementName('cache.redis_host').'%';
  322. $redisPort = !empty($cacheDriver['port']) ? $cacheDriver['port'] : '%'.$this->getObjectManagerElementName('cache.redis_port').'%';
  323. $cacheDef = new Definition($redisClass);
  324. $redisInstance = new Definition($redisInstanceClass);
  325. $redisInstance->addMethodCall('connect', array(
  326. $redisHost, $redisPort
  327. ));
  328. $container->setDefinition($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManagerName)), $redisInstance);
  329. $cacheDef->addMethodCall('setRedis', array(new Reference($this->getObjectManagerElementName(sprintf('%s_redis_instance', $objectManagerName)))));
  330. break;
  331. case 'apc':
  332. case 'array':
  333. case 'xcache':
  334. case 'wincache':
  335. case 'zenddata':
  336. $cacheDef = new Definition('%'.$this->getObjectManagerElementName(sprintf('cache.%s.class', $cacheDriver['type'])).'%');
  337. break;
  338. default:
  339. throw new \InvalidArgumentException(sprintf('"%s" is an unrecognized Doctrine cache driver.', $cacheDriver['type']));
  340. }
  341. $cacheDef->setPublic(false);
  342. if (!isset($cacheDriver['namespace'])) {
  343. // generate a unique namespace for the given application
  344. $env = $container->getParameter('kernel.root_dir').$container->getParameter('kernel.environment');
  345. $hash = hash('sha256', $env);
  346. $namespace = 'sf2'.$this->getMappingResourceExtension().'_'.$objectManagerName.'_'.$hash;
  347. $cacheDriver['namespace'] = $namespace;
  348. }
  349. $cacheDef->addMethodCall('setNamespace', array($cacheDriver['namespace']));
  350. $container->setDefinition($cacheDriverServiceId, $cacheDef);
  351. return $cacheDriverServiceId;
  352. }
  353. /**
  354. * Prefixes the relative dependency injection container path with the object manager prefix.
  355. *
  356. * @example $name is 'entity_manager' then the result would be 'doctrine.orm.entity_manager'
  357. *
  358. * @param string $name
  359. *
  360. * @return string
  361. */
  362. abstract protected function getObjectManagerElementName($name);
  363. /**
  364. * Noun that describes the mapped objects such as Entity or Document.
  365. *
  366. * Will be used for autodetection of persistent objects directory.
  367. *
  368. * @return string
  369. */
  370. abstract protected function getMappingObjectDefaultName();
  371. /**
  372. * Relative path from the bundle root to the directory where mapping files reside.
  373. *
  374. * @return string
  375. */
  376. abstract protected function getMappingResourceConfigDirectory();
  377. /**
  378. * Extension used by the mapping files.
  379. *
  380. * @return string
  381. */
  382. abstract protected function getMappingResourceExtension();
  383. }