ContainerBuilder.php 22 KB

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