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\DependencyInjection\Argument\IteratorArgument;
16 use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
17 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
18 use Symfony\Component\DependencyInjection\Compiler\Compiler;
19 use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
20 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
21 use Symfony\Component\DependencyInjection\Compiler\ResolveEnvPlaceholdersPass;
22 use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
23 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
24 use Symfony\Component\DependencyInjection\Exception\LogicException;
25 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
26 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
27 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
28 use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
29 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
30 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
31 use Symfony\Component\Config\Resource\ClassExistenceResource;
32 use Symfony\Component\Config\Resource\ComposerResource;
33 use Symfony\Component\Config\Resource\DirectoryResource;
34 use Symfony\Component\Config\Resource\FileExistenceResource;
35 use Symfony\Component\Config\Resource\FileResource;
36 use Symfony\Component\Config\Resource\GlobResource;
37 use Symfony\Component\Config\Resource\ReflectionClassResource;
38 use Symfony\Component\Config\Resource\ResourceInterface;
39 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
40 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
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();
125 private $alreadyLoading = array();
127 private static $internalTypes = array(
141 public function __construct(ParameterBagInterface $parameterBag = null)
143 parent::__construct($parameterBag);
145 $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface');
146 $this->setDefinition('service_container', (new Definition(ContainerInterface::class))->setSynthetic(true)->setPublic(true));
147 $this->setAlias(PsrContainerInterface::class, new Alias('service_container', false));
148 $this->setAlias(ContainerInterface::class, new Alias('service_container', false));
152 * @var \ReflectionClass[] a list of class reflectors
154 private $classReflectors;
157 * Sets the track resources flag.
159 * If you are not using the loaders and therefore don't want
160 * to depend on the Config component, set this flag to false.
162 * @param bool $track True if you want to track resources, false otherwise
164 public function setResourceTracking($track)
166 $this->trackResources = (bool) $track;
170 * Checks if resources are tracked.
172 * @return bool true If resources are tracked, false otherwise
174 public function isTrackingResources()
176 return $this->trackResources;
180 * Sets the instantiator to be used when fetching proxies.
182 public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)
184 $this->proxyInstantiator = $proxyInstantiator;
187 public function registerExtension(ExtensionInterface $extension)
189 $this->extensions[$extension->getAlias()] = $extension;
191 if (false !== $extension->getNamespace()) {
192 $this->extensionsByNs[$extension->getNamespace()] = $extension;
197 * Returns an extension by alias or namespace.
199 * @param string $name An alias or a namespace
201 * @return ExtensionInterface An extension instance
203 * @throws LogicException if the extension is not registered
205 public function getExtension($name)
207 if (isset($this->extensions[$name])) {
208 return $this->extensions[$name];
211 if (isset($this->extensionsByNs[$name])) {
212 return $this->extensionsByNs[$name];
215 throw new LogicException(sprintf('Container extension "%s" is not registered', $name));
219 * Returns all registered extensions.
221 * @return ExtensionInterface[] An array of ExtensionInterface
223 public function getExtensions()
225 return $this->extensions;
229 * Checks if we have an extension.
231 * @param string $name The name of the extension
233 * @return bool If the extension exists
235 public function hasExtension($name)
237 return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
241 * Returns an array of resources loaded to build this configuration.
243 * @return ResourceInterface[] An array of resources
245 public function getResources()
247 return array_values($this->resources);
253 public function addResource(ResourceInterface $resource)
255 if (!$this->trackResources) {
259 if ($resource instanceof GlobResource && $this->inVendors($resource->getPrefix())) {
263 $this->resources[(string) $resource] = $resource;
269 * Sets the resources for this configuration.
271 * @param ResourceInterface[] $resources An array of resources
275 public function setResources(array $resources)
277 if (!$this->trackResources) {
281 $this->resources = $resources;
287 * Adds the object class hierarchy as resources.
289 * @param object|string $object An object instance or class name
293 public function addObjectResource($object)
295 if ($this->trackResources) {
296 if (is_object($object)) {
297 $object = get_class($object);
299 if (!isset($this->classReflectors[$object])) {
300 $this->classReflectors[$object] = new \ReflectionClass($object);
302 $class = $this->classReflectors[$object];
304 foreach ($class->getInterfaceNames() as $name) {
305 if (null === $interface = &$this->classReflectors[$name]) {
306 $interface = new \ReflectionClass($name);
308 $file = $interface->getFileName();
309 if (false !== $file && file_exists($file)) {
310 $this->fileExists($file);
314 $file = $class->getFileName();
315 if (false !== $file && file_exists($file)) {
316 $this->fileExists($file);
318 foreach ($class->getTraitNames() as $name) {
319 $this->addObjectResource($name);
321 } while ($class = $class->getParentClass());
328 * Adds the given class hierarchy as resources.
332 * @deprecated since version 3.3, to be removed in 4.0. Use addObjectResource() or getReflectionClass() instead.
334 public function addClassResource(\ReflectionClass $class)
336 @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);
338 return $this->addObjectResource($class->name);
342 * Retrieves the requested reflection class and registers it for resource tracking.
344 * @param string $class
347 * @return \ReflectionClass|null
349 * @throws \ReflectionException when a parent class/interface/trait is not found and $throw is true
353 public function getReflectionClass($class, $throw = true)
355 if (!$class = $this->getParameterBag()->resolveValue($class)) {
359 if (isset(self::$internalTypes[$class])) {
366 if (isset($this->classReflectors[$class])) {
367 $classReflector = $this->classReflectors[$class];
368 } elseif ($this->trackResources) {
369 $resource = new ClassExistenceResource($class, false);
370 $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class);
372 $classReflector = new \ReflectionClass($class);
374 } catch (\ReflectionException $e) {
378 $classReflector = false;
381 if ($this->trackResources) {
382 if (!$classReflector) {
383 $this->addResource($resource ?: new ClassExistenceResource($class, false));
384 } elseif (!$classReflector->isInternal()) {
385 $path = $classReflector->getFileName();
387 if (!$this->inVendors($path)) {
388 $this->addResource(new ReflectionClassResource($classReflector, $this->vendors));
391 $this->classReflectors[$class] = $classReflector;
394 return $classReflector ?: null;
398 * Checks whether the requested file or directory exists and registers the result for resource tracking.
400 * @param string $path The file or directory path for which to check the existence
401 * @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed,
402 * it will be used as pattern for tracking contents of the requested directory
408 public function fileExists($path, $trackContents = true)
410 $exists = file_exists($path);
412 if (!$this->trackResources || $this->inVendors($path)) {
417 $this->addResource(new FileExistenceResource($path));
423 if ($trackContents) {
424 $this->addResource(new DirectoryResource($path, is_string($trackContents) ? $trackContents : null));
426 $this->addResource(new GlobResource($path, '/*', false));
428 } elseif ($trackContents) {
429 $this->addResource(new FileResource($path));
436 * Loads the configuration for an extension.
438 * @param string $extension The extension alias or namespace
439 * @param array $values An array of values that customizes the extension
443 * @throws BadMethodCallException When this ContainerBuilder is compiled
444 * @throws \LogicException if the extension is not registered
446 public function loadFromExtension($extension, array $values = null)
448 if ($this->isCompiled()) {
449 throw new BadMethodCallException('Cannot load from an extension on a compiled container.');
452 if (func_num_args() < 2) {
456 $namespace = $this->getExtension($extension)->getAlias();
458 $this->extensionConfigs[$namespace][] = $values;
464 * Adds a compiler pass.
466 * @param CompilerPassInterface $pass A compiler pass
467 * @param string $type The type of compiler pass
468 * @param int $priority Used to sort the passes
472 public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/)
474 if (func_num_args() >= 3) {
475 $priority = func_get_arg(2);
477 if (__CLASS__ !== get_class($this)) {
478 $r = new \ReflectionMethod($this, __FUNCTION__);
479 if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
480 @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);
487 $this->getCompiler()->addPass($pass, $type, $priority);
489 $this->addObjectResource($pass);
495 * Returns the compiler pass config which can then be modified.
497 * @return PassConfig The compiler pass config
499 public function getCompilerPassConfig()
501 return $this->getCompiler()->getPassConfig();
505 * Returns the compiler.
507 * @return Compiler The compiler
509 public function getCompiler()
511 if (null === $this->compiler) {
512 $this->compiler = new Compiler();
515 return $this->compiler;
521 * @param string $id The service identifier
522 * @param object $service The service instance
524 * @throws BadMethodCallException When this ContainerBuilder is compiled
526 public function set($id, $service)
528 $id = $this->normalizeId($id);
530 if ($this->isCompiled() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) {
531 // setting a synthetic service on a compiled container is alright
532 throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a compiled container is not allowed.', $id));
535 unset($this->definitions[$id], $this->aliasDefinitions[$id], $this->removedIds[$id]);
537 parent::set($id, $service);
541 * Removes a service definition.
543 * @param string $id The service identifier
545 public function removeDefinition($id)
547 if (isset($this->definitions[$id = $this->normalizeId($id)])) {
548 unset($this->definitions[$id]);
549 $this->removedIds[$id] = true;
554 * Returns true if the given service is defined.
556 * @param string $id The service identifier
558 * @return bool true if the service is defined, false otherwise
560 public function has($id)
562 $id = $this->normalizeId($id);
564 return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id);
570 * @param string $id The service identifier
571 * @param int $invalidBehavior The behavior when the service does not exist
573 * @return object The associated service
575 * @throws InvalidArgumentException when no definitions are available
576 * @throws ServiceCircularReferenceException When a circular reference is detected
577 * @throws ServiceNotFoundException When the service is not defined
582 public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
584 if ($this->isCompiled() && isset($this->removedIds[$id = $this->normalizeId($id)])) {
585 @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);
588 return $this->doGet($id, $invalidBehavior);
591 private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = array())
593 $id = $this->normalizeId($id);
595 if (isset($inlineServices[$id])) {
596 return $inlineServices[$id];
598 if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) {
599 return parent::get($id, $invalidBehavior);
601 if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
605 if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) {
606 return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices);
610 $definition = $this->getDefinition($id);
611 } catch (ServiceNotFoundException $e) {
612 if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
619 $loading = isset($this->alreadyLoading[$id]) ? 'loading' : 'alreadyLoading';
620 $this->{$loading}[$id] = true;
623 $service = $this->createService($definition, $inlineServices, $id);
625 unset($this->{$loading}[$id]);
632 * Merges a ContainerBuilder with the current ContainerBuilder configuration.
634 * Service definitions overrides the current defined ones.
636 * But for parameters, they are overridden by the current ones. It allows
637 * the parameters passed to the container constructor to have precedence
638 * over the loaded ones.
640 * $container = new ContainerBuilder(array('foo' => 'bar'));
641 * $loader = new LoaderXXX($container);
642 * $loader->load('resource_name');
643 * $container->register('foo', new stdClass());
645 * In the above example, even if the loaded resource defines a foo
646 * parameter, the value will still be 'bar' as defined in the ContainerBuilder
649 * @throws BadMethodCallException When this ContainerBuilder is compiled
651 public function merge(self $container)
653 if ($this->isCompiled()) {
654 throw new BadMethodCallException('Cannot merge on a compiled container.');
657 $this->addDefinitions($container->getDefinitions());
658 $this->addAliases($container->getAliases());
659 $this->getParameterBag()->add($container->getParameterBag()->all());
661 if ($this->trackResources) {
662 foreach ($container->getResources() as $resource) {
663 $this->addResource($resource);
667 foreach ($this->extensions as $name => $extension) {
668 if (!isset($this->extensionConfigs[$name])) {
669 $this->extensionConfigs[$name] = array();
672 $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
675 if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) {
676 $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders();
677 $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag());
679 $envPlaceholders = array();
682 foreach ($container->envCounters as $env => $count) {
683 if (!$count && !isset($envPlaceholders[$env])) {
686 if (!isset($this->envCounters[$env])) {
687 $this->envCounters[$env] = $count;
689 $this->envCounters[$env] += $count;
693 foreach ($container->getAutoconfiguredInstanceof() as $interface => $childDefinition) {
694 if (isset($this->autoconfiguredInstanceof[$interface])) {
695 throw new InvalidArgumentException(sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.', $interface));
698 $this->autoconfiguredInstanceof[$interface] = $childDefinition;
703 * Returns the configuration array for the given extension.
705 * @param string $name The name of the extension
707 * @return array An array of configuration
709 public function getExtensionConfig($name)
711 if (!isset($this->extensionConfigs[$name])) {
712 $this->extensionConfigs[$name] = array();
715 return $this->extensionConfigs[$name];
719 * Prepends a config array to the configs of the given extension.
721 * @param string $name The name of the extension
722 * @param array $config The config to set
724 public function prependExtensionConfig($name, array $config)
726 if (!isset($this->extensionConfigs[$name])) {
727 $this->extensionConfigs[$name] = array();
730 array_unshift($this->extensionConfigs[$name], $config);
734 * Compiles the container.
736 * This method passes the container to compiler
737 * passes whose job is to manipulate and optimize
740 * The main compiler passes roughly do four things:
742 * * The extension configurations are merged;
743 * * Parameter values are resolved;
744 * * The parameter bag is frozen;
745 * * Extension loading is disabled.
747 * @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current
748 * env vars or be replaced by uniquely identifiable placeholders.
749 * Set to "true" when you want to use the current ContainerBuilder
750 * directly, keep to "false" when the container is dumped instead.
752 public function compile(/*$resolveEnvPlaceholders = false*/)
754 if (1 <= func_num_args()) {
755 $resolveEnvPlaceholders = func_get_arg(0);
757 if (__CLASS__ !== static::class) {
758 $r = new \ReflectionMethod($this, __FUNCTION__);
759 if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) {
760 @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);
763 $resolveEnvPlaceholders = false;
765 $compiler = $this->getCompiler();
767 if ($this->trackResources) {
768 foreach ($compiler->getPassConfig()->getPasses() as $pass) {
769 $this->addObjectResource($pass);
772 $bag = $this->getParameterBag();
774 if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) {
775 $compiler->addPass(new ResolveEnvPlaceholdersPass(), PassConfig::TYPE_AFTER_REMOVING, -1000);
778 $compiler->compile($this);
780 foreach ($this->definitions as $id => $definition) {
781 if ($this->trackResources && $definition->isLazy()) {
782 $this->getReflectionClass($definition->getClass());
786 $this->extensionConfigs = array();
788 if ($bag instanceof EnvPlaceholderParameterBag) {
789 if ($resolveEnvPlaceholders) {
790 $this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true));
793 $this->envPlaceholders = $bag->getEnvPlaceholders();
798 foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) {
799 if (!$definition->isPublic() || $definition->isPrivate()) {
800 $this->removedIds[$id] = true;
806 * Gets all service ids.
808 * @return array An array of all defined service ids
810 public function getServiceIds()
812 return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()));
816 * Gets removed service or alias ids.
820 public function getRemovedIds()
822 return $this->removedIds;
826 * Adds the service aliases.
828 public function addAliases(array $aliases)
830 foreach ($aliases as $alias => $id) {
831 $this->setAlias($alias, $id);
836 * Sets the service aliases.
838 public function setAliases(array $aliases)
840 $this->aliasDefinitions = array();
841 $this->addAliases($aliases);
845 * Sets an alias for an existing service.
847 * @param string $alias The alias to create
848 * @param string|Alias $id The service to alias
852 * @throws InvalidArgumentException if the id is not a string or an Alias
853 * @throws InvalidArgumentException if the alias is for itself
855 public function setAlias($alias, $id)
857 $alias = $this->normalizeId($alias);
859 if (is_string($id)) {
860 $id = new Alias($this->normalizeId($id));
861 } elseif (!$id instanceof Alias) {
862 throw new InvalidArgumentException('$id must be a string, or an Alias object.');
865 if ($alias === (string) $id) {
866 throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
869 unset($this->definitions[$alias], $this->removedIds[$alias]);
871 return $this->aliasDefinitions[$alias] = $id;
877 * @param string $alias The alias to remove
879 public function removeAlias($alias)
881 if (isset($this->aliasDefinitions[$alias = $this->normalizeId($alias)])) {
882 unset($this->aliasDefinitions[$alias]);
883 $this->removedIds[$alias] = true;
888 * Returns true if an alias exists under the given identifier.
890 * @param string $id The service identifier
892 * @return bool true if the alias exists, false otherwise
894 public function hasAlias($id)
896 return isset($this->aliasDefinitions[$this->normalizeId($id)]);
900 * Gets all defined aliases.
902 * @return Alias[] An array of aliases
904 public function getAliases()
906 return $this->aliasDefinitions;
912 * @param string $id The service identifier
914 * @return Alias An Alias instance
916 * @throws InvalidArgumentException if the alias does not exist
918 public function getAlias($id)
920 $id = $this->normalizeId($id);
922 if (!isset($this->aliasDefinitions[$id])) {
923 throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
926 return $this->aliasDefinitions[$id];
930 * Registers a service definition.
932 * This methods allows for simple registration of service definition
933 * with a fluid interface.
935 * @param string $id The service identifier
936 * @param string $class|null The service class
938 * @return Definition A Definition instance
940 public function register($id, $class = null)
942 return $this->setDefinition($id, new Definition($class));
946 * Registers an autowired service definition.
948 * This method implements a shortcut for using setDefinition() with
949 * an autowired definition.
951 * @param string $id The service identifier
952 * @param null|string $class The service class
954 * @return Definition The created definition
956 public function autowire($id, $class = null)
958 return $this->setDefinition($id, (new Definition($class))->setAutowired(true));
962 * Adds the service definitions.
964 * @param Definition[] $definitions An array of service definitions
966 public function addDefinitions(array $definitions)
968 foreach ($definitions as $id => $definition) {
969 $this->setDefinition($id, $definition);
974 * Sets the service definitions.
976 * @param Definition[] $definitions An array of service definitions
978 public function setDefinitions(array $definitions)
980 $this->definitions = array();
981 $this->addDefinitions($definitions);
985 * Gets all service definitions.
987 * @return Definition[] An array of Definition instances
989 public function getDefinitions()
991 return $this->definitions;
995 * Sets a service definition.
997 * @param string $id The service identifier
998 * @param Definition $definition A Definition instance
1000 * @return Definition the service definition
1002 * @throws BadMethodCallException When this ContainerBuilder is compiled
1004 public function setDefinition($id, Definition $definition)
1006 if ($this->isCompiled()) {
1007 throw new BadMethodCallException('Adding definition to a compiled container is not allowed');
1010 $id = $this->normalizeId($id);
1012 unset($this->aliasDefinitions[$id], $this->removedIds[$id]);
1014 return $this->definitions[$id] = $definition;
1018 * Returns true if a service definition exists under the given identifier.
1020 * @param string $id The service identifier
1022 * @return bool true if the service definition exists, false otherwise
1024 public function hasDefinition($id)
1026 return isset($this->definitions[$this->normalizeId($id)]);
1030 * Gets a service definition.
1032 * @param string $id The service identifier
1034 * @return Definition A Definition instance
1036 * @throws ServiceNotFoundException if the service definition does not exist
1038 public function getDefinition($id)
1040 $id = $this->normalizeId($id);
1042 if (!isset($this->definitions[$id])) {
1043 throw new ServiceNotFoundException($id);
1046 return $this->definitions[$id];
1050 * Gets a service definition by id or alias.
1052 * The method "unaliases" recursively to return a Definition instance.
1054 * @param string $id The service identifier or alias
1056 * @return Definition A Definition instance
1058 * @throws ServiceNotFoundException if the service definition does not exist
1060 public function findDefinition($id)
1062 $id = $this->normalizeId($id);
1065 while (isset($this->aliasDefinitions[$id])) {
1066 $id = (string) $this->aliasDefinitions[$id];
1068 if (isset($seen[$id])) {
1069 $seen = array_values($seen);
1070 $seen = array_slice($seen, array_search($id, $seen));
1073 throw new ServiceCircularReferenceException($id, $seen);
1079 return $this->getDefinition($id);
1083 * Creates a service for a service definition.
1085 * @param Definition $definition A service definition instance
1086 * @param string $id The service identifier
1087 * @param bool $tryProxy Whether to try proxying the service with a lazy proxy
1089 * @return object The service described by the service definition
1091 * @throws RuntimeException When the factory definition is incomplete
1092 * @throws RuntimeException When the service is a synthetic service
1093 * @throws InvalidArgumentException When configure callable is not callable
1095 private function createService(Definition $definition, array &$inlineServices, $id = null, $tryProxy = true)
1097 if (null === $id && isset($inlineServices[$h = spl_object_hash($definition)])) {
1098 return $inlineServices[$h];
1101 if ($definition instanceof ChildDefinition) {
1102 throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
1105 if ($definition->isSynthetic()) {
1106 throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
1109 if ($definition->isDeprecated()) {
1110 @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED);
1113 if ($tryProxy && $definition->isLazy()) {
1115 ->getProxyInstantiator()
1119 $id, function () use ($definition, &$inlineServices, $id) {
1120 return $this->createService($definition, $inlineServices, $id, false);
1123 $this->shareService($definition, $proxy, $id, $inlineServices);
1128 $parameterBag = $this->getParameterBag();
1130 if (null !== $definition->getFile()) {
1131 require_once $parameterBag->resolveValue($definition->getFile());
1134 $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices);
1136 if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) {
1137 return $this->services[$id];
1140 if (null !== $factory = $definition->getFactory()) {
1141 if (is_array($factory)) {
1142 $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices), $factory[1]);
1143 } elseif (!is_string($factory)) {
1144 throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
1147 $service = call_user_func_array($factory, $arguments);
1149 if (!$definition->isDeprecated() && is_array($factory) && is_string($factory[0])) {
1150 $r = new \ReflectionClass($factory[0]);
1152 if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
1153 @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);
1157 $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass()));
1159 $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
1160 // don't trigger deprecations for internal uses
1161 // @deprecated since version 3.3, to be removed in 4.0 along with the deprecated class
1162 $deprecationWhitelist = array('event_dispatcher' => ContainerAwareEventDispatcher::class);
1164 if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ") && (!isset($deprecationWhitelist[$id]) || $deprecationWhitelist[$id] !== $class)) {
1165 @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);
1169 if ($tryProxy || !$definition->isLazy()) {
1170 // share only if proxying failed, or if not a proxy
1171 $this->shareService($definition, $service, $id, $inlineServices);
1174 $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlineServices);
1175 foreach ($properties as $name => $value) {
1176 $service->$name = $value;
1179 foreach ($definition->getMethodCalls() as $call) {
1180 $this->callMethod($service, $call, $inlineServices);
1183 if ($callable = $definition->getConfigurator()) {
1184 if (is_array($callable)) {
1185 $callable[0] = $parameterBag->resolveValue($callable[0]);
1187 if ($callable[0] instanceof Reference) {
1188 $callable[0] = $this->doGet((string) $callable[0], $callable[0]->getInvalidBehavior(), $inlineServices);
1189 } elseif ($callable[0] instanceof Definition) {
1190 $callable[0] = $this->createService($callable[0], $inlineServices);
1194 if (!is_callable($callable)) {
1195 throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service)));
1198 call_user_func($callable, $service);
1205 * Replaces service references by the real service instance and evaluates expressions.
1207 * @param mixed $value A value
1209 * @return mixed The same value with all service references replaced by
1210 * the real service instances and all expressions evaluated
1212 public function resolveServices($value)
1214 return $this->doResolveServices($value);
1217 private function doResolveServices($value, array &$inlineServices = array())
1219 if (is_array($value)) {
1220 foreach ($value as $k => $v) {
1221 $value[$k] = $this->doResolveServices($v, $inlineServices);
1223 } elseif ($value instanceof ServiceClosureArgument) {
1224 $reference = $value->getValues()[0];
1225 $value = function () use ($reference) {
1226 return $this->resolveServices($reference);
1228 } elseif ($value instanceof IteratorArgument) {
1229 $value = new RewindableGenerator(function () use ($value) {
1230 foreach ($value->getValues() as $k => $v) {
1231 foreach (self::getServiceConditionals($v) as $s) {
1232 if (!$this->has($s)) {
1236 foreach (self::getInitializedConditionals($v) as $s) {
1237 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1242 yield $k => $this->resolveServices($v);
1244 }, function () use ($value) {
1246 foreach ($value->getValues() as $v) {
1247 foreach (self::getServiceConditionals($v) as $s) {
1248 if (!$this->has($s)) {
1252 foreach (self::getInitializedConditionals($v) as $s) {
1253 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1263 } elseif ($value instanceof Reference) {
1264 $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices);
1265 } elseif ($value instanceof Definition) {
1266 $value = $this->createService($value, $inlineServices);
1267 } elseif ($value instanceof Parameter) {
1268 $value = $this->getParameter((string) $value);
1269 } elseif ($value instanceof Expression) {
1270 $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
1277 * Returns service ids for a given tag.
1281 * $container->register('foo')->addTag('my.tag', array('hello' => 'world'));
1283 * $serviceIds = $container->findTaggedServiceIds('my.tag');
1284 * foreach ($serviceIds as $serviceId => $tags) {
1285 * foreach ($tags as $tag) {
1286 * echo $tag['hello'];
1290 * @param string $name
1291 * @param bool $throwOnAbstract
1293 * @return array An array of tags with the tagged service as key, holding a list of attribute arrays
1295 public function findTaggedServiceIds($name, $throwOnAbstract = false)
1297 $this->usedTags[] = $name;
1299 foreach ($this->getDefinitions() as $id => $definition) {
1300 if ($definition->hasTag($name)) {
1301 if ($throwOnAbstract && $definition->isAbstract()) {
1302 throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must not be abstract.', $id, $name));
1304 $tags[$id] = $definition->getTag($name);
1312 * Returns all tags the defined services use.
1314 * @return array An array of tags
1316 public function findTags()
1319 foreach ($this->getDefinitions() as $id => $definition) {
1320 $tags = array_merge(array_keys($definition->getTags()), $tags);
1323 return array_unique($tags);
1327 * Returns all tags not queried by findTaggedServiceIds.
1329 * @return string[] An array of tags
1331 public function findUnusedTags()
1333 return array_values(array_diff($this->findTags(), $this->usedTags));
1336 public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
1338 $this->expressionLanguageProviders[] = $provider;
1342 * @return ExpressionFunctionProviderInterface[]
1344 public function getExpressionLanguageProviders()
1346 return $this->expressionLanguageProviders;
1350 * Returns a ChildDefinition that will be used for autoconfiguring the interface/class.
1352 * @param string $interface The class or interface to match
1354 * @return ChildDefinition
1356 public function registerForAutoconfiguration($interface)
1358 if (!isset($this->autoconfiguredInstanceof[$interface])) {
1359 $this->autoconfiguredInstanceof[$interface] = new ChildDefinition('');
1362 return $this->autoconfiguredInstanceof[$interface];
1366 * Returns an array of ChildDefinition[] keyed by interface.
1368 * @return ChildDefinition[]
1370 public function getAutoconfiguredInstanceof()
1372 return $this->autoconfiguredInstanceof;
1376 * Resolves env parameter placeholders in a string or an array.
1378 * @param mixed $value The value to resolve
1379 * @param string|true|null $format A sprintf() format returning the replacement for each env var name or
1380 * null to resolve back to the original "%env(VAR)%" format or
1381 * true to resolve to the actual values of the referenced env vars
1382 * @param array &$usedEnvs Env vars found while resolving are added to this array
1384 * @return mixed The value with env parameters resolved if a string or an array is passed
1386 public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null)
1388 if (null === $format) {
1389 $format = '%%env(%s)%%';
1392 $bag = $this->getParameterBag();
1393 if (true === $format) {
1394 $value = $bag->resolveValue($value);
1397 if (\is_array($value)) {
1399 foreach ($value as $k => $v) {
1400 $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs);
1406 if (!\is_string($value) || 38 > \strlen($value)) {
1409 $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1412 foreach ($envPlaceholders as $env => $placeholders) {
1413 foreach ($placeholders as $placeholder) {
1414 if (false !== stripos($value, $placeholder)) {
1415 if (true === $format) {
1416 $resolved = $bag->escapeValue($this->getEnv($env));
1418 $resolved = sprintf($format, $env);
1420 if ($placeholder === $value) {
1424 if (!is_string($resolved) && !is_numeric($resolved)) {
1425 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)));
1427 $value = str_ireplace($placeholder, $resolved, $value);
1429 $usedEnvs[$env] = $env;
1430 $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1;
1443 * Get statistics about env usage.
1445 * @return int[] The number of time each env vars has been resolved
1447 public function getEnvCounters()
1449 $bag = $this->getParameterBag();
1450 $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1452 foreach ($envPlaceholders as $env => $placeholders) {
1453 if (!isset($this->envCounters[$env])) {
1454 $this->envCounters[$env] = 0;
1458 return $this->envCounters;
1464 public function getNormalizedIds()
1466 $normalizedIds = array();
1468 foreach ($this->normalizedIds as $k => $v) {
1469 if ($v !== (string) $k) {
1470 $normalizedIds[$k] = $v;
1474 return $normalizedIds;
1480 public function log(CompilerPassInterface $pass, $message)
1482 $this->getCompiler()->log($pass, $message);
1488 public function normalizeId($id)
1490 if (!\is_string($id)) {
1494 return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || isset($this->removedIds[$id]) ? $id : parent::normalizeId($id);
1498 * Returns the Service Conditionals.
1500 * @param mixed $value An array of conditionals to return
1502 * @return array An array of Service conditionals
1504 * @internal since version 3.4
1506 public static function getServiceConditionals($value)
1508 $services = array();
1510 if (is_array($value)) {
1511 foreach ($value as $v) {
1512 $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
1514 } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) {
1515 $services[] = (string) $value;
1522 * Returns the initialized conditionals.
1524 * @param mixed $value An array of conditionals to return
1526 * @return array An array of uninitialized conditionals
1530 public static function getInitializedConditionals($value)
1532 $services = array();
1534 if (is_array($value)) {
1535 foreach ($value as $v) {
1536 $services = array_unique(array_merge($services, self::getInitializedConditionals($v)));
1538 } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior()) {
1539 $services[] = (string) $value;
1546 * Computes a reasonably unique hash of a value.
1548 * @param mixed $value A serializable value
1552 public static function hash($value)
1554 $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7);
1556 return str_replace(array('/', '+'), array('.', '_'), strtolower($hash));
1562 protected function getEnv($name)
1564 $value = parent::getEnv($name);
1565 $bag = $this->getParameterBag();
1567 if (!is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) {
1571 foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
1572 if (isset($placeholders[$value])) {
1573 $bag = new ParameterBag($bag->all());
1575 return $bag->unescapeValue($bag->get("env($name)"));
1579 $this->resolving["env($name)"] = true;
1581 return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true));
1583 unset($this->resolving["env($name)"]);
1588 * Retrieves the currently set proxy instantiator or instantiates one.
1590 * @return InstantiatorInterface
1592 private function getProxyInstantiator()
1594 if (!$this->proxyInstantiator) {
1595 $this->proxyInstantiator = new RealServiceInstantiator();
1598 return $this->proxyInstantiator;
1601 private function callMethod($service, $call, array &$inlineServices)
1603 foreach (self::getServiceConditionals($call[1]) as $s) {
1604 if (!$this->has($s)) {
1608 foreach (self::getInitializedConditionals($call[1]) as $s) {
1609 if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE, $inlineServices)) {
1614 call_user_func_array(array($service, $call[0]), $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices));
1618 * Shares a given service in the container.
1620 * @param Definition $definition
1621 * @param object $service
1622 * @param string|null $id
1624 private function shareService(Definition $definition, $service, $id, array &$inlineServices)
1626 $inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service;
1628 if (null !== $id && $definition->isShared()) {
1629 $this->services[$id] = $service;
1630 unset($this->loading[$id], $this->alreadyLoading[$id]);
1634 private function getExpressionLanguage()
1636 if (null === $this->expressionLanguage) {
1637 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1638 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1640 $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
1643 return $this->expressionLanguage;
1646 private function inVendors($path)
1648 if (null === $this->vendors) {
1649 $resource = new ComposerResource();
1650 $this->vendors = $resource->getVendors();
1651 $this->addResource($resource);
1653 $path = realpath($path) ?: $path;
1655 foreach ($this->vendors as $vendor) {
1656 if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, strlen($vendor), 1), '/'.DIRECTORY_SEPARATOR)) {