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

/src/Symfony/Component/DependencyInjection/Container.php

https://github.com/Exercise/symfony
PHP | 455 lines | 190 code | 51 blank | 214 comment | 24 complexity | 8a12be7d0c0e246dfb81ba16100f5f79 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\Component\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  12. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  13. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  14. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  17. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  18. /**
  19. * Container is a dependency injection container.
  20. *
  21. * It gives access to object instances (services).
  22. *
  23. * Services and parameters are simple key/pair stores.
  24. *
  25. * Parameter and service keys are case insensitive.
  26. *
  27. * A service id can contain lowercased letters, digits, underscores, and dots.
  28. * Underscores are used to separate words, and dots to group services
  29. * under namespaces:
  30. *
  31. * <ul>
  32. * <li>request</li>
  33. * <li>mysql_session_storage</li>
  34. * <li>symfony.mysql_session_storage</li>
  35. * </ul>
  36. *
  37. * A service can also be defined by creating a method named
  38. * getXXXService(), where XXX is the camelized version of the id:
  39. *
  40. * <ul>
  41. * <li>request -> getRequestService()</li>
  42. * <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
  43. * <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
  44. * </ul>
  45. *
  46. * The container can have three possible behaviors when a service does not exist:
  47. *
  48. * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  49. * * NULL_ON_INVALID_REFERENCE: Returns null
  50. * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
  51. * (for instance, ignore a setter if the service does not exist)
  52. *
  53. * @author Fabien Potencier <fabien@symfony.com>
  54. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  55. *
  56. * @api
  57. */
  58. class Container implements ContainerInterface
  59. {
  60. protected $parameterBag;
  61. protected $services;
  62. protected $scopes;
  63. protected $scopeChildren;
  64. protected $scopedServices;
  65. protected $scopeStacks;
  66. protected $loading = array();
  67. /**
  68. * Constructor.
  69. *
  70. * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
  71. *
  72. * @api
  73. */
  74. public function __construct(ParameterBagInterface $parameterBag = null)
  75. {
  76. $this->parameterBag = null === $parameterBag ? new ParameterBag() : $parameterBag;
  77. $this->services = array();
  78. $this->scopes = array();
  79. $this->scopeChildren = array();
  80. $this->scopedServices = array();
  81. $this->scopeStacks = array();
  82. $this->set('service_container', $this);
  83. }
  84. /**
  85. * Compiles the container.
  86. *
  87. * This method does two things:
  88. *
  89. * * Parameter values are resolved;
  90. * * The parameter bag is frozen.
  91. *
  92. * @api
  93. */
  94. public function compile()
  95. {
  96. $this->parameterBag->resolve();
  97. $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  98. }
  99. /**
  100. * Returns true if the container parameter bag are frozen.
  101. *
  102. * @return Boolean true if the container parameter bag are frozen, false otherwise
  103. *
  104. * @api
  105. */
  106. public function isFrozen()
  107. {
  108. return $this->parameterBag instanceof FrozenParameterBag;
  109. }
  110. /**
  111. * Gets the service container parameter bag.
  112. *
  113. * @return ParameterBagInterface A ParameterBagInterface instance
  114. *
  115. * @api
  116. */
  117. public function getParameterBag()
  118. {
  119. return $this->parameterBag;
  120. }
  121. /**
  122. * Gets a parameter.
  123. *
  124. * @param string $name The parameter name
  125. *
  126. * @return mixed The parameter value
  127. *
  128. * @throws InvalidArgumentException if the parameter is not defined
  129. *
  130. * @api
  131. */
  132. public function getParameter($name)
  133. {
  134. return $this->parameterBag->get($name);
  135. }
  136. /**
  137. * Checks if a parameter exists.
  138. *
  139. * @param string $name The parameter name
  140. *
  141. * @return Boolean The presence of parameter in container
  142. *
  143. * @api
  144. */
  145. public function hasParameter($name)
  146. {
  147. return $this->parameterBag->has($name);
  148. }
  149. /**
  150. * Sets a parameter.
  151. *
  152. * @param string $name The parameter name
  153. * @param mixed $value The parameter value
  154. *
  155. * @api
  156. */
  157. public function setParameter($name, $value)
  158. {
  159. $this->parameterBag->set($name, $value);
  160. }
  161. /**
  162. * Sets a service.
  163. *
  164. * @param string $id The service identifier
  165. * @param object $service The service instance
  166. * @param string $scope The scope of the service
  167. *
  168. * @api
  169. */
  170. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  171. {
  172. if (self::SCOPE_PROTOTYPE === $scope) {
  173. throw new InvalidArgumentException('You cannot set services of scope "prototype".');
  174. }
  175. $id = strtolower($id);
  176. if (self::SCOPE_CONTAINER !== $scope) {
  177. if (!isset($this->scopedServices[$scope])) {
  178. throw new RuntimeException('You cannot set services of inactive scopes.');
  179. }
  180. $this->scopedServices[$scope][$id] = $service;
  181. }
  182. $this->services[$id] = $service;
  183. }
  184. /**
  185. * Returns true if the given service is defined.
  186. *
  187. * @param string $id The service identifier
  188. *
  189. * @return Boolean true if the service is defined, false otherwise
  190. *
  191. * @api
  192. */
  193. public function has($id)
  194. {
  195. $id = strtolower($id);
  196. return isset($this->services[$id]) || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service');
  197. }
  198. /**
  199. * Gets a service.
  200. *
  201. * If a service is both defined through a set() method and
  202. * with a set*Service() method, the former has always precedence.
  203. *
  204. * @param string $id The service identifier
  205. * @param integer $invalidBehavior The behavior when the service does not exist
  206. *
  207. * @return object The associated service
  208. *
  209. * @throws InvalidArgumentException if the service is not defined
  210. *
  211. * @see Reference
  212. *
  213. * @api
  214. */
  215. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  216. {
  217. $id = strtolower($id);
  218. if (isset($this->services[$id])) {
  219. return $this->services[$id];
  220. }
  221. if (isset($this->loading[$id])) {
  222. throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  223. }
  224. if (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  225. $this->loading[$id] = true;
  226. try {
  227. $service = $this->$method();
  228. } catch (\Exception $e) {
  229. unset($this->loading[$id]);
  230. throw $e;
  231. }
  232. unset($this->loading[$id]);
  233. return $service;
  234. }
  235. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  236. throw new ServiceNotFoundException($id);
  237. }
  238. }
  239. /**
  240. * Gets all service ids.
  241. *
  242. * @return array An array of all defined service ids
  243. */
  244. public function getServiceIds()
  245. {
  246. $ids = array();
  247. $r = new \ReflectionClass($this);
  248. foreach ($r->getMethods() as $method) {
  249. if (preg_match('/^get(.+)Service$/', $method->getName(), $match)) {
  250. $ids[] = self::underscore($match[1]);
  251. }
  252. }
  253. return array_unique(array_merge($ids, array_keys($this->services)));
  254. }
  255. /**
  256. * This is called when you enter a scope
  257. *
  258. * @param string $name
  259. *
  260. * @api
  261. */
  262. public function enterScope($name)
  263. {
  264. if (!isset($this->scopes[$name])) {
  265. throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
  266. }
  267. if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) {
  268. throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name]));
  269. }
  270. // check if a scope of this name is already active, if so we need to
  271. // remove all services of this scope, and those of any of its child
  272. // scopes from the global services map
  273. if (isset($this->scopedServices[$name])) {
  274. $services = array($this->services, $name => $this->scopedServices[$name]);
  275. unset($this->scopedServices[$name]);
  276. foreach ($this->scopeChildren[$name] as $child) {
  277. $services[$child] = $this->scopedServices[$child];
  278. unset($this->scopedServices[$child]);
  279. }
  280. // update global map
  281. $this->services = call_user_func_array('array_diff_key', $services);
  282. array_shift($services);
  283. // add stack entry for this scope so we can restore the removed services later
  284. if (!isset($this->scopeStacks[$name])) {
  285. $this->scopeStacks[$name] = new \SplStack();
  286. }
  287. $this->scopeStacks[$name]->push($services);
  288. }
  289. $this->scopedServices[$name] = array();
  290. }
  291. /**
  292. * This is called to leave the current scope, and move back to the parent
  293. * scope.
  294. *
  295. * @param string $name The name of the scope to leave
  296. *
  297. * @throws InvalidArgumentException if the scope is not active
  298. *
  299. * @api
  300. */
  301. public function leaveScope($name)
  302. {
  303. if (!isset($this->scopedServices[$name])) {
  304. throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
  305. }
  306. // remove all services of this scope, or any of its child scopes from
  307. // the global service map
  308. $services = array($this->services, $this->scopedServices[$name]);
  309. unset($this->scopedServices[$name]);
  310. foreach ($this->scopeChildren[$name] as $child) {
  311. if (!isset($this->scopedServices[$child])) {
  312. continue;
  313. }
  314. $services[] = $this->scopedServices[$child];
  315. unset($this->scopedServices[$child]);
  316. }
  317. $this->services = call_user_func_array('array_diff_key', $services);
  318. // check if we need to restore services of a previous scope of this type
  319. if (isset($this->scopeStacks[$name]) && count($this->scopeStacks[$name]) > 0) {
  320. $services = $this->scopeStacks[$name]->pop();
  321. $this->scopedServices += $services;
  322. array_unshift($services, $this->services);
  323. $this->services = call_user_func_array('array_merge', $services);
  324. }
  325. }
  326. /**
  327. * Adds a scope to the container.
  328. *
  329. * @param ScopeInterface $scope
  330. *
  331. * @api
  332. */
  333. public function addScope(ScopeInterface $scope)
  334. {
  335. $name = $scope->getName();
  336. $parentScope = $scope->getParentName();
  337. if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) {
  338. throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
  339. }
  340. if (isset($this->scopes[$name])) {
  341. throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
  342. }
  343. if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) {
  344. throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
  345. }
  346. $this->scopes[$name] = $parentScope;
  347. $this->scopeChildren[$name] = array();
  348. // normalize the child relations
  349. while ($parentScope !== self::SCOPE_CONTAINER) {
  350. $this->scopeChildren[$parentScope][] = $name;
  351. $parentScope = $this->scopes[$parentScope];
  352. }
  353. }
  354. /**
  355. * Returns whether this container has a certain scope
  356. *
  357. * @param string $name The name of the scope
  358. *
  359. * @return Boolean
  360. *
  361. * @api
  362. */
  363. public function hasScope($name)
  364. {
  365. return isset($this->scopes[$name]);
  366. }
  367. /**
  368. * Returns whether this scope is currently active
  369. *
  370. * This does not actually check if the passed scope actually exists.
  371. *
  372. * @param string $name
  373. *
  374. * @return Boolean
  375. *
  376. * @api
  377. */
  378. public function isScopeActive($name)
  379. {
  380. return isset($this->scopedServices[$name]);
  381. }
  382. /**
  383. * Camelizes a string.
  384. *
  385. * @param string $id A string to camelize
  386. *
  387. * @return string The camelized string
  388. */
  389. static public function camelize($id)
  390. {
  391. return preg_replace_callback('/(^|_|\.)+(.)/', function ($match) { return ('.' === $match[1] ? '_' : '').strtoupper($match[2]); }, $id);
  392. }
  393. /**
  394. * A string to underscore.
  395. *
  396. * @param string $id The string to underscore
  397. *
  398. * @return string The underscored string
  399. */
  400. static public function underscore($id)
  401. {
  402. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  403. }
  404. }