ContainerBuilder.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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\Compiler\Compiler;
  12. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  13. use Symfony\Component\DependencyInjection\Compiler\PassConfig;
  14. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use Symfony\Component\Config\Resource\FileResource;
  17. use Symfony\Component\Config\Resource\ResourceInterface;
  18. /**
  19. * ContainerBuilder is a DI container that provides an API to easily describe services.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class ContainerBuilder extends Container implements TaggedContainerInterface
  24. {
  25. private $extensions = array();
  26. private $extensionsByNs = array();
  27. private $definitions = array();
  28. private $aliases = array();
  29. private $resources = array();
  30. private $extensionConfigs = array();
  31. private $injectors = array();
  32. private $compiler;
  33. /**
  34. * Registers an extension.
  35. *
  36. * @param ExtensionInterface $extension An extension instance
  37. */
  38. public function registerExtension(ExtensionInterface $extension)
  39. {
  40. $this->extensions[$extension->getAlias()] = $extension;
  41. if (false !== $extension->getNamespace()) {
  42. $this->extensionsByNs[$extension->getNamespace()] = $extension;
  43. }
  44. }
  45. /**
  46. * Returns an extension by alias or namespace.
  47. *
  48. * @param string $name An alias or a namespace
  49. *
  50. * @return ExtensionInterface An extension instance
  51. */
  52. public function getExtension($name)
  53. {
  54. if (isset($this->extensions[$name])) {
  55. return $this->extensions[$name];
  56. }
  57. if (isset($this->extensionsByNs[$name])) {
  58. return $this->extensionsByNs[$name];
  59. }
  60. throw new \LogicException(sprintf('Container extension "%s" is not registered', $name));
  61. }
  62. /**
  63. * Returns all registered extensions.
  64. *
  65. * @return array An array of ExtensionInterface
  66. */
  67. public function getExtensions()
  68. {
  69. return $this->extensions;
  70. }
  71. /**
  72. * Checks if we have an extension.
  73. *
  74. * @param string $name The name of the extension
  75. * @return Boolean If the extension exists
  76. */
  77. public function hasExtension($name)
  78. {
  79. return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
  80. }
  81. /**
  82. * Returns an array of resources loaded to build this configuration.
  83. *
  84. * @return ResourceInterface[] An array of resources
  85. */
  86. public function getResources()
  87. {
  88. return array_unique($this->resources);
  89. }
  90. /**
  91. * Adds a resource for this configuration.
  92. *
  93. * @param ResourceInterface $resource A resource instance
  94. *
  95. * @return ContainerBuilder The current instance
  96. */
  97. public function addResource(ResourceInterface $resource)
  98. {
  99. $this->resources[] = $resource;
  100. return $this;
  101. }
  102. /**
  103. * Adds the object class hierarchy as resources.
  104. *
  105. * @param object $object An object instance
  106. */
  107. public function addObjectResource($object)
  108. {
  109. $parent = new \ReflectionObject($object);
  110. do {
  111. $this->addResource(new FileResource($parent->getFileName()));
  112. } while ($parent = $parent->getParentClass());
  113. }
  114. /**
  115. * Loads the configuration for an extension.
  116. *
  117. * @param string $extension The extension alias or namespace
  118. * @param array $values An array of values that customizes the extension
  119. *
  120. * @return ContainerBuilder The current instance
  121. */
  122. public function loadFromExtension($extension, array $values = array())
  123. {
  124. if (true === $this->isFrozen()) {
  125. throw new \LogicException('Cannot load from an extension on a frozen container.');
  126. }
  127. $namespace = $this->getExtension($extension)->getAlias();
  128. if (!isset($this->extensionConfigs[$namespace])) {
  129. $this->extensionConfigs[$namespace] = array();
  130. }
  131. $this->extensionConfigs[$namespace][] = $this->getParameterBag()->resolveValue($values);
  132. return $this;
  133. }
  134. /**
  135. * Adds a compiler pass.
  136. *
  137. * @param CompilerPassInterface $pass A compiler pass
  138. * @param string $type The type of compiler pass
  139. */
  140. public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION)
  141. {
  142. if (null === $this->compiler) {
  143. $this->compiler = new Compiler();
  144. }
  145. $this->compiler->addPass($pass, $type);
  146. $this->addObjectResource($pass);
  147. }
  148. /**
  149. * Returns the compiler pass config which can then be modified.
  150. *
  151. * @return PassConfig The compiler pass config
  152. */
  153. public function getCompilerPassConfig()
  154. {
  155. if (null === $this->compiler) {
  156. $this->compiler = new Compiler();
  157. }
  158. return $this->compiler->getPassConfig();
  159. }
  160. /**
  161. * Returns the compiler.
  162. *
  163. * @return Compiler The compiler
  164. */
  165. public function getCompiler()
  166. {
  167. if (null === $this->compiler) {
  168. $this->compiler = new Compiler();
  169. }
  170. return $this->compiler;
  171. }
  172. /**
  173. * Returns all Scopes.
  174. *
  175. * @return array An array of scopes
  176. */
  177. public function getScopes()
  178. {
  179. return $this->scopes;
  180. }
  181. /**
  182. * Returns all Scope children.
  183. *
  184. * @return array An array of scope children.
  185. */
  186. public function getScopeChildren()
  187. {
  188. return $this->scopeChildren;
  189. }
  190. /**
  191. * Sets a service.
  192. *
  193. * @param string $id The service identifier
  194. * @param object $service The service instance
  195. * @param string $scope The scope
  196. *
  197. * @throws BadMethodCallException
  198. */
  199. public function set($id, $service, $scope = self::SCOPE_CONTAINER)
  200. {
  201. if ($this->isFrozen()) {
  202. throw new \BadMethodCallException('Setting service on a frozen container is not allowed');
  203. }
  204. $id = strtolower($id);
  205. unset($this->definitions[$id], $this->aliases[$id]);
  206. parent::set($id, $service, $scope);
  207. }
  208. /**
  209. * Removes a service definition.
  210. *
  211. * @param string $id The service identifier
  212. */
  213. public function removeDefinition($id)
  214. {
  215. unset($this->definitions[strtolower($id)]);
  216. }
  217. /**
  218. * Returns true if the given service is defined.
  219. *
  220. * @param string $id The service identifier
  221. *
  222. * @return Boolean true if the service is defined, false otherwise
  223. */
  224. public function has($id)
  225. {
  226. $id = strtolower($id);
  227. return isset($this->definitions[$id]) || isset($this->aliases[$id]) || parent::has($id);
  228. }
  229. /**
  230. * Gets a service.
  231. *
  232. * @param string $id The service identifier
  233. * @param integer $invalidBehavior The behavior when the service does not exist
  234. *
  235. * @return object The associated service
  236. *
  237. * @throws \InvalidArgumentException if the service is not defined
  238. * @throws \LogicException if the service has a circular reference to itself
  239. *
  240. * @see Reference
  241. */
  242. public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
  243. {
  244. $id = strtolower($id);
  245. try {
  246. return parent::get($id, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
  247. } catch (\InvalidArgumentException $e) {
  248. if (isset($this->loading[$id])) {
  249. throw new \LogicException(sprintf('The service "%s" has a circular reference to itself.', $id), 0, $e);
  250. }
  251. if (!$this->hasDefinition($id) && isset($this->aliases[$id])) {
  252. return $this->get($this->aliases[$id]);
  253. }
  254. try {
  255. $definition = $this->getDefinition($id);
  256. } catch (\InvalidArgumentException $e) {
  257. if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
  258. return null;
  259. }
  260. throw $e;
  261. }
  262. $this->loading[$id] = true;
  263. $service = $this->createService($definition, $id);
  264. unset($this->loading[$id]);
  265. return $service;
  266. }
  267. }
  268. /**
  269. * Merges a ContainerBuilder with the current ContainerBuilder configuration.
  270. *
  271. * Service definitions overrides the current defined ones.
  272. *
  273. * But for parameters, they are overridden by the current ones. It allows
  274. * the parameters passed to the container constructor to have precedence
  275. * over the loaded ones.
  276. *
  277. * $container = new ContainerBuilder(array('foo' => 'bar'));
  278. * $loader = new LoaderXXX($container);
  279. * $loader->load('resource_name');
  280. * $container->register('foo', new stdClass());
  281. *
  282. * In the above example, even if the loaded resource defines a foo
  283. * parameter, the value will still be 'bar' as defined in the ContainerBuilder
  284. * constructor.
  285. *
  286. * @param ContainerBuilder $container The ContainerBuilder instance to merge.
  287. * @throws \LogicException when this ContainerBuilder is frozen
  288. */
  289. public function merge(ContainerBuilder $container)
  290. {
  291. if (true === $this->isFrozen()) {
  292. throw new \LogicException('Cannot merge on a frozen container.');
  293. }
  294. $this->addDefinitions($container->getDefinitions());
  295. $this->addAliases($container->getAliases());
  296. $this->getParameterBag()->add($container->getParameterBag()->all());
  297. foreach ($container->getResources() as $resource) {
  298. $this->addResource($resource);
  299. }
  300. foreach ($this->extensions as $name => $extension) {
  301. if (!isset($this->extensionConfigs[$name])) {
  302. $this->extensionConfigs[$name] = array();
  303. }
  304. $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
  305. }
  306. }
  307. /**
  308. * Returns the configuration array for the given extension.
  309. *
  310. * @param string $name The name of the extension
  311. *
  312. * @return array An array of configuration
  313. */
  314. public function getExtensionConfig($name)
  315. {
  316. if (!isset($this->extensionConfigs[$name])) {
  317. $this->extensionConfigs[$name] = array();
  318. }
  319. return $this->extensionConfigs[$name];
  320. }
  321. /**
  322. * Compiles the container.
  323. *
  324. * This method passes the container to compiler
  325. * passes whose job is to manipulate and optimize
  326. * the container.
  327. *
  328. * The main compiler passes roughly do four things:
  329. *
  330. * * The extension configurations are merged;
  331. * * Parameter values are resolved;
  332. * * The parameter bag is frozen;
  333. * * Extension loading is disabled.
  334. */
  335. public function compile()
  336. {
  337. if (null === $this->compiler) {
  338. $this->compiler = new Compiler();
  339. }
  340. foreach ($this->compiler->getPassConfig()->getPasses() as $pass) {
  341. $this->addObjectResource($pass);
  342. }
  343. $this->compiler->compile($this);
  344. $this->extensionConfigs = array();
  345. parent::compile();
  346. }
  347. /**
  348. * Gets all service ids.
  349. *
  350. * @return array An array of all defined service ids
  351. */
  352. public function getServiceIds()
  353. {
  354. return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliases), parent::getServiceIds()));
  355. }
  356. /**
  357. * Adds the service aliases.
  358. *
  359. * @param array $aliases An array of aliases
  360. */
  361. public function addAliases(array $aliases)
  362. {
  363. foreach ($aliases as $alias => $id) {
  364. $this->setAlias($alias, $id);
  365. }
  366. }
  367. /**
  368. * Sets the service aliases.
  369. *
  370. * @param array $aliases An array of service definitions
  371. */
  372. public function setAliases(array $aliases)
  373. {
  374. $this->aliases = array();
  375. $this->addAliases($aliases);
  376. }
  377. /**
  378. * Sets an alias for an existing service.
  379. *
  380. * @param string $alias The alias to create
  381. * @param mixed $id The service to alias
  382. */
  383. public function setAlias($alias, $id)
  384. {
  385. $alias = strtolower($alias);
  386. if (is_string($id)) {
  387. $id = new Alias($id);
  388. } else if (!$id instanceof Alias) {
  389. throw new \InvalidArgumentException('$id must be a string, or an Alias object.');
  390. }
  391. if ($alias === strtolower($id)) {
  392. throw new \InvalidArgumentException('An alias can not reference itself, got a circular reference on "'.$alias.'".');
  393. }
  394. unset($this->definitions[$alias]);
  395. $this->aliases[$alias] = $id;
  396. }
  397. /**
  398. * Removes an alias.
  399. *
  400. * @param string $alias The alias to remove
  401. */
  402. public function removeAlias($alias)
  403. {
  404. unset($this->aliases[strtolower($alias)]);
  405. }
  406. /**
  407. * Returns true if an alias exists under the given identifier.
  408. *
  409. * @param string $id The service identifier
  410. *
  411. * @return Boolean true if the alias exists, false otherwise
  412. */
  413. public function hasAlias($id)
  414. {
  415. return isset($this->aliases[strtolower($id)]);
  416. }
  417. /**
  418. * Gets all defined aliases.
  419. *
  420. * @return array An array of aliases
  421. */
  422. public function getAliases()
  423. {
  424. return $this->aliases;
  425. }
  426. /**
  427. * Gets an alias.
  428. *
  429. * @param string $id The service identifier
  430. *
  431. * @return string The aliased service identifier
  432. *
  433. * @throws \InvalidArgumentException if the alias does not exist
  434. */
  435. public function getAlias($id)
  436. {
  437. $id = strtolower($id);
  438. if (!$this->hasAlias($id)) {
  439. throw new \InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
  440. }
  441. return $this->aliases[$id];
  442. }
  443. /**
  444. * Registers a service definition.
  445. *
  446. * This methods allows for simple registration of service definition
  447. * with a fluid interface.
  448. *
  449. * @param string $id The service identifier
  450. * @param string $class The service class
  451. *
  452. * @return Definition A Definition instance
  453. */
  454. public function register($id, $class = null)
  455. {
  456. return $this->setDefinition(strtolower($id), new Definition($class));
  457. }
  458. /**
  459. * Adds the service definitions.
  460. *
  461. * @param Definition[] $definitions An array of service definitions
  462. */
  463. public function addDefinitions(array $definitions)
  464. {
  465. foreach ($definitions as $id => $definition) {
  466. $this->setDefinition($id, $definition);
  467. }
  468. }
  469. /**
  470. * Sets the service definitions.
  471. *
  472. * @param array $definitions An array of service definitions
  473. */
  474. public function setDefinitions(array $definitions)
  475. {
  476. $this->definitions = array();
  477. $this->addDefinitions($definitions);
  478. }
  479. /**
  480. * Gets all service definitions.
  481. *
  482. * @return array An array of Definition instances
  483. */
  484. public function getDefinitions()
  485. {
  486. return $this->definitions;
  487. }
  488. /**
  489. * Sets a service definition.
  490. *
  491. * @param string $id The service identifier
  492. * @param Definition $definition A Definition instance
  493. *
  494. * @throws BadMethodCallException
  495. */
  496. public function setDefinition($id, Definition $definition)
  497. {
  498. if ($this->isFrozen()) {
  499. throw new \BadMethodCallException('Adding definition to a frozen container is not allowed');
  500. }
  501. $id = strtolower($id);
  502. unset($this->aliases[$id]);
  503. return $this->definitions[$id] = $definition;
  504. }
  505. /**
  506. * Returns true if a service definition exists under the given identifier.
  507. *
  508. * @param string $id The service identifier
  509. *
  510. * @return Boolean true if the service definition exists, false otherwise
  511. */
  512. public function hasDefinition($id)
  513. {
  514. return array_key_exists(strtolower($id), $this->definitions);
  515. }
  516. /**
  517. * Gets a service definition.
  518. *
  519. * @param string $id The service identifier
  520. *
  521. * @return Definition A Definition instance
  522. *
  523. * @throws \InvalidArgumentException if the service definition does not exist
  524. */
  525. public function getDefinition($id)
  526. {
  527. $id = strtolower($id);
  528. if (!$this->hasDefinition($id)) {
  529. throw new \InvalidArgumentException(sprintf('The service definition "%s" does not exist.', $id));
  530. }
  531. return $this->definitions[$id];
  532. }
  533. /**
  534. * Gets a service definition by id or alias.
  535. *
  536. * The method "unaliases" recursively to return a Definition instance.
  537. *
  538. * @param string $id The service identifier or alias
  539. *
  540. * @return Definition A Definition instance
  541. *
  542. * @throws \InvalidArgumentException if the service definition does not exist
  543. */
  544. public function findDefinition($id)
  545. {
  546. $id = strtolower($id);
  547. if ($this->hasAlias($id)) {
  548. return $this->findDefinition((string) $this->getAlias($id));
  549. }
  550. return $this->getDefinition($id);
  551. }
  552. /**
  553. * Creates a service for a service definition.
  554. *
  555. * @param Definition $definition A service definition instance
  556. * @param string $id The service identifier
  557. *
  558. * @return object The service described by the service definition
  559. *
  560. * @throws \InvalidArgumentException When configure callable is not callable
  561. */
  562. private function createService(Definition $definition, $id)
  563. {
  564. if (null !== $definition->getFile()) {
  565. require_once $this->getParameterBag()->resolveValue($definition->getFile());
  566. }
  567. $arguments = $this->resolveServices($this->getParameterBag()->resolveValue($definition->getArguments()));
  568. if (null !== $definition->getFactoryMethod()) {
  569. if (null !== $definition->getFactoryClass()) {
  570. $factory = $this->getParameterBag()->resolveValue($definition->getFactoryClass());
  571. } elseif (null !== $definition->getFactoryService()) {
  572. $factory = $this->get($this->getParameterBag()->resolveValue($definition->getFactoryService()));
  573. } else {
  574. throw new \RuntimeException('Cannot create service from factory method without a factory service or factory class.');
  575. }
  576. $service = call_user_func_array(array($factory, $definition->getFactoryMethod()), $arguments);
  577. } else {
  578. $r = new \ReflectionClass($this->getParameterBag()->resolveValue($definition->getClass()));
  579. $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
  580. }
  581. if (self::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) {
  582. if (self::SCOPE_CONTAINER !== $scope && !isset($this->scopedServices[$scope])) {
  583. throw new \RuntimeException('You tried to create a service of an inactive scope.');
  584. }
  585. $this->services[$lowerId = strtolower($id)] = $service;
  586. if (self::SCOPE_CONTAINER !== $scope) {
  587. $this->scopedServices[$scope][$lowerId] = $service;
  588. }
  589. }
  590. foreach ($definition->getMethodCalls() as $call) {
  591. $services = self::getServiceConditionals($call[1]);
  592. $ok = true;
  593. foreach ($services as $s) {
  594. if (!$this->has($s)) {
  595. $ok = false;
  596. break;
  597. }
  598. }
  599. if ($ok) {
  600. call_user_func_array(array($service, $call[0]), $this->resolveServices($this->getParameterBag()->resolveValue($call[1])));
  601. }
  602. }
  603. $properties = $this->resolveServices($this->getParameterBag()->resolveValue($definition->getProperties()));
  604. $outsideClass = new \ReflectionClass($service);
  605. foreach ($properties as $name => $value) {
  606. $class = $outsideClass;
  607. do {
  608. if ($class->hasProperty($name)) {
  609. $property = $class->getProperty($name);
  610. $property->setAccessible(true);
  611. $property->setValue($service, $value);
  612. continue 2;
  613. }
  614. } while (false !== $class = $class->getParentClass());
  615. }
  616. if ($callable = $definition->getConfigurator()) {
  617. if (is_array($callable) && is_object($callable[0]) && $callable[0] instanceof Reference) {
  618. $callable[0] = $this->get((string) $callable[0]);
  619. } elseif (is_array($callable)) {
  620. $callable[0] = $this->getParameterBag()->resolveValue($callable[0]);
  621. }
  622. if (!is_callable($callable)) {
  623. throw new \InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service)));
  624. }
  625. call_user_func($callable, $service);
  626. }
  627. return $service;
  628. }
  629. /**
  630. * Replaces service references by the real service instance.
  631. *
  632. * @param mixed $value A value
  633. *
  634. * @return mixed The same value with all service references replaced by the real service instances
  635. */
  636. public function resolveServices($value)
  637. {
  638. if (is_array($value)) {
  639. foreach ($value as &$v) {
  640. $v = $this->resolveServices($v);
  641. }
  642. } elseif (is_object($value) && $value instanceof Reference) {
  643. $value = $this->get((string) $value, $value->getInvalidBehavior());
  644. } elseif (is_object($value) && $value instanceof Definition) {
  645. $value = $this->createService($value, null);
  646. }
  647. return $value;
  648. }
  649. /**
  650. * Returns service ids for a given tag.
  651. *
  652. * @param string $name The tag name
  653. *
  654. * @return array An array of tags
  655. */
  656. public function findTaggedServiceIds($name)
  657. {
  658. $tags = array();
  659. foreach ($this->getDefinitions() as $id => $definition) {
  660. if ($definition->getTag($name)) {
  661. $tags[$id] = $definition->getTag($name);
  662. }
  663. }
  664. return $tags;
  665. }
  666. /**
  667. * Returns the Service Conditionals.
  668. *
  669. * @param mixed $value An array of conditionals to return.
  670. * @return array An array of Service conditionals
  671. */
  672. static public function getServiceConditionals($value)
  673. {
  674. $services = array();
  675. if (is_array($value)) {
  676. foreach ($value as $v) {
  677. $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
  678. }
  679. } elseif (is_object($value) && $value instanceof Reference && $value->getInvalidBehavior() === ContainerInterface::IGNORE_ON_INVALID_REFERENCE) {
  680. $services[] = (string) $value;
  681. }
  682. return $services;
  683. }
  684. }