Drupal investigation

Container.php 20KB

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