ContainerBuilder.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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\Config\Resource\FileResource;
  12. use Symfony\Component\Config\Resource\ResourceInterface;
  13. use Symfony\Component\DependencyInjection\Compiler\Compiler;
  14. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  15. use Symfony\Component\DependencyInjection\Compiler\PassConfig;
  16. use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
  17. use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
  18. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  19. use Symfony\Component\DependencyInjection\Exception\LogicException;
  20. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  21. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  22. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  23. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  24. use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
  25. use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
  26. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  27. use Symfony\Component\ExpressionLanguage\Expression;
  28. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  29. /**
  30. * ContainerBuilder is a DI container that provides an API to easily describe services.
  31. *
  32. * @author Fabien Potencier <fabien@symfony.com>
  33. */
  34. class ContainerBuilder extends Container implements TaggedContainerInterface
  35. {
  36. /**
  37. * @var ExtensionInterface[]
  38. */
  39. private $extensions = array();
  40. /**
  41. * @var ExtensionInterface[]
  42. */
  43. private $extensionsByNs = array();
  44. /**
  45. * @var Definition[]
  46. */
  47. private $definitions = array();
  48. /**
  49. * @var Definition[]
  50. */
  51. private $obsoleteDefinitions = array();
  52. /**
  53. * @var Alias[]
  54. */
  55. private $aliasDefinitions = array();
  56. /**
  57. * @var ResourceInterface[]
  58. */
  59. private $resources = array();
  60. private $extensionConfigs = array();
  61. /**
  62. * @var Compiler
  63. */
  64. private $compiler;
  65. private $trackResources;
  66. /**
  67. * @var InstantiatorInterface|null
  68. */
  69. private $proxyInstantiator;
  70. /**
  71. * @var ExpressionLanguage|null
  72. */
  73. private $expressionLanguage;
  74. /**
  75. * @var ExpressionFunctionProviderInterface[]
  76. */
  77. private $expressionLanguageProviders = array();
  78. public function __construct(ParameterBagInterface $parameterBag = null)
  79. {
  80. parent::__construct($parameterBag);
  81. $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface');
  82. }
  83. /**
  84. * @var string[] with tag names used by findTaggedServiceIds
  85. */
  86. private $usedTags = array();
  87. /**
  88. * Sets the track resources flag.
  89. *
  90. * If you are not using the loaders and therefore don't want
  91. * to depend on the Config component, set this flag to false.
  92. *
  93. * @param bool $track True if you want to track resources, false otherwise
  94. */
  95. public function setResourceTracking($track)
  96. {
  97. $this->trackResources = (bool) $track;
  98. }
  99. /**
  100. * Checks if resources are tracked.
  101. *
  102. * @return bool true If resources are tracked, false otherwise
  103. */
  104. public function isTrackingResources()
  105. {
  106. return $this->trackResources;
  107. }
  108. /**
  109. * Sets the instantiator to be used when fetching proxies.
  110. */
  111. public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)
  112. {
  113. $this->proxyInstantiator = $proxyInstantiator;
  114. }
  115. public function registerExtension(ExtensionInterface $extension)
  116. {
  117. $this->extensions[$extension->getAlias()] = $extension;
  118. if (false !== $extension->getNamespace()) {
  119. $this->extensionsByNs[$extension->getNamespace()] = $extension;
  120. }
  121. }
  122. /**
  123. * Returns an extension by alias or namespace.
  124. *
  125. * @param string $name An alias or a namespace
  126. *
  127. * @return ExtensionInterface An extension instance
  128. *
  129. * @throws LogicException if the extension is not registered
  130. */
  131. public function getExtension($name)
  132. {
  133. if (isset($this->extensions[$name])) {
  134. return $this->extensions[$name];
  135. }
  136. if (isset($this->extensionsByNs[$name])) {
  137. return $this->extensionsByNs[$name];
  138. }
  139. throw new LogicException(sprintf('Container extension "%s" is not registered', $name));
  140. }
  141. /**
  142. * Returns all registered extensions.
  143. *
  144. * @return ExtensionInterface[] An array of ExtensionInterface
  145. */
  146. public function getExtensions()
  147. {
  148. return $this->extensions;
  149. }
  150. /**
  151. * Checks if we have an extension.
  152. *
  153. * @param string $name The name of the extension
  154. *
  155. * @return bool If the extension exists
  156. */
  157. public function hasExtension($name)
  158. {
  159. return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
  160. }
  161. /**
  162. * Returns an array of resources loaded to build this configuration.
  163. *
  164. * @return ResourceInterface[] An array of resources
  165. */
  166. public function getResources()
  167. {
  168. return array_unique($this->resources);
  169. }
  170. /**
  171. * @return $this
  172. */
  173. public function addResource(ResourceInterface $resource)
  174. {
  175. if (!$this->trackResources) {
  176. return $this;
  177. }
  178. $this->resources[] = $resource;
  179. return $this;
  180. }
  181. /**
  182. * Sets the resources for this configuration.
  183. *
  184. * @param ResourceInterface[] $resources An array of resources
  185. *
  186. * @return $this
  187. */
  188. public function setResources(array $resources)
  189. {
  190. if (!$this->trackResources) {
  191. return $this;
  192. }
  193. $this->resources = $resources;
  194. return $this;
  195. }
  196. /**
  197. * Adds the object class hierarchy as resources.
  198. *
  199. * @param object $object An object instance
  200. *
  201. * @return $this
  202. */
  203. public function addObjectResource($object)
  204. {
  205. if ($this->trackResources) {
  206. $this->addClassResource(new \ReflectionClass($object));
  207. }
  208. return $this;
  209. }
  210. /**
  211. * Adds the given class hierarchy as resources.
  212. *
  213. * @return $this
  214. */
  215. public function addClassResource(\ReflectionClass $class)
  216. {
  217. if (!$this->trackResources) {
  218. return $this;
  219. }
  220. do {
  221. if (is_file($class->getFileName())) {
  222. $this->addResource(new FileResource($class->getFileName()));
  223. }
  224. } while ($class = $class->getParentClass());
  225. return $this;
  226. }
  227. /**
  228. * Loads the configuration for an extension.
  229. *
  230. * @param string $extension The extension alias or namespace
  231. * @param array $values An array of values that customizes the extension
  232. *
  233. * @return $this
  234. *
  235. * @throws BadMethodCallException When this ContainerBuilder is frozen
  236. * @throws \LogicException if the container is frozen
  237. */
  238. public function loadFromExtension($extension, array $values = null)
  239. {
  240. if ($this->isFrozen()) {
  241. throw new BadMethodCallException('Cannot load from an extension on a frozen container.');
  242. }
  243. if (\func_num_args() < 2) {
  244. $values = array();
  245. }
  246. $namespace = $this->getExtension($extension)->getAlias();
  247. $this->extensionConfigs[$namespace][] = $values;
  248. return $this;
  249. }
  250. /**
  251. * Adds a compiler pass.
  252. *
  253. * @param CompilerPassInterface $pass A compiler pass
  254. * @param string $type The type of compiler pass
  255. *
  256. * @return $this
  257. */
  258. public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION)
  259. {
  260. $this->getCompiler()->addPass($pass, $type);
  261. $this->addObjectResource($pass);
  262. return $this;
  263. }
  264. /**
  265. * Returns the compiler pass config which can then be modified.
  266. *
  267. * @return PassConfig The compiler pass config
  268. */
  269. public function getCompilerPassConfig()
  270. {
  271. return $this->getCompiler()->getPassConfig();
  272. }
  273. /**
  274. * Returns the compiler.
  275. *
  276. * @return Compiler The compiler
  277. */
  278. public function getCompiler()
  279. {
  280. if (null === $this->compiler) {
  281. $this->compiler = new Compiler();
  282. }
  283. return $this->compiler;
  284. }
  285. /**
  286. * Returns all Scopes.
  287. *
  288. * @return array An array of scopes
  289. *
  290. * @deprecated since version 2.8, to be removed in 3.0.
  291. */
  292. public function getScopes($triggerDeprecationError = true)
  293. {
  294. if ($triggerDeprecationError) {
  295. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  296. }
  297. return $this->scopes;
  298. }
  299. /**
  300. * Returns all Scope children.
  301. *
  302. * @return array An array of scope children
  303. *
  304. * @deprecated since version 2.8, to be removed in 3.0.
  305. */
  306. public function getScopeChildren($triggerDeprecationError = true)
  307. {
  308. if ($triggerDeprecationError) {
  309. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
  310. }
  311. return $this->scopeChildren;
  312. }
  313. /**
  314. * Sets a service.
  315. *
  316. * Note: The $scope parameter is deprecated since version 2.8 and will be removed in 3.0.
  317. *
  318. * @param string $id The service identifier
  319. * @param object $service The service instance
  320. * @param string $scope The scope
  321. *
  322. * @throws BadMethodCallException When this ContainerBuilder is frozen
  323. */
  324. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  325. {
  326. $id = strtolower($id);
  327. $set = isset($this->definitions[$id]);
  328. if ($this->isFrozen() && ($set || isset($this->obsoleteDefinitions[$id])) && !$this->{$set ? 'definitions' : 'obsoleteDefinitions'}[$id]->isSynthetic()) {
  329. // setting a synthetic service on a frozen container is alright
  330. throw new BadMethodCallException(sprintf('Setting service "%s" on a frozen container is not allowed.', $id));
  331. }
  332. if ($set) {
  333. $this->obsoleteDefinitions[$id] = $this->definitions[$id];
  334. }
  335. unset($this->definitions[$id], $this->aliasDefinitions[$id]);
  336. parent::set($id, $service, $scope);
  337. if (isset($this->obsoleteDefinitions[$id]) && $this->obsoleteDefinitions[$id]->isSynchronized(false)) {
  338. $this->synchronize($id);
  339. }
  340. }
  341. /**
  342. * Removes a service definition.
  343. *
  344. * @param string $id The service identifier
  345. */
  346. public function removeDefinition($id)
  347. {
  348. unset($this->definitions[strtolower($id)]);
  349. }
  350. /**
  351. * Returns true if the given service is defined.
  352. *
  353. * @param string $id The service identifier
  354. *
  355. * @return bool true if the service is defined, false otherwise
  356. */
  357. public function has($id)
  358. {
  359. $id = strtolower($id);
  360. return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id);
  361. }
  362. /**
  363. * Gets a service.
  364. *
  365. * @param string $id The service identifier
  366. * @param int $invalidBehavior The behavior when the service does not exist
  367. *
  368. * @return object The associated service
  369. *
  370. * @throws InvalidArgumentException when no definitions are available
  371. * @throws ServiceCircularReferenceException When a circular reference is detected
  372. * @throws ServiceNotFoundException When the service is not defined
  373. * @throws \Exception
  374. *
  375. * @see Reference
  376. */
  377. public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
  378. {
  379. $id = strtolower($id);
  380. if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
  381. return $service;
  382. }
  383. if (!array_key_exists($id, $this->definitions) && isset($this->aliasDefinitions[$id])) {
  384. return $this->get((string) $this->aliasDefinitions[$id], $invalidBehavior);
  385. }
  386. try {
  387. $definition = $this->getDefinition($id);
  388. } catch (ServiceNotFoundException $e) {
  389. if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  390. return;
  391. }
  392. throw $e;
  393. }
  394. $this->loading[$id] = true;
  395. try {
  396. $service = $this->createService($definition, new \SplObjectStorage(), $id);
  397. } catch (\Exception $e) {
  398. unset($this->loading[$id]);
  399. if ($e instanceof InactiveScopeException && self::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  400. return;
  401. }
  402. throw $e;
  403. } catch (\Throwable $e) {
  404. unset($this->loading[$id]);
  405. throw $e;
  406. }
  407. unset($this->loading[$id]);
  408. return $service;
  409. }
  410. /**
  411. * Merges a ContainerBuilder with the current ContainerBuilder configuration.
  412. *
  413. * Service definitions overrides the current defined ones.
  414. *
  415. * But for parameters, they are overridden by the current ones. It allows
  416. * the parameters passed to the container constructor to have precedence
  417. * over the loaded ones.
  418. *
  419. * $container = new ContainerBuilder(new ParameterBag(array('foo' => 'bar')));
  420. * $loader = new LoaderXXX($container);
  421. * $loader->load('resource_name');
  422. * $container->register('foo', 'stdClass');
  423. *
  424. * In the above example, even if the loaded resource defines a foo
  425. * parameter, the value will still be 'bar' as defined in the ContainerBuilder
  426. * constructor.
  427. *
  428. * @throws BadMethodCallException When this ContainerBuilder is frozen
  429. */
  430. public function merge(ContainerBuilder $container)
  431. {
  432. if ($this->isFrozen()) {
  433. throw new BadMethodCallException('Cannot merge on a frozen container.');
  434. }
  435. $this->addDefinitions($container->getDefinitions());
  436. $this->addAliases($container->getAliases());
  437. $this->getParameterBag()->add($container->getParameterBag()->all());
  438. if ($this->trackResources) {
  439. foreach ($container->getResources() as $resource) {
  440. $this->addResource($resource);
  441. }
  442. }
  443. foreach ($this->extensions as $name => $extension) {
  444. if (!isset($this->extensionConfigs[$name])) {
  445. $this->extensionConfigs[$name] = array();
  446. }
  447. $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
  448. }
  449. }
  450. /**
  451. * Returns the configuration array for the given extension.
  452. *
  453. * @param string $name The name of the extension
  454. *
  455. * @return array An array of configuration
  456. */
  457. public function getExtensionConfig($name)
  458. {
  459. if (!isset($this->extensionConfigs[$name])) {
  460. $this->extensionConfigs[$name] = array();
  461. }
  462. return $this->extensionConfigs[$name];
  463. }
  464. /**
  465. * Prepends a config array to the configs of the given extension.
  466. *
  467. * @param string $name The name of the extension
  468. * @param array $config The config to set
  469. */
  470. public function prependExtensionConfig($name, array $config)
  471. {
  472. if (!isset($this->extensionConfigs[$name])) {
  473. $this->extensionConfigs[$name] = array();
  474. }
  475. array_unshift($this->extensionConfigs[$name], $config);
  476. }
  477. /**
  478. * Compiles the container.
  479. *
  480. * This method passes the container to compiler
  481. * passes whose job is to manipulate and optimize
  482. * the container.
  483. *
  484. * The main compiler passes roughly do four things:
  485. *
  486. * * The extension configurations are merged;
  487. * * Parameter values are resolved;
  488. * * The parameter bag is frozen;
  489. * * Extension loading is disabled.
  490. */
  491. public function compile()
  492. {
  493. $compiler = $this->getCompiler();
  494. if ($this->trackResources) {
  495. foreach ($compiler->getPassConfig()->getPasses() as $pass) {
  496. $this->addObjectResource($pass);
  497. }
  498. }
  499. $compiler->compile($this);
  500. if ($this->trackResources) {
  501. foreach ($this->definitions as $definition) {
  502. if ($definition->isLazy() && ($class = $definition->getClass()) && class_exists($class)) {
  503. $this->addClassResource(new \ReflectionClass($class));
  504. }
  505. }
  506. }
  507. $this->extensionConfigs = array();
  508. parent::compile();
  509. }
  510. /**
  511. * Gets all service ids.
  512. *
  513. * @return array An array of all defined service ids
  514. */
  515. public function getServiceIds()
  516. {
  517. return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()));
  518. }
  519. /**
  520. * Adds the service aliases.
  521. */
  522. public function addAliases(array $aliases)
  523. {
  524. foreach ($aliases as $alias => $id) {
  525. $this->setAlias($alias, $id);
  526. }
  527. }
  528. /**
  529. * Sets the service aliases.
  530. */
  531. public function setAliases(array $aliases)
  532. {
  533. $this->aliasDefinitions = array();
  534. $this->addAliases($aliases);
  535. }
  536. /**
  537. * Sets an alias for an existing service.
  538. *
  539. * @param string $alias The alias to create
  540. * @param string|Alias $id The service to alias
  541. *
  542. * @throws InvalidArgumentException if the id is not a string or an Alias
  543. * @throws InvalidArgumentException if the alias is for itself
  544. */
  545. public function setAlias($alias, $id)
  546. {
  547. $alias = strtolower($alias);
  548. if ('' === $alias || '\\' === substr($alias, -1) || \strlen($alias) !== strcspn($alias, "\0\r\n'")) {
  549. throw new InvalidArgumentException(sprintf('Invalid alias id: "%s"', $alias));
  550. }
  551. if (\is_string($id)) {
  552. $id = new Alias($id);
  553. } elseif (!$id instanceof Alias) {
  554. throw new InvalidArgumentException('$id must be a string, or an Alias object.');
  555. }
  556. if ($alias === (string) $id) {
  557. throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
  558. }
  559. unset($this->definitions[$alias]);
  560. $this->aliasDefinitions[$alias] = $id;
  561. }
  562. /**
  563. * Removes an alias.
  564. *
  565. * @param string $alias The alias to remove
  566. */
  567. public function removeAlias($alias)
  568. {
  569. unset($this->aliasDefinitions[strtolower($alias)]);
  570. }
  571. /**
  572. * Returns true if an alias exists under the given identifier.
  573. *
  574. * @param string $id The service identifier
  575. *
  576. * @return bool true if the alias exists, false otherwise
  577. */
  578. public function hasAlias($id)
  579. {
  580. return isset($this->aliasDefinitions[strtolower($id)]);
  581. }
  582. /**
  583. * Gets all defined aliases.
  584. *
  585. * @return Alias[] An array of aliases
  586. */
  587. public function getAliases()
  588. {
  589. return $this->aliasDefinitions;
  590. }
  591. /**
  592. * Gets an alias.
  593. *
  594. * @param string $id The service identifier
  595. *
  596. * @return Alias An Alias instance
  597. *
  598. * @throws InvalidArgumentException if the alias does not exist
  599. */
  600. public function getAlias($id)
  601. {
  602. $id = strtolower($id);
  603. if (!isset($this->aliasDefinitions[$id])) {
  604. throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
  605. }
  606. return $this->aliasDefinitions[$id];
  607. }
  608. /**
  609. * Registers a service definition.
  610. *
  611. * This methods allows for simple registration of service definition
  612. * with a fluid interface.
  613. *
  614. * @param string $id The service identifier
  615. * @param string $class|null The service class
  616. *
  617. * @return Definition A Definition instance
  618. */
  619. public function register($id, $class = null)
  620. {
  621. return $this->setDefinition($id, new Definition($class));
  622. }
  623. /**
  624. * Adds the service definitions.
  625. *
  626. * @param Definition[] $definitions An array of service definitions
  627. */
  628. public function addDefinitions(array $definitions)
  629. {
  630. foreach ($definitions as $id => $definition) {
  631. $this->setDefinition($id, $definition);
  632. }
  633. }
  634. /**
  635. * Sets the service definitions.
  636. *
  637. * @param Definition[] $definitions An array of service definitions
  638. */
  639. public function setDefinitions(array $definitions)
  640. {
  641. $this->definitions = array();
  642. $this->addDefinitions($definitions);
  643. }
  644. /**
  645. * Gets all service definitions.
  646. *
  647. * @return Definition[] An array of Definition instances
  648. */
  649. public function getDefinitions()
  650. {
  651. return $this->definitions;
  652. }
  653. /**
  654. * Sets a service definition.
  655. *
  656. * @param string $id The service identifier
  657. * @param Definition $definition A Definition instance
  658. *
  659. * @return Definition the service definition
  660. *
  661. * @throws BadMethodCallException When this ContainerBuilder is frozen
  662. */
  663. public function setDefinition($id, Definition $definition)
  664. {
  665. if ($this->isFrozen()) {
  666. throw new BadMethodCallException('Adding definition to a frozen container is not allowed');
  667. }
  668. $id = strtolower($id);
  669. if ('' === $id || '\\' === substr($id, -1) || \strlen($id) !== strcspn($id, "\0\r\n'")) {
  670. throw new InvalidArgumentException(sprintf('Invalid service id: "%s"', $id));
  671. }
  672. unset($this->aliasDefinitions[$id]);
  673. return $this->definitions[$id] = $definition;
  674. }
  675. /**
  676. * Returns true if a service definition exists under the given identifier.
  677. *
  678. * @param string $id The service identifier
  679. *
  680. * @return bool true if the service definition exists, false otherwise
  681. */
  682. public function hasDefinition($id)
  683. {
  684. return array_key_exists(strtolower($id), $this->definitions);
  685. }
  686. /**
  687. * Gets a service definition.
  688. *
  689. * @param string $id The service identifier
  690. *
  691. * @return Definition A Definition instance
  692. *
  693. * @throws ServiceNotFoundException if the service definition does not exist
  694. */
  695. public function getDefinition($id)
  696. {
  697. $id = strtolower($id);
  698. if (!array_key_exists($id, $this->definitions)) {
  699. throw new ServiceNotFoundException($id);
  700. }
  701. return $this->definitions[$id];
  702. }
  703. /**
  704. * Gets a service definition by id or alias.
  705. *
  706. * The method "unaliases" recursively to return a Definition instance.
  707. *
  708. * @param string $id The service identifier or alias
  709. *
  710. * @return Definition A Definition instance
  711. *
  712. * @throws ServiceNotFoundException if the service definition does not exist
  713. */
  714. public function findDefinition($id)
  715. {
  716. $id = strtolower($id);
  717. while (isset($this->aliasDefinitions[$id])) {
  718. $id = (string) $this->aliasDefinitions[$id];
  719. }
  720. return $this->getDefinition($id);
  721. }
  722. /**
  723. * Creates a service for a service definition.
  724. *
  725. * @param Definition $definition A service definition instance
  726. * @param string $id The service identifier
  727. * @param bool $tryProxy Whether to try proxying the service with a lazy proxy
  728. *
  729. * @return object The service described by the service definition
  730. *
  731. * @throws RuntimeException When the scope is inactive
  732. * @throws RuntimeException When the factory definition is incomplete
  733. * @throws RuntimeException When the service is a synthetic service
  734. * @throws InvalidArgumentException When configure callable is not callable
  735. *
  736. * @internal this method is public because of PHP 5.3 limitations, do not use it explicitly in your code
  737. */
  738. public function createService(Definition $definition, \SplObjectStorage $inlinedDefinitions, $id = null, $tryProxy = true)
  739. {
  740. if (null === $id && isset($inlinedDefinitions[$definition])) {
  741. return $inlinedDefinitions[$definition];
  742. }
  743. if ($definition instanceof DefinitionDecorator) {
  744. throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
  745. }
  746. if ($definition->isSynthetic()) {
  747. throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
  748. }
  749. if ($definition->isDeprecated()) {
  750. @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED);
  751. }
  752. if ($tryProxy && $definition->isLazy()) {
  753. $container = $this;
  754. $proxy = $this
  755. ->getProxyInstantiator()
  756. ->instantiateProxy(
  757. $container,
  758. $definition,
  759. $id, function () use ($definition, $inlinedDefinitions, $id, $container) {
  760. return $container->createService($definition, $inlinedDefinitions, $id, false);
  761. }
  762. );
  763. $this->shareService($definition, $proxy, $id, $inlinedDefinitions);
  764. return $proxy;
  765. }
  766. $parameterBag = $this->getParameterBag();
  767. if (null !== $definition->getFile()) {
  768. require_once $parameterBag->resolveValue($definition->getFile());
  769. }
  770. $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlinedDefinitions);
  771. if (null !== $factory = $definition->getFactory()) {
  772. if (\is_array($factory)) {
  773. $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlinedDefinitions), $factory[1]);
  774. } elseif (!\is_string($factory)) {
  775. throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
  776. }
  777. $service = \call_user_func_array($factory, $arguments);
  778. if (!$definition->isDeprecated() && \is_array($factory) && \is_string($factory[0])) {
  779. $r = new \ReflectionClass($factory[0]);
  780. if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
  781. @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" factory class. It should either be deprecated or its factory upgraded.', $id, $r->name), E_USER_DEPRECATED);
  782. }
  783. }
  784. } elseif (null !== $definition->getFactoryMethod(false)) {
  785. if (null !== $definition->getFactoryClass(false)) {
  786. $factory = $parameterBag->resolveValue($definition->getFactoryClass(false));
  787. } elseif (null !== $definition->getFactoryService(false)) {
  788. $factory = $this->get($parameterBag->resolveValue($definition->getFactoryService(false)));
  789. } else {
  790. throw new RuntimeException(sprintf('Cannot create service "%s" from factory method without a factory service or factory class.', $id));
  791. }
  792. $service = \call_user_func_array(array($factory, $definition->getFactoryMethod(false)), $arguments);
  793. } else {
  794. $r = new \ReflectionClass($parameterBag->resolveValue($definition->getClass()));
  795. $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
  796. if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
  797. @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" class. It should either be deprecated or its implementation upgraded.', $id, $r->name), E_USER_DEPRECATED);
  798. }
  799. }
  800. if ($tryProxy || !$definition->isLazy()) {
  801. // share only if proxying failed, or if not a proxy
  802. $this->shareService($definition, $service, $id, $inlinedDefinitions);
  803. }
  804. $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlinedDefinitions);
  805. foreach ($properties as $name => $value) {
  806. $service->$name = $value;
  807. }
  808. foreach ($definition->getMethodCalls() as $call) {
  809. $this->callMethod($service, $call, $inlinedDefinitions);
  810. }
  811. if ($callable = $definition->getConfigurator()) {
  812. if (\is_array($callable)) {
  813. $callable[0] = $parameterBag->resolveValue($callable[0]);
  814. if ($callable[0] instanceof Reference) {
  815. $callable[0] = $this->get((string) $callable[0], $callable[0]->getInvalidBehavior());
  816. } elseif ($callable[0] instanceof Definition) {
  817. $callable[0] = $this->createService($callable[0], $inlinedDefinitions);
  818. }
  819. }
  820. if (!\is_callable($callable)) {
  821. throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', \get_class($service)));
  822. }
  823. \call_user_func($callable, $service);
  824. }
  825. return $service;
  826. }
  827. /**
  828. * Replaces service references by the real service instance and evaluates expressions.
  829. *
  830. * @param mixed $value A value
  831. *
  832. * @return mixed The same value with all service references replaced by
  833. * the real service instances and all expressions evaluated
  834. */
  835. public function resolveServices($value)
  836. {
  837. return $this->doResolveServices($value, new \SplObjectStorage());
  838. }
  839. private function doResolveServices($value, \SplObjectStorage $inlinedDefinitions)
  840. {
  841. if (\is_array($value)) {
  842. foreach ($value as $k => $v) {
  843. $value[$k] = $this->doResolveServices($v, $inlinedDefinitions);
  844. }
  845. } elseif ($value instanceof Reference) {
  846. $value = $this->get((string) $value, $value->getInvalidBehavior());
  847. } elseif ($value instanceof Definition) {
  848. $value = $this->createService($value, $inlinedDefinitions);
  849. } elseif ($value instanceof Expression) {
  850. $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
  851. }
  852. return $value;
  853. }
  854. /**
  855. * Returns service ids for a given tag.
  856. *
  857. * Example:
  858. *
  859. * $container->register('foo')->addTag('my.tag', array('hello' => 'world'));
  860. *
  861. * $serviceIds = $container->findTaggedServiceIds('my.tag');
  862. * foreach ($serviceIds as $serviceId => $tags) {
  863. * foreach ($tags as $tag) {
  864. * echo $tag['hello'];
  865. * }
  866. * }
  867. *
  868. * @param string $name The tag name
  869. *
  870. * @return array An array of tags with the tagged service as key, holding a list of attribute arrays
  871. */
  872. public function findTaggedServiceIds($name)
  873. {
  874. $this->usedTags[] = $name;
  875. $tags = array();
  876. foreach ($this->getDefinitions() as $id => $definition) {
  877. if ($definition->hasTag($name)) {
  878. $tags[$id] = $definition->getTag($name);
  879. }
  880. }
  881. return $tags;
  882. }
  883. /**
  884. * Returns all tags the defined services use.
  885. *
  886. * @return array An array of tags
  887. */
  888. public function findTags()
  889. {
  890. $tags = array();
  891. foreach ($this->getDefinitions() as $id => $definition) {
  892. $tags = array_merge(array_keys($definition->getTags()), $tags);
  893. }
  894. return array_unique($tags);
  895. }
  896. /**
  897. * Returns all tags not queried by findTaggedServiceIds.
  898. *
  899. * @return string[] An array of tags
  900. */
  901. public function findUnusedTags()
  902. {
  903. return array_values(array_diff($this->findTags(), $this->usedTags));
  904. }
  905. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  906. {
  907. $this->expressionLanguageProviders[] = $provider;
  908. }
  909. /**
  910. * @return ExpressionFunctionProviderInterface[]
  911. */
  912. public function getExpressionLanguageProviders()
  913. {
  914. return $this->expressionLanguageProviders;
  915. }
  916. /**
  917. * Returns the Service Conditionals.
  918. *
  919. * @param mixed $value An array of conditionals to return
  920. *
  921. * @return array An array of Service conditionals
  922. */
  923. public static function getServiceConditionals($value)
  924. {
  925. $services = array();
  926. if (\is_array($value)) {
  927. foreach ($value as $v) {
  928. $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
  929. }
  930. } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) {
  931. $services[] = (string) $value;
  932. }
  933. return $services;
  934. }
  935. /**
  936. * Retrieves the currently set proxy instantiator or instantiates one.
  937. *
  938. * @return InstantiatorInterface
  939. */
  940. private function getProxyInstantiator()
  941. {
  942. if (!$this->proxyInstantiator) {
  943. $this->proxyInstantiator = new RealServiceInstantiator();
  944. }
  945. return $this->proxyInstantiator;
  946. }
  947. /**
  948. * Synchronizes a service change.
  949. *
  950. * This method updates all services that depend on the given
  951. * service by calling all methods referencing it.
  952. *
  953. * @param string $id A service id
  954. *
  955. * @deprecated since version 2.7, will be removed in 3.0.
  956. */
  957. private function synchronize($id)
  958. {
  959. if ('request' !== $id) {
  960. @trigger_error('The '.__METHOD__.' method is deprecated in version 2.7 and will be removed in version 3.0.', E_USER_DEPRECATED);
  961. }
  962. foreach ($this->definitions as $definitionId => $definition) {
  963. // only check initialized services
  964. if (!$this->initialized($definitionId)) {
  965. continue;
  966. }
  967. foreach ($definition->getMethodCalls() as $call) {
  968. foreach ($call[1] as $argument) {
  969. if ($argument instanceof Reference && $id == (string) $argument) {
  970. $this->callMethod($this->get($definitionId), $call, new \SplObjectStorage());
  971. }
  972. }
  973. }
  974. }
  975. }
  976. private function callMethod($service, $call, \SplObjectStorage $inlinedDefinitions)
  977. {
  978. $services = self::getServiceConditionals($call[1]);
  979. foreach ($services as $s) {
  980. if (!$this->has($s)) {
  981. return;
  982. }
  983. }
  984. \call_user_func_array(array($service, $call[0]), $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlinedDefinitions));
  985. }
  986. /**
  987. * Shares a given service in the container.
  988. *
  989. * @param Definition $definition
  990. * @param mixed $service
  991. * @param string|null $id
  992. *
  993. * @throws InactiveScopeException
  994. */
  995. private function shareService(Definition $definition, $service, $id, \SplObjectStorage $inlinedDefinitions)
  996. {
  997. if (!$definition->isShared() || self::SCOPE_PROTOTYPE === $scope = $definition->getScope(false)) {
  998. return;
  999. }
  1000. if (null === $id) {
  1001. $inlinedDefinitions[$definition] = $service;
  1002. } else {
  1003. if (self::SCOPE_CONTAINER !== $scope && !isset($this->scopedServices[$scope])) {
  1004. throw new InactiveScopeException($id, $scope);
  1005. }
  1006. $this->services[$lowerId = strtolower($id)] = $service;
  1007. if (self::SCOPE_CONTAINER !== $scope) {
  1008. $this->scopedServices[$scope][$lowerId] = $service;
  1009. }
  1010. }
  1011. }
  1012. private function getExpressionLanguage()
  1013. {
  1014. if (null === $this->expressionLanguage) {
  1015. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  1016. throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  1017. }
  1018. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  1019. }
  1020. return $this->expressionLanguage;
  1021. }
  1022. }