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

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

https://github.com/djae138/symfony
PHP | 549 lines | 244 code | 62 blank | 243 comment | 42 complexity | a3862f5ffaac7635a4d1e10fb6d22ba5 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\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. * Setting a service to null resets the service: has() returns false and get()
  172. * behaves in the same way as if the service was never created.
  173. *
  174. * @param string $id The service identifier
  175. * @param object $service The service instance
  176. * @param string $scope The scope of the service
  177. *
  178. * @throws RuntimeException When trying to set a service in an inactive scope
  179. * @throws InvalidArgumentException When trying to set a service in the prototype scope
  180. *
  181. * @api
  182. */
  183. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  184. {
  185. if (self::SCOPE_PROTOTYPE === $scope) {
  186. throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id));
  187. }
  188. $id = strtolower($id);
  189. if (self::SCOPE_CONTAINER !== $scope) {
  190. if (!isset($this->scopedServices[$scope])) {
  191. throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id));
  192. }
  193. $this->scopedServices[$scope][$id] = $service;
  194. }
  195. $this->services[$id] = $service;
  196. if (method_exists($this, $method = 'synchronize'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  197. $this->$method();
  198. }
  199. if (self::SCOPE_CONTAINER !== $scope && null === $service) {
  200. unset($this->scopedServices[$scope][$id]);
  201. }
  202. if (null === $service) {
  203. unset($this->services[$id]);
  204. }
  205. }
  206. /**
  207. * Returns true if the given service is defined.
  208. *
  209. * @param string $id The service identifier
  210. *
  211. * @return Boolean true if the service is defined, false otherwise
  212. *
  213. * @api
  214. */
  215. public function has($id)
  216. {
  217. $id = strtolower($id);
  218. return isset($this->services[$id])
  219. || array_key_exists($id, $this->services)
  220. || isset($this->aliases[$id])
  221. || method_exists($this, 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')
  222. ;
  223. }
  224. /**
  225. * Gets a service.
  226. *
  227. * If a service is defined both through a set() method and
  228. * with a get{$id}Service() method, the former has always precedence.
  229. *
  230. * @param string $id The service identifier
  231. * @param integer $invalidBehavior The behavior when the service does not exist
  232. *
  233. * @return object The associated service
  234. *
  235. * @throws InvalidArgumentException if the service is not defined
  236. * @throws ServiceCircularReferenceException When a circular reference is detected
  237. * @throws ServiceNotFoundException When the service is not defined
  238. *
  239. * @see Reference
  240. *
  241. * @api
  242. */
  243. public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
  244. {
  245. // Attempt to retrieve the service by checking first aliases then
  246. // available services. Service IDs are case insensitive, however since
  247. // this method can be called thousands of times during a request, avoid
  248. // calling strotolower() unless necessary.
  249. foreach (array(false, true) as $strtolower) {
  250. if ($strtolower) {
  251. $id = strtolower($id);
  252. }
  253. if (isset($this->aliases[$id])) {
  254. $id = $this->aliases[$id];
  255. }
  256. // Re-use shared service instance if it exists.
  257. if (isset($this->services[$id]) || array_key_exists($id, $this->services)) {
  258. return $this->services[$id];
  259. }
  260. }
  261. if (isset($this->loading[$id])) {
  262. throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  263. }
  264. if (isset($this->methodMap[$id])) {
  265. $method = $this->methodMap[$id];
  266. } elseif (method_exists($this, $method = 'get'.strtr($id, array('_' => '', '.' => '_')).'Service')) {
  267. // $method is set to the right value, proceed
  268. } else {
  269. if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  270. if (!$id) {
  271. throw new ServiceNotFoundException($id);
  272. }
  273. $alternatives = array();
  274. foreach (array_keys($this->services) as $key) {
  275. $lev = levenshtein($id, $key);
  276. if ($lev <= strlen($id) / 3 || false !== strpos($key, $id)) {
  277. $alternatives[] = $key;
  278. }
  279. }
  280. throw new ServiceNotFoundException($id, null, null, $alternatives);
  281. }
  282. return null;
  283. }
  284. $this->loading[$id] = true;
  285. try {
  286. $service = $this->$method();
  287. } catch (\Exception $e) {
  288. unset($this->loading[$id]);
  289. if (array_key_exists($id, $this->services)) {
  290. unset($this->services[$id]);
  291. }
  292. if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  293. return null;
  294. }
  295. throw $e;
  296. }
  297. unset($this->loading[$id]);
  298. return $service;
  299. }
  300. /**
  301. * Returns true if the given service has actually been initialized
  302. *
  303. * @param string $id The service identifier
  304. *
  305. * @return Boolean true if service has already been initialized, false otherwise
  306. */
  307. public function initialized($id)
  308. {
  309. $id = strtolower($id);
  310. return isset($this->services[$id]) || array_key_exists($id, $this->services);
  311. }
  312. /**
  313. * Gets all service ids.
  314. *
  315. * @return array An array of all defined service ids
  316. */
  317. public function getServiceIds()
  318. {
  319. $ids = array();
  320. $r = new \ReflectionClass($this);
  321. foreach ($r->getMethods() as $method) {
  322. if (preg_match('/^get(.+)Service$/', $method->name, $match)) {
  323. $ids[] = self::underscore($match[1]);
  324. }
  325. }
  326. return array_unique(array_merge($ids, array_keys($this->services)));
  327. }
  328. /**
  329. * This is called when you enter a scope
  330. *
  331. * @param string $name
  332. *
  333. * @throws RuntimeException When the parent scope is inactive
  334. * @throws InvalidArgumentException When the scope does not exist
  335. *
  336. * @api
  337. */
  338. public function enterScope($name)
  339. {
  340. if (!isset($this->scopes[$name])) {
  341. throw new InvalidArgumentException(sprintf('The scope "%s" does not exist.', $name));
  342. }
  343. if (self::SCOPE_CONTAINER !== $this->scopes[$name] && !isset($this->scopedServices[$this->scopes[$name]])) {
  344. throw new RuntimeException(sprintf('The parent scope "%s" must be active when entering this scope.', $this->scopes[$name]));
  345. }
  346. // check if a scope of this name is already active, if so we need to
  347. // remove all services of this scope, and those of any of its child
  348. // scopes from the global services map
  349. if (isset($this->scopedServices[$name])) {
  350. $services = array($this->services, $name => $this->scopedServices[$name]);
  351. unset($this->scopedServices[$name]);
  352. foreach ($this->scopeChildren[$name] as $child) {
  353. if (isset($this->scopedServices[$child])) {
  354. $services[$child] = $this->scopedServices[$child];
  355. unset($this->scopedServices[$child]);
  356. }
  357. }
  358. // update global map
  359. $this->services = call_user_func_array('array_diff_key', $services);
  360. array_shift($services);
  361. // add stack entry for this scope so we can restore the removed services later
  362. if (!isset($this->scopeStacks[$name])) {
  363. $this->scopeStacks[$name] = new \SplStack();
  364. }
  365. $this->scopeStacks[$name]->push($services);
  366. }
  367. $this->scopedServices[$name] = array();
  368. }
  369. /**
  370. * This is called to leave the current scope, and move back to the parent
  371. * scope.
  372. *
  373. * @param string $name The name of the scope to leave
  374. *
  375. * @throws InvalidArgumentException if the scope is not active
  376. *
  377. * @api
  378. */
  379. public function leaveScope($name)
  380. {
  381. if (!isset($this->scopedServices[$name])) {
  382. throw new InvalidArgumentException(sprintf('The scope "%s" is not active.', $name));
  383. }
  384. // remove all services of this scope, or any of its child scopes from
  385. // the global service map
  386. $services = array($this->services, $this->scopedServices[$name]);
  387. unset($this->scopedServices[$name]);
  388. foreach ($this->scopeChildren[$name] as $child) {
  389. if (!isset($this->scopedServices[$child])) {
  390. continue;
  391. }
  392. $services[] = $this->scopedServices[$child];
  393. unset($this->scopedServices[$child]);
  394. }
  395. $this->services = call_user_func_array('array_diff_key', $services);
  396. // check if we need to restore services of a previous scope of this type
  397. if (isset($this->scopeStacks[$name]) && count($this->scopeStacks[$name]) > 0) {
  398. $services = $this->scopeStacks[$name]->pop();
  399. $this->scopedServices += $services;
  400. foreach ($services as $array) {
  401. foreach ($array as $id => $service) {
  402. $this->set($id, $service, $name);
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Adds a scope to the container.
  409. *
  410. * @param ScopeInterface $scope
  411. *
  412. * @throws InvalidArgumentException
  413. *
  414. * @api
  415. */
  416. public function addScope(ScopeInterface $scope)
  417. {
  418. $name = $scope->getName();
  419. $parentScope = $scope->getParentName();
  420. if (self::SCOPE_CONTAINER === $name || self::SCOPE_PROTOTYPE === $name) {
  421. throw new InvalidArgumentException(sprintf('The scope "%s" is reserved.', $name));
  422. }
  423. if (isset($this->scopes[$name])) {
  424. throw new InvalidArgumentException(sprintf('A scope with name "%s" already exists.', $name));
  425. }
  426. if (self::SCOPE_CONTAINER !== $parentScope && !isset($this->scopes[$parentScope])) {
  427. throw new InvalidArgumentException(sprintf('The parent scope "%s" does not exist, or is invalid.', $parentScope));
  428. }
  429. $this->scopes[$name] = $parentScope;
  430. $this->scopeChildren[$name] = array();
  431. // normalize the child relations
  432. while ($parentScope !== self::SCOPE_CONTAINER) {
  433. $this->scopeChildren[$parentScope][] = $name;
  434. $parentScope = $this->scopes[$parentScope];
  435. }
  436. }
  437. /**
  438. * Returns whether this container has a certain scope
  439. *
  440. * @param string $name The name of the scope
  441. *
  442. * @return Boolean
  443. *
  444. * @api
  445. */
  446. public function hasScope($name)
  447. {
  448. return isset($this->scopes[$name]);
  449. }
  450. /**
  451. * Returns whether this scope is currently active
  452. *
  453. * This does not actually check if the passed scope actually exists.
  454. *
  455. * @param string $name
  456. *
  457. * @return Boolean
  458. *
  459. * @api
  460. */
  461. public function isScopeActive($name)
  462. {
  463. return isset($this->scopedServices[$name]);
  464. }
  465. /**
  466. * Camelizes a string.
  467. *
  468. * @param string $id A string to camelize
  469. *
  470. * @return string The camelized string
  471. */
  472. public static function camelize($id)
  473. {
  474. return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ '))), array(' ' => ''));
  475. }
  476. /**
  477. * A string to underscore.
  478. *
  479. * @param string $id The string to underscore
  480. *
  481. * @return string The underscored string
  482. */
  483. public static function underscore($id)
  484. {
  485. return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
  486. }
  487. }