4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection;
14 use Psr\Container\ContainerInterface as PsrContainerInterface;
15 use Symfony\Component\Config\Resource\ClassExistenceResource;
16 use Symfony\Component\Config\Resource\ComposerResource;
17 use Symfony\Component\Config\Resource\DirectoryResource;
18 use Symfony\Component\Config\Resource\FileExistenceResource;
19 use Symfony\Component\Config\Resource\FileResource;
20 use Symfony\Component\Config\Resource\GlobResource;
21 use Symfony\Component\Config\Resource\ReflectionClassResource;
22 use Symfony\Component\Config\Resource\ResourceInterface;
23 use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
24 use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
25 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
26 use Symfony\Component\DependencyInjection\Compiler\Compiler;
27 use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
28 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
29 use Symfony\Component\DependencyInjection\Compiler\ResolveEnvPlaceholdersPass;
30 use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
31 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
32 use Symfony\Component\DependencyInjection\Exception\LogicException;
33 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
34 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
35 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
36 use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
37 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
38 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
39 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
40 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
41 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
42 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
43 use Symfony\Component\ExpressionLanguage\Expression;
44 use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
47 * ContainerBuilder is a DI container that provides an API to easily describe services.
49 * @author Fabien Potencier <fabien@symfony.com>
51 class ContainerBuilder extends Container implements TaggedContainerInterface
54 * @var ExtensionInterface[]
56 private $extensions = array();
59 * @var ExtensionInterface[]
61 private $extensionsByNs = array();
66 private $definitions = array();
71 private $aliasDefinitions = array();
74 * @var ResourceInterface[]
76 private $resources = array();
78 private $extensionConfigs = array();
85 private $trackResources;
88 * @var InstantiatorInterface|null
90 private $proxyInstantiator;
93 * @var ExpressionLanguage|null
95 private $expressionLanguage;
98 * @var ExpressionFunctionProviderInterface[]
100 private $expressionLanguageProviders = array();
103 * @var string[] with tag names used by findTaggedServiceIds
105 private $usedTags = array();
108 * @var string[][] a map of env var names to their placeholders
110 private $envPlaceholders = array();
113 * @var int[] a map of env vars to their resolution counter
115 private $envCounters = array();
118 * @var string[] the list of vendor directories
122 private $autoconfiguredInstanceof = array();
124 private $removedIds = array();
126 private static $internalTypes = array(
140 public function __construct(ParameterBagInterface $parameterBag = null)
142 parent::__construct($parameterBag);
144 $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface');
145 $this->setDefinition('service_container', (new Definition(ContainerInterface::class))->setSynthetic(true)->setPublic(true));
146 $this->setAlias(PsrContainerInterface::class, new Alias('service_container', false));
147 $this->setAlias(ContainerInterface::class, new Alias('service_container', false));
151 * @var \ReflectionClass[] a list of class reflectors
153 private $classReflectors;
156 * Sets the track resources flag.
158 * If you are not using the loaders and therefore don't want
159 * to depend on the Config component, set this flag to false.
161 * @param bool $track True if you want to track resources, false otherwise
163 public function setResourceTracking($track)
165 $this->trackResources = (bool) $track;
169 * Checks if resources are tracked.
171 * @return bool true If resources are tracked, false otherwise
173 public function isTrackingResources()
175 return $this->trackResources;
179 * Sets the instantiator to be used when fetching proxies.
181 public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)
183 $this->proxyInstantiator = $proxyInstantiator;
186 public function registerExtension(ExtensionInterface $extension)
188 $this->extensions[$extension->getAlias()] = $extension;
190 if (false !== $extension->getNamespace()) {
191 $this->extensionsByNs[$extension->getNamespace()] = $extension;
196 * Returns an extension by alias or namespace.
198 * @param string $name An alias or a namespace
200 * @return ExtensionInterface An extension instance
202 * @throws LogicException if the extension is not registered
204 public function getExtension($name)
206 if (isset($this->extensions[$name])) {
207 return $this->extensions[$name];
210 if (isset($this->extensionsByNs[$name])) {
211 return $this->extensionsByNs[$name];
214 throw new LogicException(sprintf('Container extension "%s" is not registered', $name));
218 * Returns all registered extensions.
220 * @return ExtensionInterface[] An array of ExtensionInterface
222 public function getExtensions()
224 return $this->extensions;
228 * Checks if we have an extension.
230 * @param string $name The name of the extension
232 * @return bool If the extension exists
234 public function hasExtension($name)
236 return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
240 * Returns an array of resources loaded to build this configuration.
242 * @return ResourceInterface[] An array of resources
244 public function getResources()
246 return array_values($this->resources);
252 public function addResource(ResourceInterface $resource)
254 if (!$this->trackResources) {
258 if ($resource instanceof GlobResource && $this->inVendors($resource->getPrefix())) {
262 $this->resources[(string) $resource] = $resource;
268 * Sets the resources for this configuration.
270 * @param ResourceInterface[] $resources An array of resources
274 public function setResources(array $resources)
276 if (!$this->trackResources) {
280 $this->resources = $resources;
286 * Adds the object class hierarchy as resources.
288 * @param object|string $object An object instance or class name
292 public function addObjectResource($object)
294 if ($this->trackResources) {
295 if (\is_object($object)) {
296 $object = \get_class($object);
298 if (!isset($this->classReflectors[$object])) {
299 $this->classReflectors[$object] = new \ReflectionClass($object);
301 $class = $this->classReflectors[$object];
303 foreach ($class->getInterfaceNames() as $name) {
304 if (null === $interface = &$this->classReflectors[$name]) {
305 $interface = new \ReflectionClass($name);
307 $file = $interface->getFileName();
308 if (false !== $file && file_exists($file)) {
309 $this->fileExists($file);
313 $file = $class->getFileName();
314 if (false !== $file && file_exists($file)) {
315 $this->fileExists($file);
317 foreach ($class->getTraitNames() as $name) {
318 $this->addObjectResource($name);
320 } while ($class = $class->getParentClass());
327 * Adds the given class hierarchy as resources.
331 * @deprecated since version 3.3, to be removed in 4.0. Use addObjectResource() or getReflectionClass() instead.
333 public function addClassResource(\ReflectionClass $class)
335 @trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the addObjectResource() or the getReflectionClass() method instead.', E_USER_DEPRECATED);
337 return $this->addObjectResource($class->name);
341 * Retrieves the requested reflection class and registers it for resource tracking.
343 * @param string $class
346 * @return \ReflectionClass|null
348 * @throws \ReflectionException when a parent class/interface/trait is not found and $throw is true
352 public function getReflectionClass($class, $throw = true)
354 if (!$class = $this->getParameterBag()->resolveValue($class)) {
358 if (isset(self::$internalTypes[$class])) {
365 if (isset($this->classReflectors[$class])) {
366 $classReflector = $this->classReflectors[$class];
367 } elseif ($this->trackResources) {
368 $resource = new ClassExistenceResource($class, false);
369 $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class);
371 $classReflector = new \ReflectionClass($class);
373 } catch (\ReflectionException $e) {
377 $classReflector = false;
380 if ($this->trackResources) {
381 if (!$classReflector) {
382 $this->addResource($resource ?: new ClassExistenceResource($class, false));
383 } elseif (!$classReflector->isInternal()) {
384 $path = $classReflector->getFileName();
386 if (!$this->inVendors($path)) {
387 $this->addResource(new ReflectionClassResource($classReflector, $this->vendors));
390 $this->classReflectors[$class] = $classReflector;
393 return $classReflector ?: null;
397 * Checks whether the requested file or directory exists and registers the result for resource tracking.
399 * @param string $path The file or directory path for which to check the existence
400 * @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed,
401 * it will be used as pattern for tracking contents of the requested directory
407 public function fileExists($path, $trackContents = true)
409 $exists = file_exists($path);
411 if (!$this->trackResources || $this->inVendors($path)) {
416 $this->addResource(new FileExistenceResource($path));
422 if ($trackContents) {
423 $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null));
425 $this->addResource(new GlobResource($path, '/*', false));
427 } elseif ($trackContents) {
428 $this->addResource(new FileResource($path));
435 * Loads the configuration for an extension.
437 * @param string $extension The extension alias or namespace
438 * @param array $values An array of values that customizes the extension
442 * @throws BadMethodCallException When this ContainerBuilder is compiled
443 * @throws \LogicException if the extension is not registered
445 public function loadFromExtension($extension, array $values = null)
447 if ($this->isCompiled()) {
448 throw new BadMethodCallException('Cannot load from an extension on a compiled container.');
451 if (\func_num_args() < 2) {
455 $namespace = $this->getExtension($extension)->getAlias();
457 $this->extensionConfigs[$namespace][] = $values;
463 * Adds a compiler pass.
465 * @param CompilerPassInterface $pass A compiler pass
466 * @param string $type The type of compiler pass
467 * @param int $priority Used to sort the passes
471 public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/)
473 if (\func_num_args() >= 3) {
474 $priority = func_get_arg(2);
476 if (__CLASS__ !== \get_class($this)) {
477 $r = new \ReflectionMethod($this, __FUNCTION__);
478 if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
479 @trigger_error(sprintf('Method %s() will have a third `int $priority = 0` argument in version 4.0. Not defining it is deprecated since Symfony 3.2.', __METHOD__), E_USER_DEPRECATED);
486 $this->getCompiler()->addPass($pass, $type, $priority);
488 $this->addObjectResource($pass);
494 * Returns the compiler pass config which can then be modified.
496 * @return PassConfig The compiler pass config
498 public function getCompilerPassConfig()
500 return $this->getCompiler()->getPassConfig();
504 * Returns the compiler.
506 * @return Compiler The compiler
508 public function getCompiler()
510 if (null === $this->compiler) {
511 $this->compiler = new Compiler();
514 return $this->compiler;
520 * @param string $id The service identifier
521 * @param object $service The service instance
523 * @throws BadMethodCallException When this ContainerBuilder is compiled
525 public function set($id, $service)
527 $id = $this->normalizeId($id);
529 if ($this->isCompiled() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) {
530 // setting a synthetic service on a compiled container is alright
531 throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a compiled container is not allowed.', $id));
534 unset($this->definitions[$id], $this->aliasDefinitions[$id], $this->removedIds[$id]);
536 parent::set($id, $service);
540 * Removes a service definition.
542 * @param string $id The service identifier
544 public function removeDefinition($id)
546 if (isset($this->definitions[$id = $this->normalizeId($id)])) {
547 unset($this->definitions[$id]);
548 $this->removedIds[$id] = true;
553 * Returns true if the given service is defined.
555 * @param string $id The service identifier
557 * @return bool true if the service is defined, false otherwise
559 public function has($id)
561 $id = $this->normalizeId($id);
563 return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id);
569 * @param string $id The service identifier
570 * @param int $invalidBehavior The behavior when the service does not exist
572 * @return object The associated service
574 * @throws InvalidArgumentException when no definitions are available
575 * @throws ServiceCircularReferenceException When a circular reference is detected
576 * @throws ServiceNotFoundException When the service is not defined
581 public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
583 if ($this->isCompiled() && isset($this->removedIds[$id = $this->normalizeId($id)])) {
584 @trigger_error(sprintf('Fetching the "%s" private service or alias is deprecated since Symfony 3.4 and will fail in 4.0. Make it public instead.', $id), E_USER_DEPRECATED);
587 return $this->doGet($id, $invalidBehavior);
590 private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = null, $isConstructorArgument = false)
592 $id = $this->normalizeId($id);
594 if (isset($inlineServices[$id])) {
595 return $inlineServices[$id];
597 if (null === $inlineServices) {
598 $isConstructorArgument = true;
599 $inlineServices = array();
602 if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) {
603 return parent::get($id, $invalidBehavior);
605 if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
608 } catch (ServiceCircularReferenceException $e) {
609 if ($isConstructorArgument) {
614 if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) {
615 return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices, $isConstructorArgument);
619 $definition = $this->getDefinition($id);
620 } catch (ServiceNotFoundException $e) {
621 if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
628 if ($isConstructorArgument) {
629 $this->loading[$id] = true;
633 return $this->createService($definition, $inlineServices, $isConstructorArgument, $id);
635 if ($isConstructorArgument) {
636 unset($this->loading[$id]);
642 * Merges a ContainerBuilder with the current ContainerBuilder configuration.
644 * Service definitions overrides the current defined ones.
646 * But for parameters, they are overridden by the current ones. It allows
647 * the parameters passed to the container constructor to have precedence
648 * over the loaded ones.
650 * $container = new ContainerBuilder(new ParameterBag(array('foo' => 'bar')));
651 * $loader = new LoaderXXX($container);
652 * $loader->load('resource_name');
653 * $container->register('foo', 'stdClass');
655 * In the above example, even if the loaded resource defines a foo
656 * parameter, the value will still be 'bar' as defined in the ContainerBuilder
659 * @throws BadMethodCallException When this ContainerBuilder is compiled
661 public function merge(self $container)
663 if ($this->isCompiled()) {
664 throw new BadMethodCallException('Cannot merge on a compiled container.');
667 $this->addDefinitions($container->getDefinitions());
668 $this->addAliases($container->getAliases());
669 $this->getParameterBag()->add($container->getParameterBag()->all());
671 if ($this->trackResources) {
672 foreach ($container->getResources() as $resource) {
673 $this->addResource($resource);
677 foreach ($this->extensions as $name => $extension) {
678 if (!isset($this->extensionConfigs[$name])) {
679 $this->extensionConfigs[$name] = array();
682 $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
685 if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) {
686 $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders();
687 $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag());
689 $envPlaceholders = array();
692 foreach ($container->envCounters as $env => $count) {
693 if (!$count && !isset($envPlaceholders[$env])) {
696 if (!isset($this->envCounters[$env])) {
697 $this->envCounters[$env] = $count;
699 $this->envCounters[$env] += $count;
703 foreach ($container->getAutoconfiguredInstanceof() as $interface => $childDefinition) {
704 if (isset($this->autoconfiguredInstanceof[$interface])) {
705 throw new InvalidArgumentException(sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.', $interface));
708 $this->autoconfiguredInstanceof[$interface] = $childDefinition;
713 * Returns the configuration array for the given extension.
715 * @param string $name The name of the extension
717 * @return array An array of configuration
719 public function getExtensionConfig($name)
721 if (!isset($this->extensionConfigs[$name])) {
722 $this->extensionConfigs[$name] = array();
725 return $this->extensionConfigs[$name];
729 * Prepends a config array to the configs of the given extension.
731 * @param string $name The name of the extension
732 * @param array $config The config to set
734 public function prependExtensionConfig($name, array $config)
736 if (!isset($this->extensionConfigs[$name])) {
737 $this->extensionConfigs[$name] = array();
740 array_unshift($this->extensionConfigs[$name], $config);
744 * Compiles the container.
746 * This method passes the container to compiler
747 * passes whose job is to manipulate and optimize
750 * The main compiler passes roughly do four things:
752 * * The extension configurations are merged;
753 * * Parameter values are resolved;
754 * * The parameter bag is frozen;
755 * * Extension loading is disabled.
757 * @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current
758 * env vars or be replaced by uniquely identifiable placeholders.
759 * Set to "true" when you want to use the current ContainerBuilder
760 * directly, keep to "false" when the container is dumped instead.
762 public function compile(/*$resolveEnvPlaceholders = false*/)
764 if (1 <= \func_num_args()) {
765 $resolveEnvPlaceholders = func_get_arg(0);
767 if (__CLASS__ !== static::class) {
768 $r = new \ReflectionMethod($this, __FUNCTION__);
769 if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) {
770 @trigger_error(sprintf('The %s::compile() method expects a first "$resolveEnvPlaceholders" argument since Symfony 3.3. It will be made mandatory in 4.0.', static::class), E_USER_DEPRECATED);
773 $resolveEnvPlaceholders = false;
775 $compiler = $this->getCompiler();
777 if ($this->trackResources) {
778 foreach ($compiler->getPassConfig()->getPasses() as $pass) {
779 $this->addObjectResource($pass);
782 $bag = $this->getParameterBag();
784 if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) {
785 $compiler->addPass(new ResolveEnvPlaceholdersPass(), PassConfig::TYPE_AFTER_REMOVING, -1000);
788 $compiler->compile($this);
790 foreach ($this->definitions as $id => $definition) {
791 if ($this->trackResources && $definition->isLazy()) {
792 $this->getReflectionClass($definition->getClass());
796 $this->extensionConfigs = array();
798 if ($bag instanceof EnvPlaceholderParameterBag) {
799 if ($resolveEnvPlaceholders) {
800 $this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true));
803 $this->envPlaceholders = $bag->getEnvPlaceholders();
808 foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) {
809 if (!$definition->isPublic() || $definition->isPrivate()) {
810 $this->removedIds[$id] = true;
816 * Gets all service ids.
818 * @return array An array of all defined service ids
820 public function getServiceIds()
822 return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()));
826 * Gets removed service or alias ids.
830 public function getRemovedIds()
832 return $this->removedIds;
836 * Adds the service aliases.
838 public function addAliases(array $aliases)
840 foreach ($aliases as $alias => $id) {
841 $this->setAlias($alias, $id);
846 * Sets the service aliases.
848 public function setAliases(array $aliases)
850 $this->aliasDefinitions = array();
851 $this->addAliases($aliases);
855 * Sets an alias for an existing service.
857 * @param string $alias The alias to create
858 * @param string|Alias $id The service to alias
862 * @throws InvalidArgumentException if the id is not a string or an Alias
863 * @throws InvalidArgumentException if the alias is for itself
865 public function setAlias($alias, $id)
867 $alias = $this->normalizeId($alias);
869 if (\is_string($id)) {
870 $id = new Alias($this->normalizeId($id));
871 } elseif (!$id instanceof Alias) {
872 throw new InvalidArgumentException('$id must be a string, or an Alias object.');
875 if ($alias === (string) $id) {
876 throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
879 unset($this->definitions[$alias], $this->removedIds[$alias]);
881 return $this->aliasDefinitions[$alias] = $id;
887 * @param string $alias The alias to remove
889 public function removeAlias($alias)
891 if (isset($this->aliasDefinitions[$alias = $this->normalizeId($alias)])) {
892 unset($this->aliasDefinitions[$alias]);
893 $this->removedIds[$alias] = true;
898 * Returns true if an alias exists under the given identifier.
900 * @param string $id The service identifier
902 * @return bool true if the alias exists, false otherwise
904 public function hasAlias($id)
906 return isset($this->aliasDefinitions[$this->normalizeId($id)]);
910 * Gets all defined aliases.
912 * @return Alias[] An array of aliases
914 public function getAliases()
916 return $this->aliasDefinitions;
922 * @param string $id The service identifier
924 * @return Alias An Alias instance
926 * @throws InvalidArgumentException if the alias does not exist
928 public function getAlias($id)
930 $id = $this->normalizeId($id);
932 if (!isset($this->aliasDefinitions[$id])) {
933 throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
936 return $this->aliasDefinitions[$id];
940 * Registers a service definition.
942 * This methods allows for simple registration of service definition
943 * with a fluid interface.
945 * @param string $id The service identifier
946 * @param string $class|null The service class
948 * @return Definition A Definition instance
950 public function register($id, $class = null)
952 return $this->setDefinition($id, new Definition($class));
956 * Registers an autowired service definition.
958 * This method implements a shortcut for using setDefinition() with
959 * an autowired definition.
961 * @param string $id The service identifier
962 * @param string|null $class The service class
964 * @return Definition The created definition
966 public function autowire($id, $class = null)
968 return $this->setDefinition($id, (new Definition($class))->setAutowired(true));
972 * Adds the service definitions.
974 * @param Definition[] $definitions An array of service definitions
976 public function addDefinitions(array $definitions)
978 foreach ($definitions as $id => $definition) {
979 $this->setDefinition($id, $definition);
984 * Sets the service definitions.
986 * @param Definition[] $definitions An array of service definitions
988 public function setDefinitions(array $definitions)
990 $this->definitions = array();
991 $this->addDefinitions($definitions);
995 * Gets all service definitions.
997 * @return Definition[] An array of Definition instances
999 public function getDefinitions()
1001 return $this->definitions;
1005 * Sets a service definition.
1007 * @param string $id The service identifier
1008 * @param Definition $definition A Definition instance
1010 * @return Definition the service definition
1012 * @throws BadMethodCallException When this ContainerBuilder is compiled
1014 public function setDefinition($id, Definition $definition)
1016 if ($this->isCompiled()) {
1017 throw new BadMethodCallException('Adding definition to a compiled container is not allowed');
1020 $id = $this->normalizeId($id);
1022 unset($this->aliasDefinitions[$id], $this->removedIds[$id]);
1024 return $this->definitions[$id] = $definition;
1028 * Returns true if a service definition exists under the given identifier.
1030 * @param string $id The service identifier
1032 * @return bool true if the service definition exists, false otherwise
1034 public function hasDefinition($id)
1036 return isset($this->definitions[$this->normalizeId($id)]);
1040 * Gets a service definition.
1042 * @param string $id The service identifier
1044 * @return Definition A Definition instance
1046 * @throws ServiceNotFoundException if the service definition does not exist
1048 public function getDefinition($id)
1050 $id = $this->normalizeId($id);
1052 if (!isset($this->definitions[$id])) {
1053 throw new ServiceNotFoundException($id);
1056 return $this->definitions[$id];
1060 * Gets a service definition by id or alias.
1062 * The method "unaliases" recursively to return a Definition instance.
1064 * @param string $id The service identifier or alias
1066 * @return Definition A Definition instance
1068 * @throws ServiceNotFoundException if the service definition does not exist
1070 public function findDefinition($id)
1072 $id = $this->normalizeId($id);
1075 while (isset($this->aliasDefinitions[$id])) {
1076 $id = (string) $this->aliasDefinitions[$id];
1078 if (isset($seen[$id])) {
1079 $seen = array_values($seen);
1080 $seen = \array_slice($seen, array_search($id, $seen));
1083 throw new ServiceCircularReferenceException($id, $seen);
1089 return $this->getDefinition($id);
1093 * Creates a service for a service definition.
1095 * @param Definition $definition A service definition instance
1096 * @param string $id The service identifier
1097 * @param bool $tryProxy Whether to try proxying the service with a lazy proxy
1099 * @return object The service described by the service definition
1101 * @throws RuntimeException When the factory definition is incomplete
1102 * @throws RuntimeException When the service is a synthetic service
1103 * @throws InvalidArgumentException When configure callable is not callable
1105 private function createService(Definition $definition, array &$inlineServices, $isConstructorArgument = false, $id = null, $tryProxy = true)
1107 if (null === $id && isset($inlineServices[$h = spl_object_hash($definition)])) {
1108 return $inlineServices[$h];
1111 if ($definition instanceof ChildDefinition) {
1112 throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
1115 if ($definition->isSynthetic()) {
1116 throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
1119 if ($definition->isDeprecated()) {
1120 @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED);
1123 if ($tryProxy && $definition->isLazy() && !$tryProxy = !($proxy = $this->proxyInstantiator) || $proxy instanceof RealServiceInstantiator) {
1124 $proxy = $proxy->instantiateProxy(
1127 $id, function () use ($definition, &$inlineServices, $id) {
1128 return $this->createService($definition, $inlineServices, true, $id, false);
1131 $this->shareService($definition, $proxy, $id, $inlineServices);
1136 $parameterBag = $this->getParameterBag();
1138 if (null !== $definition->getFile()) {
1139 require_once $parameterBag->resolveValue($definition->getFile());
1142 $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument);
1144 if (null !== $factory = $definition->getFactory()) {
1145 if (\is_array($factory)) {
1146 $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]);
1147 } elseif (!\is_string($factory)) {
1148 throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
1152 if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) {
1153 return $this->services[$id];
1156 if (null !== $factory) {
1157 $service = \call_user_func_array($factory, $arguments);
1159 if (!$definition->isDeprecated() && \is_array($factory) && \is_string($factory[0])) {
1160 $r = new \ReflectionClass($factory[0]);
1162 if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
1163 @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);
1167 $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass()));
1169 $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
1170 // don't trigger deprecations for internal uses
1171 // @deprecated since version 3.3, to be removed in 4.0 along with the deprecated class
1172 $deprecationWhitelist = array('event_dispatcher' => ContainerAwareEventDispatcher::class);
1174 if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ") && (!isset($deprecationWhitelist[$id]) || $deprecationWhitelist[$id] !== $class)) {
1175 @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);
1179 if ($tryProxy || !$definition->isLazy()) {
1180 // share only if proxying failed, or if not a proxy
1181 $this->shareService($definition, $service, $id, $inlineServices);
1184 $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlineServices);
1185 foreach ($properties as $name => $value) {
1186 $service->$name = $value;
1189 foreach ($definition->getMethodCalls() as $call) {
1190 $this->callMethod($service, $call, $inlineServices);
1193 if ($callable = $definition->getConfigurator()) {
1194 if (\is_array($callable)) {
1195 $callable[0] = $parameterBag->resolveValue($callable[0]);
1197 if ($callable[0] instanceof Reference) {
1198 $callable[0] = $this->doGet((string) $callable[0], $callable[0]->getInvalidBehavior(), $inlineServices);
1199 } elseif ($callable[0] instanceof Definition) {
1200 $callable[0] = $this->createService($callable[0], $inlineServices);
1204 if (!\is_callable($callable)) {
1205 throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', \get_class($service)));
1208 \call_user_func($callable, $service);
1215 * Replaces service references by the real service instance and evaluates expressions.
1217 * @param mixed $value A value
1219 * @return mixed The same value with all service references replaced by
1220 * the real service instances and all expressions evaluated
1222 public function resolveServices($value)
1224 return $this->doResolveServices($value);
1227 private function doResolveServices($value, array &$inlineServices = array(), $isConstructorArgument = false)
1229 if (\is_array($value)) {
1230 foreach ($value as $k => $v) {
1231 $value[$k] = $this->doResolveServices($v, $inlineServices, $isConstructorArgument);
1233 } elseif ($value instanceof ServiceClosureArgument) {
1234 $reference = $value->getValues()[0];
1235 $value = function () use ($reference) {
1236 return $this->resolveServices($reference);
1238 } elseif ($value instanceof IteratorArgument) {
1239 $value = new RewindableGenerator(function () use ($value) {
1240 foreach ($value->getValues() as $k => $v) {
1241 foreach (self::getServiceConditionals($v) as $s) {
1242 if (!$this->has($s)) {
1246 foreach (self::getInitializedConditionals($v) as $s) {
1247 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1252 yield $k => $this->resolveServices($v);
1254 }, function () use ($value) {
1256 foreach ($value->getValues() as $v) {
1257 foreach (self::getServiceConditionals($v) as $s) {
1258 if (!$this->has($s)) {
1262 foreach (self::getInitializedConditionals($v) as $s) {
1263 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1273 } elseif ($value instanceof Reference) {
1274 $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument);
1275 } elseif ($value instanceof Definition) {
1276 $value = $this->createService($value, $inlineServices, $isConstructorArgument);
1277 } elseif ($value instanceof Parameter) {
1278 $value = $this->getParameter((string) $value);
1279 } elseif ($value instanceof Expression) {
1280 $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
1287 * Returns service ids for a given tag.
1291 * $container->register('foo')->addTag('my.tag', array('hello' => 'world'));
1293 * $serviceIds = $container->findTaggedServiceIds('my.tag');
1294 * foreach ($serviceIds as $serviceId => $tags) {
1295 * foreach ($tags as $tag) {
1296 * echo $tag['hello'];
1300 * @param string $name
1301 * @param bool $throwOnAbstract
1303 * @return array An array of tags with the tagged service as key, holding a list of attribute arrays
1305 public function findTaggedServiceIds($name, $throwOnAbstract = false)
1307 $this->usedTags[] = $name;
1309 foreach ($this->getDefinitions() as $id => $definition) {
1310 if ($definition->hasTag($name)) {
1311 if ($throwOnAbstract && $definition->isAbstract()) {
1312 throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must not be abstract.', $id, $name));
1314 $tags[$id] = $definition->getTag($name);
1322 * Returns all tags the defined services use.
1324 * @return array An array of tags
1326 public function findTags()
1329 foreach ($this->getDefinitions() as $id => $definition) {
1330 $tags = array_merge(array_keys($definition->getTags()), $tags);
1333 return array_unique($tags);
1337 * Returns all tags not queried by findTaggedServiceIds.
1339 * @return string[] An array of tags
1341 public function findUnusedTags()
1343 return array_values(array_diff($this->findTags(), $this->usedTags));
1346 public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
1348 $this->expressionLanguageProviders[] = $provider;
1352 * @return ExpressionFunctionProviderInterface[]
1354 public function getExpressionLanguageProviders()
1356 return $this->expressionLanguageProviders;
1360 * Returns a ChildDefinition that will be used for autoconfiguring the interface/class.
1362 * @param string $interface The class or interface to match
1364 * @return ChildDefinition
1366 public function registerForAutoconfiguration($interface)
1368 if (!isset($this->autoconfiguredInstanceof[$interface])) {
1369 $this->autoconfiguredInstanceof[$interface] = new ChildDefinition('');
1372 return $this->autoconfiguredInstanceof[$interface];
1376 * Returns an array of ChildDefinition[] keyed by interface.
1378 * @return ChildDefinition[]
1380 public function getAutoconfiguredInstanceof()
1382 return $this->autoconfiguredInstanceof;
1386 * Resolves env parameter placeholders in a string or an array.
1388 * @param mixed $value The value to resolve
1389 * @param string|true|null $format A sprintf() format returning the replacement for each env var name or
1390 * null to resolve back to the original "%env(VAR)%" format or
1391 * true to resolve to the actual values of the referenced env vars
1392 * @param array &$usedEnvs Env vars found while resolving are added to this array
1394 * @return mixed The value with env parameters resolved if a string or an array is passed
1396 public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null)
1398 if (null === $format) {
1399 $format = '%%env(%s)%%';
1402 $bag = $this->getParameterBag();
1403 if (true === $format) {
1404 $value = $bag->resolveValue($value);
1407 if (\is_array($value)) {
1409 foreach ($value as $k => $v) {
1410 $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs);
1416 if (!\is_string($value) || 38 > \strlen($value)) {
1419 $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1422 foreach ($envPlaceholders as $env => $placeholders) {
1423 foreach ($placeholders as $placeholder) {
1424 if (false !== stripos($value, $placeholder)) {
1425 if (true === $format) {
1426 $resolved = $bag->escapeValue($this->getEnv($env));
1428 $resolved = sprintf($format, $env);
1430 if ($placeholder === $value) {
1434 if (!\is_string($resolved) && !is_numeric($resolved)) {
1435 throw new RuntimeException(sprintf('A string value must be composed of strings and/or numbers, but found parameter "env(%s)" of type %s inside string value "%s".', $env, \gettype($resolved), $this->resolveEnvPlaceholders($value)));
1437 $value = str_ireplace($placeholder, $resolved, $value);
1439 $usedEnvs[$env] = $env;
1440 $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1;
1453 * Get statistics about env usage.
1455 * @return int[] The number of time each env vars has been resolved
1457 public function getEnvCounters()
1459 $bag = $this->getParameterBag();
1460 $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1462 foreach ($envPlaceholders as $env => $placeholders) {
1463 if (!isset($this->envCounters[$env])) {
1464 $this->envCounters[$env] = 0;
1468 return $this->envCounters;
1474 public function getNormalizedIds()
1476 $normalizedIds = array();
1478 foreach ($this->normalizedIds as $k => $v) {
1479 if ($v !== (string) $k) {
1480 $normalizedIds[$k] = $v;
1484 return $normalizedIds;
1490 public function log(CompilerPassInterface $pass, $message)
1492 $this->getCompiler()->log($pass, $this->resolveEnvPlaceholders($message));
1498 public function normalizeId($id)
1500 if (!\is_string($id)) {
1504 return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || isset($this->removedIds[$id]) ? $id : parent::normalizeId($id);
1508 * Returns the Service Conditionals.
1510 * @param mixed $value An array of conditionals to return
1512 * @return array An array of Service conditionals
1514 * @internal since version 3.4
1516 public static function getServiceConditionals($value)
1518 $services = array();
1520 if (\is_array($value)) {
1521 foreach ($value as $v) {
1522 $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
1524 } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) {
1525 $services[] = (string) $value;
1532 * Returns the initialized conditionals.
1534 * @param mixed $value An array of conditionals to return
1536 * @return array An array of uninitialized conditionals
1540 public static function getInitializedConditionals($value)
1542 $services = array();
1544 if (\is_array($value)) {
1545 foreach ($value as $v) {
1546 $services = array_unique(array_merge($services, self::getInitializedConditionals($v)));
1548 } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior()) {
1549 $services[] = (string) $value;
1556 * Computes a reasonably unique hash of a value.
1558 * @param mixed $value A serializable value
1562 public static function hash($value)
1564 $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7);
1566 return str_replace(array('/', '+'), array('.', '_'), strtolower($hash));
1572 protected function getEnv($name)
1574 $value = parent::getEnv($name);
1575 $bag = $this->getParameterBag();
1577 if (!\is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) {
1581 foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
1582 if (isset($placeholders[$value])) {
1583 $bag = new ParameterBag($bag->all());
1585 return $bag->unescapeValue($bag->get("env($name)"));
1589 $this->resolving["env($name)"] = true;
1591 return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true));
1593 unset($this->resolving["env($name)"]);
1597 private function callMethod($service, $call, array &$inlineServices)
1599 foreach (self::getServiceConditionals($call[1]) as $s) {
1600 if (!$this->has($s)) {
1604 foreach (self::getInitializedConditionals($call[1]) as $s) {
1605 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE, $inlineServices)) {
1610 \call_user_func_array(array($service, $call[0]), $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices));
1614 * Shares a given service in the container.
1616 * @param Definition $definition
1617 * @param object $service
1618 * @param string|null $id
1620 private function shareService(Definition $definition, $service, $id, array &$inlineServices)
1622 $inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service;
1624 if (null !== $id && $definition->isShared()) {
1625 $this->services[$id] = $service;
1626 unset($this->loading[$id]);
1630 private function getExpressionLanguage()
1632 if (null === $this->expressionLanguage) {
1633 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1634 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1636 $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
1639 return $this->expressionLanguage;
1642 private function inVendors($path)
1644 if (null === $this->vendors) {
1645 $resource = new ComposerResource();
1646 $this->vendors = $resource->getVendors();
1647 $this->addResource($resource);
1649 $path = realpath($path) ?: $path;
1651 foreach ($this->vendors as $vendor) {
1652 if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {