PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

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

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