Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\DependencyInjection; Chris@0: Chris@14: use Psr\Container\ContainerInterface as PsrContainerInterface; Chris@17: use Symfony\Component\Config\Resource\ClassExistenceResource; Chris@17: use Symfony\Component\Config\Resource\ComposerResource; Chris@17: use Symfony\Component\Config\Resource\DirectoryResource; Chris@17: use Symfony\Component\Config\Resource\FileExistenceResource; Chris@17: use Symfony\Component\Config\Resource\FileResource; Chris@17: use Symfony\Component\Config\Resource\GlobResource; Chris@17: use Symfony\Component\Config\Resource\ReflectionClassResource; Chris@17: use Symfony\Component\Config\Resource\ResourceInterface; Chris@14: use Symfony\Component\DependencyInjection\Argument\IteratorArgument; Chris@14: use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; Chris@14: use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; Chris@0: use Symfony\Component\DependencyInjection\Compiler\Compiler; Chris@0: use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; Chris@0: use Symfony\Component\DependencyInjection\Compiler\PassConfig; Chris@14: use Symfony\Component\DependencyInjection\Compiler\ResolveEnvPlaceholdersPass; Chris@0: use Symfony\Component\DependencyInjection\Exception\BadMethodCallException; Chris@0: use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\DependencyInjection\Exception\LogicException; Chris@0: use Symfony\Component\DependencyInjection\Exception\RuntimeException; Chris@0: use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; Chris@0: use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; Chris@0: use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; Chris@17: use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface; Chris@17: use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; Chris@14: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; Chris@14: use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; Chris@0: use Symfony\Component\ExpressionLanguage\Expression; Chris@0: use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; Chris@0: Chris@0: /** Chris@0: * ContainerBuilder is a DI container that provides an API to easily describe services. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class ContainerBuilder extends Container implements TaggedContainerInterface Chris@0: { Chris@0: /** Chris@0: * @var ExtensionInterface[] Chris@0: */ Chris@17: private $extensions = []; Chris@0: Chris@0: /** Chris@0: * @var ExtensionInterface[] Chris@0: */ Chris@17: private $extensionsByNs = []; Chris@0: Chris@0: /** Chris@0: * @var Definition[] Chris@0: */ Chris@17: private $definitions = []; Chris@0: Chris@0: /** Chris@0: * @var Alias[] Chris@0: */ Chris@17: private $aliasDefinitions = []; Chris@0: Chris@0: /** Chris@0: * @var ResourceInterface[] Chris@0: */ Chris@17: private $resources = []; Chris@0: Chris@17: private $extensionConfigs = []; Chris@0: Chris@0: /** Chris@0: * @var Compiler Chris@0: */ Chris@0: private $compiler; Chris@0: Chris@0: private $trackResources; Chris@0: Chris@0: /** Chris@0: * @var InstantiatorInterface|null Chris@0: */ Chris@0: private $proxyInstantiator; Chris@0: Chris@0: /** Chris@0: * @var ExpressionLanguage|null Chris@0: */ Chris@0: private $expressionLanguage; Chris@0: Chris@0: /** Chris@0: * @var ExpressionFunctionProviderInterface[] Chris@0: */ Chris@17: private $expressionLanguageProviders = []; Chris@0: Chris@0: /** Chris@0: * @var string[] with tag names used by findTaggedServiceIds Chris@0: */ Chris@17: private $usedTags = []; Chris@0: Chris@0: /** Chris@0: * @var string[][] a map of env var names to their placeholders Chris@0: */ Chris@17: private $envPlaceholders = []; Chris@0: Chris@0: /** Chris@0: * @var int[] a map of env vars to their resolution counter Chris@0: */ Chris@17: private $envCounters = []; Chris@0: Chris@0: /** Chris@14: * @var string[] the list of vendor directories Chris@14: */ Chris@14: private $vendors; Chris@14: Chris@17: private $autoconfiguredInstanceof = []; Chris@14: Chris@17: private $removedIds = []; Chris@14: Chris@18: private $removedBindingIds = []; Chris@18: Chris@17: private static $internalTypes = [ Chris@16: 'int' => true, Chris@16: 'float' => true, Chris@16: 'string' => true, Chris@16: 'bool' => true, Chris@16: 'resource' => true, Chris@16: 'object' => true, Chris@16: 'array' => true, Chris@16: 'null' => true, Chris@16: 'callable' => true, Chris@16: 'iterable' => true, Chris@16: 'mixed' => true, Chris@17: ]; Chris@16: Chris@14: public function __construct(ParameterBagInterface $parameterBag = null) Chris@14: { Chris@14: parent::__construct($parameterBag); Chris@14: Chris@14: $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface'); Chris@14: $this->setDefinition('service_container', (new Definition(ContainerInterface::class))->setSynthetic(true)->setPublic(true)); Chris@14: $this->setAlias(PsrContainerInterface::class, new Alias('service_container', false)); Chris@14: $this->setAlias(ContainerInterface::class, new Alias('service_container', false)); Chris@14: } Chris@14: Chris@14: /** Chris@14: * @var \ReflectionClass[] a list of class reflectors Chris@14: */ Chris@14: private $classReflectors; Chris@14: Chris@14: /** Chris@0: * Sets the track resources flag. Chris@0: * Chris@0: * If you are not using the loaders and therefore don't want Chris@0: * to depend on the Config component, set this flag to false. Chris@0: * Chris@14: * @param bool $track True if you want to track resources, false otherwise Chris@0: */ Chris@0: public function setResourceTracking($track) Chris@0: { Chris@0: $this->trackResources = (bool) $track; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if resources are tracked. Chris@0: * Chris@14: * @return bool true If resources are tracked, false otherwise Chris@0: */ Chris@0: public function isTrackingResources() Chris@0: { Chris@0: return $this->trackResources; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the instantiator to be used when fetching proxies. Chris@0: */ Chris@0: public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator) Chris@0: { Chris@0: $this->proxyInstantiator = $proxyInstantiator; Chris@0: } Chris@0: Chris@0: public function registerExtension(ExtensionInterface $extension) Chris@0: { Chris@0: $this->extensions[$extension->getAlias()] = $extension; Chris@0: Chris@0: if (false !== $extension->getNamespace()) { Chris@0: $this->extensionsByNs[$extension->getNamespace()] = $extension; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns an extension by alias or namespace. Chris@0: * Chris@0: * @param string $name An alias or a namespace Chris@0: * Chris@0: * @return ExtensionInterface An extension instance Chris@0: * Chris@0: * @throws LogicException if the extension is not registered Chris@0: */ Chris@0: public function getExtension($name) Chris@0: { Chris@0: if (isset($this->extensions[$name])) { Chris@0: return $this->extensions[$name]; Chris@0: } Chris@0: Chris@0: if (isset($this->extensionsByNs[$name])) { Chris@0: return $this->extensionsByNs[$name]; Chris@0: } Chris@0: Chris@0: throw new LogicException(sprintf('Container extension "%s" is not registered', $name)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all registered extensions. Chris@0: * Chris@0: * @return ExtensionInterface[] An array of ExtensionInterface Chris@0: */ Chris@0: public function getExtensions() Chris@0: { Chris@0: return $this->extensions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if we have an extension. Chris@0: * Chris@0: * @param string $name The name of the extension Chris@0: * Chris@0: * @return bool If the extension exists Chris@0: */ Chris@0: public function hasExtension($name) Chris@0: { Chris@0: return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns an array of resources loaded to build this configuration. Chris@0: * Chris@0: * @return ResourceInterface[] An array of resources Chris@0: */ Chris@0: public function getResources() Chris@0: { Chris@14: return array_values($this->resources); Chris@0: } Chris@0: Chris@0: /** Chris@0: * @return $this Chris@0: */ Chris@0: public function addResource(ResourceInterface $resource) Chris@0: { Chris@0: if (!$this->trackResources) { Chris@0: return $this; Chris@0: } Chris@0: Chris@14: if ($resource instanceof GlobResource && $this->inVendors($resource->getPrefix())) { Chris@14: return $this; Chris@14: } Chris@14: Chris@14: $this->resources[(string) $resource] = $resource; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the resources for this configuration. Chris@0: * Chris@0: * @param ResourceInterface[] $resources An array of resources Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setResources(array $resources) Chris@0: { Chris@0: if (!$this->trackResources) { Chris@0: return $this; Chris@0: } Chris@0: Chris@0: $this->resources = $resources; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the object class hierarchy as resources. Chris@0: * Chris@14: * @param object|string $object An object instance or class name Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addObjectResource($object) Chris@0: { Chris@0: if ($this->trackResources) { Chris@17: if (\is_object($object)) { Chris@17: $object = \get_class($object); Chris@14: } Chris@14: if (!isset($this->classReflectors[$object])) { Chris@14: $this->classReflectors[$object] = new \ReflectionClass($object); Chris@14: } Chris@14: $class = $this->classReflectors[$object]; Chris@14: Chris@14: foreach ($class->getInterfaceNames() as $name) { Chris@14: if (null === $interface = &$this->classReflectors[$name]) { Chris@14: $interface = new \ReflectionClass($name); Chris@14: } Chris@14: $file = $interface->getFileName(); Chris@14: if (false !== $file && file_exists($file)) { Chris@14: $this->fileExists($file); Chris@14: } Chris@14: } Chris@14: do { Chris@14: $file = $class->getFileName(); Chris@14: if (false !== $file && file_exists($file)) { Chris@14: $this->fileExists($file); Chris@14: } Chris@14: foreach ($class->getTraitNames() as $name) { Chris@14: $this->addObjectResource($name); Chris@14: } Chris@14: } while ($class = $class->getParentClass()); Chris@0: } Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the given class hierarchy as resources. Chris@0: * Chris@14: * @return $this Chris@0: * Chris@14: * @deprecated since version 3.3, to be removed in 4.0. Use addObjectResource() or getReflectionClass() instead. Chris@0: */ Chris@0: public function addClassResource(\ReflectionClass $class) Chris@0: { Chris@14: @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); Chris@14: Chris@14: return $this->addObjectResource($class->name); Chris@14: } Chris@14: Chris@14: /** Chris@14: * Retrieves the requested reflection class and registers it for resource tracking. Chris@14: * Chris@14: * @param string $class Chris@14: * @param bool $throw Chris@14: * Chris@14: * @return \ReflectionClass|null Chris@14: * Chris@14: * @throws \ReflectionException when a parent class/interface/trait is not found and $throw is true Chris@14: * Chris@14: * @final Chris@14: */ Chris@14: public function getReflectionClass($class, $throw = true) Chris@14: { Chris@14: if (!$class = $this->getParameterBag()->resolveValue($class)) { Chris@14: return; Chris@14: } Chris@16: Chris@16: if (isset(self::$internalTypes[$class])) { Chris@16: return null; Chris@16: } Chris@16: Chris@14: $resource = null; Chris@14: Chris@14: try { Chris@14: if (isset($this->classReflectors[$class])) { Chris@14: $classReflector = $this->classReflectors[$class]; Chris@17: } elseif (class_exists(ClassExistenceResource::class)) { Chris@14: $resource = new ClassExistenceResource($class, false); Chris@14: $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class); Chris@14: } else { Chris@17: $classReflector = class_exists($class) ? new \ReflectionClass($class) : false; Chris@14: } Chris@14: } catch (\ReflectionException $e) { Chris@14: if ($throw) { Chris@14: throw $e; Chris@14: } Chris@14: $classReflector = false; Chris@0: } Chris@0: Chris@14: if ($this->trackResources) { Chris@14: if (!$classReflector) { Chris@14: $this->addResource($resource ?: new ClassExistenceResource($class, false)); Chris@14: } elseif (!$classReflector->isInternal()) { Chris@14: $path = $classReflector->getFileName(); Chris@14: Chris@14: if (!$this->inVendors($path)) { Chris@14: $this->addResource(new ReflectionClassResource($classReflector, $this->vendors)); Chris@14: } Chris@0: } Chris@14: $this->classReflectors[$class] = $classReflector; Chris@14: } Chris@0: Chris@14: return $classReflector ?: null; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Checks whether the requested file or directory exists and registers the result for resource tracking. Chris@14: * Chris@14: * @param string $path The file or directory path for which to check the existence Chris@14: * @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed, Chris@14: * it will be used as pattern for tracking contents of the requested directory Chris@14: * Chris@14: * @return bool Chris@14: * Chris@14: * @final Chris@14: */ Chris@14: public function fileExists($path, $trackContents = true) Chris@14: { Chris@14: $exists = file_exists($path); Chris@14: Chris@14: if (!$this->trackResources || $this->inVendors($path)) { Chris@14: return $exists; Chris@14: } Chris@14: Chris@14: if (!$exists) { Chris@14: $this->addResource(new FileExistenceResource($path)); Chris@14: Chris@14: return $exists; Chris@14: } Chris@14: Chris@14: if (is_dir($path)) { Chris@14: if ($trackContents) { Chris@17: $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null)); Chris@14: } else { Chris@14: $this->addResource(new GlobResource($path, '/*', false)); Chris@14: } Chris@14: } elseif ($trackContents) { Chris@14: $this->addResource(new FileResource($path)); Chris@14: } Chris@14: Chris@14: return $exists; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Loads the configuration for an extension. Chris@0: * Chris@0: * @param string $extension The extension alias or namespace Chris@0: * @param array $values An array of values that customizes the extension Chris@0: * Chris@0: * @return $this Chris@0: * Chris@14: * @throws BadMethodCallException When this ContainerBuilder is compiled Chris@14: * @throws \LogicException if the extension is not registered Chris@0: */ Chris@14: public function loadFromExtension($extension, array $values = null) Chris@0: { Chris@14: if ($this->isCompiled()) { Chris@14: throw new BadMethodCallException('Cannot load from an extension on a compiled container.'); Chris@14: } Chris@14: Chris@17: if (\func_num_args() < 2) { Chris@17: $values = []; Chris@0: } Chris@0: Chris@0: $namespace = $this->getExtension($extension)->getAlias(); Chris@0: Chris@0: $this->extensionConfigs[$namespace][] = $values; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds a compiler pass. Chris@0: * Chris@0: * @param CompilerPassInterface $pass A compiler pass Chris@0: * @param string $type The type of compiler pass Chris@0: * @param int $priority Used to sort the passes Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@14: public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/) Chris@0: { Chris@17: if (\func_num_args() >= 3) { Chris@0: $priority = func_get_arg(2); Chris@0: } else { Chris@17: if (__CLASS__ !== \get_class($this)) { Chris@0: $r = new \ReflectionMethod($this, __FUNCTION__); Chris@0: if (__CLASS__ !== $r->getDeclaringClass()->getName()) { Chris@14: @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); Chris@0: } Chris@0: } Chris@0: Chris@0: $priority = 0; Chris@0: } Chris@0: Chris@0: $this->getCompiler()->addPass($pass, $type, $priority); Chris@0: Chris@0: $this->addObjectResource($pass); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the compiler pass config which can then be modified. Chris@0: * Chris@0: * @return PassConfig The compiler pass config Chris@0: */ Chris@0: public function getCompilerPassConfig() Chris@0: { Chris@0: return $this->getCompiler()->getPassConfig(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the compiler. Chris@0: * Chris@0: * @return Compiler The compiler Chris@0: */ Chris@0: public function getCompiler() Chris@0: { Chris@0: if (null === $this->compiler) { Chris@0: $this->compiler = new Compiler(); Chris@0: } Chris@0: Chris@0: return $this->compiler; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a service. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * @param object $service The service instance Chris@0: * Chris@14: * @throws BadMethodCallException When this ContainerBuilder is compiled Chris@0: */ Chris@0: public function set($id, $service) Chris@0: { Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@14: if ($this->isCompiled() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) { Chris@14: // setting a synthetic service on a compiled container is alright Chris@14: throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a compiled container is not allowed.', $id)); Chris@0: } Chris@0: Chris@14: unset($this->definitions[$id], $this->aliasDefinitions[$id], $this->removedIds[$id]); Chris@0: Chris@0: parent::set($id, $service); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Removes a service definition. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: */ Chris@0: public function removeDefinition($id) Chris@0: { Chris@14: if (isset($this->definitions[$id = $this->normalizeId($id)])) { Chris@14: unset($this->definitions[$id]); Chris@14: $this->removedIds[$id] = true; Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the given service is defined. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return bool true if the service is defined, false otherwise Chris@0: */ Chris@0: public function has($id) Chris@0: { Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@0: return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a service. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * @param int $invalidBehavior The behavior when the service does not exist Chris@0: * Chris@0: * @return object The associated service Chris@0: * Chris@0: * @throws InvalidArgumentException when no definitions are available Chris@0: * @throws ServiceCircularReferenceException When a circular reference is detected Chris@0: * @throws ServiceNotFoundException When the service is not defined Chris@0: * @throws \Exception Chris@0: * Chris@0: * @see Reference Chris@0: */ Chris@0: public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) Chris@0: { Chris@14: if ($this->isCompiled() && isset($this->removedIds[$id = $this->normalizeId($id)])) { Chris@14: @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); Chris@14: } Chris@0: Chris@14: return $this->doGet($id, $invalidBehavior); Chris@14: } Chris@14: Chris@17: private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = null, $isConstructorArgument = false) Chris@14: { Chris@14: $id = $this->normalizeId($id); Chris@14: Chris@14: if (isset($inlineServices[$id])) { Chris@14: return $inlineServices[$id]; Chris@14: } Chris@17: if (null === $inlineServices) { Chris@17: $isConstructorArgument = true; Chris@17: $inlineServices = []; Chris@14: } Chris@17: try { Chris@17: if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) { Chris@17: return parent::get($id, $invalidBehavior); Chris@17: } Chris@17: if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) { Chris@17: return $service; Chris@17: } Chris@17: } catch (ServiceCircularReferenceException $e) { Chris@17: if ($isConstructorArgument) { Chris@17: throw $e; Chris@17: } Chris@0: } Chris@0: Chris@0: if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) { Chris@17: return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices, $isConstructorArgument); Chris@0: } Chris@0: Chris@0: try { Chris@0: $definition = $this->getDefinition($id); Chris@0: } catch (ServiceNotFoundException $e) { Chris@0: if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) { Chris@0: return; Chris@0: } Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@17: if ($isConstructorArgument) { Chris@17: $this->loading[$id] = true; Chris@17: } Chris@0: Chris@0: try { Chris@17: return $this->createService($definition, $inlineServices, $isConstructorArgument, $id); Chris@0: } finally { Chris@17: if ($isConstructorArgument) { Chris@17: unset($this->loading[$id]); Chris@17: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Merges a ContainerBuilder with the current ContainerBuilder configuration. Chris@0: * Chris@0: * Service definitions overrides the current defined ones. Chris@0: * Chris@0: * But for parameters, they are overridden by the current ones. It allows Chris@0: * the parameters passed to the container constructor to have precedence Chris@0: * over the loaded ones. Chris@0: * Chris@17: * $container = new ContainerBuilder(new ParameterBag(['foo' => 'bar'])); Chris@17: * $loader = new LoaderXXX($container); Chris@17: * $loader->load('resource_name'); Chris@17: * $container->register('foo', 'stdClass'); Chris@0: * Chris@0: * In the above example, even if the loaded resource defines a foo Chris@0: * parameter, the value will still be 'bar' as defined in the ContainerBuilder Chris@0: * constructor. Chris@0: * Chris@14: * @throws BadMethodCallException When this ContainerBuilder is compiled Chris@0: */ Chris@14: public function merge(self $container) Chris@0: { Chris@14: if ($this->isCompiled()) { Chris@14: throw new BadMethodCallException('Cannot merge on a compiled container.'); Chris@0: } Chris@0: Chris@0: $this->addDefinitions($container->getDefinitions()); Chris@0: $this->addAliases($container->getAliases()); Chris@0: $this->getParameterBag()->add($container->getParameterBag()->all()); Chris@0: Chris@0: if ($this->trackResources) { Chris@0: foreach ($container->getResources() as $resource) { Chris@0: $this->addResource($resource); Chris@0: } Chris@0: } Chris@0: Chris@0: foreach ($this->extensions as $name => $extension) { Chris@0: if (!isset($this->extensionConfigs[$name])) { Chris@17: $this->extensionConfigs[$name] = []; Chris@0: } Chris@0: Chris@0: $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name)); Chris@0: } Chris@0: Chris@0: if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) { Chris@14: $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders(); Chris@0: $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag()); Chris@14: } else { Chris@17: $envPlaceholders = []; Chris@0: } Chris@0: Chris@0: foreach ($container->envCounters as $env => $count) { Chris@14: if (!$count && !isset($envPlaceholders[$env])) { Chris@14: continue; Chris@14: } Chris@0: if (!isset($this->envCounters[$env])) { Chris@0: $this->envCounters[$env] = $count; Chris@0: } else { Chris@0: $this->envCounters[$env] += $count; Chris@0: } Chris@0: } Chris@14: Chris@14: foreach ($container->getAutoconfiguredInstanceof() as $interface => $childDefinition) { Chris@14: if (isset($this->autoconfiguredInstanceof[$interface])) { Chris@14: throw new InvalidArgumentException(sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.', $interface)); Chris@14: } Chris@14: Chris@14: $this->autoconfiguredInstanceof[$interface] = $childDefinition; Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the configuration array for the given extension. Chris@0: * Chris@0: * @param string $name The name of the extension Chris@0: * Chris@0: * @return array An array of configuration Chris@0: */ Chris@0: public function getExtensionConfig($name) Chris@0: { Chris@0: if (!isset($this->extensionConfigs[$name])) { Chris@17: $this->extensionConfigs[$name] = []; Chris@0: } Chris@0: Chris@0: return $this->extensionConfigs[$name]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepends a config array to the configs of the given extension. Chris@0: * Chris@0: * @param string $name The name of the extension Chris@0: * @param array $config The config to set Chris@0: */ Chris@0: public function prependExtensionConfig($name, array $config) Chris@0: { Chris@0: if (!isset($this->extensionConfigs[$name])) { Chris@17: $this->extensionConfigs[$name] = []; Chris@0: } Chris@0: Chris@0: array_unshift($this->extensionConfigs[$name], $config); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Compiles the container. Chris@0: * Chris@0: * This method passes the container to compiler Chris@0: * passes whose job is to manipulate and optimize Chris@0: * the container. Chris@0: * Chris@0: * The main compiler passes roughly do four things: Chris@0: * Chris@0: * * The extension configurations are merged; Chris@0: * * Parameter values are resolved; Chris@0: * * The parameter bag is frozen; Chris@0: * * Extension loading is disabled. Chris@14: * Chris@14: * @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current Chris@14: * env vars or be replaced by uniquely identifiable placeholders. Chris@14: * Set to "true" when you want to use the current ContainerBuilder Chris@14: * directly, keep to "false" when the container is dumped instead. Chris@0: */ Chris@14: public function compile(/*$resolveEnvPlaceholders = false*/) Chris@0: { Chris@17: if (1 <= \func_num_args()) { Chris@14: $resolveEnvPlaceholders = func_get_arg(0); Chris@14: } else { Chris@14: if (__CLASS__ !== static::class) { Chris@14: $r = new \ReflectionMethod($this, __FUNCTION__); Chris@14: if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) { Chris@14: @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); Chris@14: } Chris@14: } Chris@14: $resolveEnvPlaceholders = false; Chris@14: } Chris@0: $compiler = $this->getCompiler(); Chris@0: Chris@0: if ($this->trackResources) { Chris@0: foreach ($compiler->getPassConfig()->getPasses() as $pass) { Chris@0: $this->addObjectResource($pass); Chris@0: } Chris@0: } Chris@14: $bag = $this->getParameterBag(); Chris@14: Chris@14: if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) { Chris@14: $compiler->addPass(new ResolveEnvPlaceholdersPass(), PassConfig::TYPE_AFTER_REMOVING, -1000); Chris@14: } Chris@0: Chris@0: $compiler->compile($this); Chris@0: Chris@0: foreach ($this->definitions as $id => $definition) { Chris@14: if ($this->trackResources && $definition->isLazy()) { Chris@14: $this->getReflectionClass($definition->getClass()); Chris@0: } Chris@0: } Chris@0: Chris@17: $this->extensionConfigs = []; Chris@14: Chris@14: if ($bag instanceof EnvPlaceholderParameterBag) { Chris@14: if ($resolveEnvPlaceholders) { Chris@14: $this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true)); Chris@14: } Chris@14: Chris@14: $this->envPlaceholders = $bag->getEnvPlaceholders(); Chris@14: } Chris@0: Chris@0: parent::compile(); Chris@0: Chris@14: foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) { Chris@14: if (!$definition->isPublic() || $definition->isPrivate()) { Chris@14: $this->removedIds[$id] = true; Chris@14: } Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets all service ids. Chris@0: * Chris@0: * @return array An array of all defined service ids Chris@0: */ Chris@0: public function getServiceIds() Chris@0: { Chris@0: return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds())); Chris@0: } Chris@0: Chris@0: /** Chris@14: * Gets removed service or alias ids. Chris@14: * Chris@14: * @return array Chris@14: */ Chris@14: public function getRemovedIds() Chris@14: { Chris@14: return $this->removedIds; Chris@14: } Chris@14: Chris@14: /** Chris@0: * Adds the service aliases. Chris@0: */ Chris@0: public function addAliases(array $aliases) Chris@0: { Chris@0: foreach ($aliases as $alias => $id) { Chris@0: $this->setAlias($alias, $id); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the service aliases. Chris@0: */ Chris@0: public function setAliases(array $aliases) Chris@0: { Chris@17: $this->aliasDefinitions = []; Chris@0: $this->addAliases($aliases); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets an alias for an existing service. Chris@0: * Chris@0: * @param string $alias The alias to create Chris@0: * @param string|Alias $id The service to alias Chris@0: * Chris@14: * @return Alias Chris@14: * Chris@0: * @throws InvalidArgumentException if the id is not a string or an Alias Chris@0: * @throws InvalidArgumentException if the alias is for itself Chris@0: */ Chris@0: public function setAlias($alias, $id) Chris@0: { Chris@14: $alias = $this->normalizeId($alias); Chris@0: Chris@18: if ('' === $alias || '\\' === substr($alias, -1) || \strlen($alias) !== strcspn($alias, "\0\r\n'")) { Chris@18: throw new InvalidArgumentException(sprintf('Invalid alias id: "%s"', $alias)); Chris@18: } Chris@18: Chris@17: if (\is_string($id)) { Chris@14: $id = new Alias($this->normalizeId($id)); Chris@0: } elseif (!$id instanceof Alias) { Chris@0: throw new InvalidArgumentException('$id must be a string, or an Alias object.'); Chris@0: } Chris@0: Chris@0: if ($alias === (string) $id) { Chris@0: throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias)); Chris@0: } Chris@0: Chris@14: unset($this->definitions[$alias], $this->removedIds[$alias]); Chris@0: Chris@14: return $this->aliasDefinitions[$alias] = $id; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Removes an alias. Chris@0: * Chris@0: * @param string $alias The alias to remove Chris@0: */ Chris@0: public function removeAlias($alias) Chris@0: { Chris@14: if (isset($this->aliasDefinitions[$alias = $this->normalizeId($alias)])) { Chris@14: unset($this->aliasDefinitions[$alias]); Chris@14: $this->removedIds[$alias] = true; Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if an alias exists under the given identifier. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return bool true if the alias exists, false otherwise Chris@0: */ Chris@0: public function hasAlias($id) Chris@0: { Chris@14: return isset($this->aliasDefinitions[$this->normalizeId($id)]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets all defined aliases. Chris@0: * Chris@0: * @return Alias[] An array of aliases Chris@0: */ Chris@0: public function getAliases() Chris@0: { Chris@0: return $this->aliasDefinitions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets an alias. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return Alias An Alias instance Chris@0: * Chris@0: * @throws InvalidArgumentException if the alias does not exist Chris@0: */ Chris@0: public function getAlias($id) Chris@0: { Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@0: if (!isset($this->aliasDefinitions[$id])) { Chris@0: throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id)); Chris@0: } Chris@0: Chris@0: return $this->aliasDefinitions[$id]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers a service definition. Chris@0: * Chris@0: * This methods allows for simple registration of service definition Chris@0: * with a fluid interface. Chris@0: * Chris@14: * @param string $id The service identifier Chris@14: * @param string $class|null The service class Chris@0: * Chris@0: * @return Definition A Definition instance Chris@0: */ Chris@0: public function register($id, $class = null) Chris@0: { Chris@0: return $this->setDefinition($id, new Definition($class)); Chris@0: } Chris@0: Chris@0: /** Chris@14: * Registers an autowired service definition. Chris@14: * Chris@14: * This method implements a shortcut for using setDefinition() with Chris@14: * an autowired definition. Chris@14: * Chris@14: * @param string $id The service identifier Chris@17: * @param string|null $class The service class Chris@14: * Chris@14: * @return Definition The created definition Chris@14: */ Chris@14: public function autowire($id, $class = null) Chris@14: { Chris@14: return $this->setDefinition($id, (new Definition($class))->setAutowired(true)); Chris@14: } Chris@14: Chris@14: /** Chris@0: * Adds the service definitions. Chris@0: * Chris@0: * @param Definition[] $definitions An array of service definitions Chris@0: */ Chris@0: public function addDefinitions(array $definitions) Chris@0: { Chris@0: foreach ($definitions as $id => $definition) { Chris@0: $this->setDefinition($id, $definition); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the service definitions. Chris@0: * Chris@0: * @param Definition[] $definitions An array of service definitions Chris@0: */ Chris@0: public function setDefinitions(array $definitions) Chris@0: { Chris@17: $this->definitions = []; Chris@0: $this->addDefinitions($definitions); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets all service definitions. Chris@0: * Chris@0: * @return Definition[] An array of Definition instances Chris@0: */ Chris@0: public function getDefinitions() Chris@0: { Chris@0: return $this->definitions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a service definition. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * @param Definition $definition A Definition instance Chris@0: * Chris@0: * @return Definition the service definition Chris@0: * Chris@14: * @throws BadMethodCallException When this ContainerBuilder is compiled Chris@0: */ Chris@0: public function setDefinition($id, Definition $definition) Chris@0: { Chris@14: if ($this->isCompiled()) { Chris@14: throw new BadMethodCallException('Adding definition to a compiled container is not allowed'); Chris@0: } Chris@0: Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@18: if ('' === $id || '\\' === substr($id, -1) || \strlen($id) !== strcspn($id, "\0\r\n'")) { Chris@18: throw new InvalidArgumentException(sprintf('Invalid service id: "%s"', $id)); Chris@18: } Chris@18: Chris@14: unset($this->aliasDefinitions[$id], $this->removedIds[$id]); Chris@0: Chris@0: return $this->definitions[$id] = $definition; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if a service definition exists under the given identifier. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return bool true if the service definition exists, false otherwise Chris@0: */ Chris@0: public function hasDefinition($id) Chris@0: { Chris@14: return isset($this->definitions[$this->normalizeId($id)]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a service definition. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return Definition A Definition instance Chris@0: * Chris@0: * @throws ServiceNotFoundException if the service definition does not exist Chris@0: */ Chris@0: public function getDefinition($id) Chris@0: { Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@0: if (!isset($this->definitions[$id])) { Chris@0: throw new ServiceNotFoundException($id); Chris@0: } Chris@0: Chris@0: return $this->definitions[$id]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a service definition by id or alias. Chris@0: * Chris@0: * The method "unaliases" recursively to return a Definition instance. Chris@0: * Chris@0: * @param string $id The service identifier or alias Chris@0: * Chris@0: * @return Definition A Definition instance Chris@0: * Chris@0: * @throws ServiceNotFoundException if the service definition does not exist Chris@0: */ Chris@0: public function findDefinition($id) Chris@0: { Chris@14: $id = $this->normalizeId($id); Chris@0: Chris@17: $seen = []; Chris@0: while (isset($this->aliasDefinitions[$id])) { Chris@0: $id = (string) $this->aliasDefinitions[$id]; Chris@14: Chris@14: if (isset($seen[$id])) { Chris@14: $seen = array_values($seen); Chris@17: $seen = \array_slice($seen, array_search($id, $seen)); Chris@14: $seen[] = $id; Chris@14: Chris@14: throw new ServiceCircularReferenceException($id, $seen); Chris@14: } Chris@14: Chris@14: $seen[$id] = $id; Chris@0: } Chris@0: Chris@0: return $this->getDefinition($id); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a service for a service definition. Chris@0: * Chris@0: * @param Definition $definition A service definition instance Chris@0: * @param string $id The service identifier Chris@0: * @param bool $tryProxy Whether to try proxying the service with a lazy proxy Chris@0: * Chris@0: * @return object The service described by the service definition Chris@0: * Chris@0: * @throws RuntimeException When the factory definition is incomplete Chris@0: * @throws RuntimeException When the service is a synthetic service Chris@0: * @throws InvalidArgumentException When configure callable is not callable Chris@0: */ Chris@17: private function createService(Definition $definition, array &$inlineServices, $isConstructorArgument = false, $id = null, $tryProxy = true) Chris@0: { Chris@14: if (null === $id && isset($inlineServices[$h = spl_object_hash($definition)])) { Chris@14: return $inlineServices[$h]; Chris@14: } Chris@14: Chris@14: if ($definition instanceof ChildDefinition) { Chris@0: throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id)); Chris@0: } Chris@0: Chris@0: if ($definition->isSynthetic()) { Chris@0: throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id)); Chris@0: } Chris@0: Chris@0: if ($definition->isDeprecated()) { Chris@0: @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED); Chris@0: } Chris@0: Chris@17: if ($tryProxy && $definition->isLazy() && !$tryProxy = !($proxy = $this->proxyInstantiator) || $proxy instanceof RealServiceInstantiator) { Chris@17: $proxy = $proxy->instantiateProxy( Chris@17: $this, Chris@17: $definition, Chris@17: $id, function () use ($definition, &$inlineServices, $id) { Chris@17: return $this->createService($definition, $inlineServices, true, $id, false); Chris@17: } Chris@17: ); Chris@14: $this->shareService($definition, $proxy, $id, $inlineServices); Chris@0: Chris@0: return $proxy; Chris@0: } Chris@0: Chris@0: $parameterBag = $this->getParameterBag(); Chris@0: Chris@0: if (null !== $definition->getFile()) { Chris@0: require_once $parameterBag->resolveValue($definition->getFile()); Chris@0: } Chris@0: Chris@17: $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument); Chris@17: Chris@17: if (null !== $factory = $definition->getFactory()) { Chris@17: if (\is_array($factory)) { Chris@17: $factory = [$this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]]; Chris@17: } elseif (!\is_string($factory)) { Chris@17: throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id)); Chris@17: } Chris@17: } Chris@14: Chris@14: if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) { Chris@14: return $this->services[$id]; Chris@14: } Chris@0: Chris@17: if (null !== $factory) { Chris@17: $service = \call_user_func_array($factory, $arguments); Chris@0: Chris@17: if (!$definition->isDeprecated() && \is_array($factory) && \is_string($factory[0])) { Chris@0: $r = new \ReflectionClass($factory[0]); Chris@0: Chris@0: if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) { Chris@0: @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); Chris@0: } Chris@0: } Chris@0: } else { Chris@14: $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass())); Chris@0: Chris@0: $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments); Chris@14: // don't trigger deprecations for internal uses Chris@14: // @deprecated since version 3.3, to be removed in 4.0 along with the deprecated class Chris@17: $deprecationWhitelist = ['event_dispatcher' => ContainerAwareEventDispatcher::class]; Chris@0: Chris@14: if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ") && (!isset($deprecationWhitelist[$id]) || $deprecationWhitelist[$id] !== $class)) { Chris@0: @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); Chris@0: } Chris@0: } Chris@0: Chris@0: if ($tryProxy || !$definition->isLazy()) { Chris@0: // share only if proxying failed, or if not a proxy Chris@14: $this->shareService($definition, $service, $id, $inlineServices); Chris@0: } Chris@0: Chris@14: $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlineServices); Chris@0: foreach ($properties as $name => $value) { Chris@0: $service->$name = $value; Chris@0: } Chris@0: Chris@0: foreach ($definition->getMethodCalls() as $call) { Chris@14: $this->callMethod($service, $call, $inlineServices); Chris@0: } Chris@0: Chris@0: if ($callable = $definition->getConfigurator()) { Chris@17: if (\is_array($callable)) { Chris@0: $callable[0] = $parameterBag->resolveValue($callable[0]); Chris@0: Chris@0: if ($callable[0] instanceof Reference) { Chris@14: $callable[0] = $this->doGet((string) $callable[0], $callable[0]->getInvalidBehavior(), $inlineServices); Chris@0: } elseif ($callable[0] instanceof Definition) { Chris@14: $callable[0] = $this->createService($callable[0], $inlineServices); Chris@0: } Chris@0: } Chris@0: Chris@17: if (!\is_callable($callable)) { Chris@17: throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', \get_class($service))); Chris@0: } Chris@0: Chris@17: \call_user_func($callable, $service); Chris@0: } Chris@0: Chris@0: return $service; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Replaces service references by the real service instance and evaluates expressions. Chris@0: * Chris@0: * @param mixed $value A value Chris@0: * Chris@0: * @return mixed The same value with all service references replaced by Chris@0: * the real service instances and all expressions evaluated Chris@0: */ Chris@0: public function resolveServices($value) Chris@0: { Chris@14: return $this->doResolveServices($value); Chris@14: } Chris@14: Chris@17: private function doResolveServices($value, array &$inlineServices = [], $isConstructorArgument = false) Chris@14: { Chris@17: if (\is_array($value)) { Chris@0: foreach ($value as $k => $v) { Chris@17: $value[$k] = $this->doResolveServices($v, $inlineServices, $isConstructorArgument); Chris@0: } Chris@14: } elseif ($value instanceof ServiceClosureArgument) { Chris@14: $reference = $value->getValues()[0]; Chris@14: $value = function () use ($reference) { Chris@14: return $this->resolveServices($reference); Chris@14: }; Chris@14: } elseif ($value instanceof IteratorArgument) { Chris@14: $value = new RewindableGenerator(function () use ($value) { Chris@14: foreach ($value->getValues() as $k => $v) { Chris@14: foreach (self::getServiceConditionals($v) as $s) { Chris@14: if (!$this->has($s)) { Chris@14: continue 2; Chris@14: } Chris@14: } Chris@14: foreach (self::getInitializedConditionals($v) as $s) { Chris@14: if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) { Chris@14: continue 2; Chris@14: } Chris@14: } Chris@14: Chris@14: yield $k => $this->resolveServices($v); Chris@14: } Chris@14: }, function () use ($value) { Chris@14: $count = 0; Chris@14: foreach ($value->getValues() as $v) { Chris@14: foreach (self::getServiceConditionals($v) as $s) { Chris@14: if (!$this->has($s)) { Chris@14: continue 2; Chris@14: } Chris@14: } Chris@14: foreach (self::getInitializedConditionals($v) as $s) { Chris@14: if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) { Chris@14: continue 2; Chris@14: } Chris@14: } Chris@14: Chris@14: ++$count; Chris@14: } Chris@14: Chris@14: return $count; Chris@14: }); Chris@0: } elseif ($value instanceof Reference) { Chris@17: $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument); Chris@0: } elseif ($value instanceof Definition) { Chris@17: $value = $this->createService($value, $inlineServices, $isConstructorArgument); Chris@14: } elseif ($value instanceof Parameter) { Chris@14: $value = $this->getParameter((string) $value); Chris@0: } elseif ($value instanceof Expression) { Chris@17: $value = $this->getExpressionLanguage()->evaluate($value, ['container' => $this]); Chris@0: } Chris@0: Chris@0: return $value; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns service ids for a given tag. Chris@0: * Chris@0: * Example: Chris@0: * Chris@17: * $container->register('foo')->addTag('my.tag', ['hello' => 'world']); Chris@0: * Chris@17: * $serviceIds = $container->findTaggedServiceIds('my.tag'); Chris@17: * foreach ($serviceIds as $serviceId => $tags) { Chris@17: * foreach ($tags as $tag) { Chris@17: * echo $tag['hello']; Chris@17: * } Chris@0: * } Chris@0: * Chris@14: * @param string $name Chris@14: * @param bool $throwOnAbstract Chris@0: * Chris@0: * @return array An array of tags with the tagged service as key, holding a list of attribute arrays Chris@0: */ Chris@14: public function findTaggedServiceIds($name, $throwOnAbstract = false) Chris@0: { Chris@0: $this->usedTags[] = $name; Chris@17: $tags = []; Chris@0: foreach ($this->getDefinitions() as $id => $definition) { Chris@0: if ($definition->hasTag($name)) { Chris@14: if ($throwOnAbstract && $definition->isAbstract()) { Chris@14: throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must not be abstract.', $id, $name)); Chris@14: } Chris@0: $tags[$id] = $definition->getTag($name); Chris@0: } Chris@0: } Chris@0: Chris@0: return $tags; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all tags the defined services use. Chris@0: * Chris@0: * @return array An array of tags Chris@0: */ Chris@0: public function findTags() Chris@0: { Chris@17: $tags = []; Chris@0: foreach ($this->getDefinitions() as $id => $definition) { Chris@0: $tags = array_merge(array_keys($definition->getTags()), $tags); Chris@0: } Chris@0: Chris@0: return array_unique($tags); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all tags not queried by findTaggedServiceIds. Chris@0: * Chris@0: * @return string[] An array of tags Chris@0: */ Chris@0: public function findUnusedTags() Chris@0: { Chris@0: return array_values(array_diff($this->findTags(), $this->usedTags)); Chris@0: } Chris@0: Chris@0: public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) Chris@0: { Chris@0: $this->expressionLanguageProviders[] = $provider; Chris@0: } Chris@0: Chris@0: /** Chris@0: * @return ExpressionFunctionProviderInterface[] Chris@0: */ Chris@0: public function getExpressionLanguageProviders() Chris@0: { Chris@0: return $this->expressionLanguageProviders; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Returns a ChildDefinition that will be used for autoconfiguring the interface/class. Chris@14: * Chris@14: * @param string $interface The class or interface to match Chris@14: * Chris@14: * @return ChildDefinition Chris@14: */ Chris@14: public function registerForAutoconfiguration($interface) Chris@14: { Chris@14: if (!isset($this->autoconfiguredInstanceof[$interface])) { Chris@14: $this->autoconfiguredInstanceof[$interface] = new ChildDefinition(''); Chris@14: } Chris@14: Chris@14: return $this->autoconfiguredInstanceof[$interface]; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Returns an array of ChildDefinition[] keyed by interface. Chris@14: * Chris@14: * @return ChildDefinition[] Chris@14: */ Chris@14: public function getAutoconfiguredInstanceof() Chris@14: { Chris@14: return $this->autoconfiguredInstanceof; Chris@14: } Chris@14: Chris@14: /** Chris@0: * Resolves env parameter placeholders in a string or an array. Chris@0: * Chris@14: * @param mixed $value The value to resolve Chris@14: * @param string|true|null $format A sprintf() format returning the replacement for each env var name or Chris@14: * null to resolve back to the original "%env(VAR)%" format or Chris@14: * true to resolve to the actual values of the referenced env vars Chris@14: * @param array &$usedEnvs Env vars found while resolving are added to this array Chris@0: * Chris@14: * @return mixed The value with env parameters resolved if a string or an array is passed Chris@0: */ Chris@0: public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null) Chris@0: { Chris@0: if (null === $format) { Chris@0: $format = '%%env(%s)%%'; Chris@0: } Chris@0: Chris@14: $bag = $this->getParameterBag(); Chris@14: if (true === $format) { Chris@14: $value = $bag->resolveValue($value); Chris@14: } Chris@14: Chris@14: if (\is_array($value)) { Chris@17: $result = []; Chris@0: foreach ($value as $k => $v) { Chris@14: $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs); Chris@0: } Chris@0: Chris@0: return $result; Chris@0: } Chris@0: Chris@14: if (!\is_string($value) || 38 > \strlen($value)) { Chris@0: return $value; Chris@0: } Chris@0: $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders; Chris@0: Chris@16: $completed = false; Chris@0: foreach ($envPlaceholders as $env => $placeholders) { Chris@0: foreach ($placeholders as $placeholder) { Chris@0: if (false !== stripos($value, $placeholder)) { Chris@14: if (true === $format) { Chris@14: $resolved = $bag->escapeValue($this->getEnv($env)); Chris@14: } else { Chris@14: $resolved = sprintf($format, $env); Chris@14: } Chris@14: if ($placeholder === $value) { Chris@14: $value = $resolved; Chris@16: $completed = true; Chris@14: } else { Chris@17: if (!\is_string($resolved) && !is_numeric($resolved)) { Chris@17: 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))); Chris@14: } Chris@14: $value = str_ireplace($placeholder, $resolved, $value); Chris@14: } Chris@0: $usedEnvs[$env] = $env; Chris@0: $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1; Chris@16: Chris@16: if ($completed) { Chris@16: break 2; Chris@16: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $value; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get statistics about env usage. Chris@0: * Chris@0: * @return int[] The number of time each env vars has been resolved Chris@0: */ Chris@0: public function getEnvCounters() Chris@0: { Chris@0: $bag = $this->getParameterBag(); Chris@0: $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders; Chris@0: Chris@0: foreach ($envPlaceholders as $env => $placeholders) { Chris@0: if (!isset($this->envCounters[$env])) { Chris@0: $this->envCounters[$env] = 0; Chris@0: } Chris@0: } Chris@0: Chris@0: return $this->envCounters; Chris@0: } Chris@0: Chris@0: /** Chris@14: * @internal Chris@14: */ Chris@14: public function getNormalizedIds() Chris@14: { Chris@17: $normalizedIds = []; Chris@14: Chris@14: foreach ($this->normalizedIds as $k => $v) { Chris@14: if ($v !== (string) $k) { Chris@14: $normalizedIds[$k] = $v; Chris@14: } Chris@14: } Chris@14: Chris@14: return $normalizedIds; Chris@14: } Chris@14: Chris@14: /** Chris@14: * @final Chris@14: */ Chris@14: public function log(CompilerPassInterface $pass, $message) Chris@14: { Chris@16: $this->getCompiler()->log($pass, $this->resolveEnvPlaceholders($message)); Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: public function normalizeId($id) Chris@14: { Chris@14: if (!\is_string($id)) { Chris@14: $id = (string) $id; Chris@14: } Chris@14: Chris@14: return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || isset($this->removedIds[$id]) ? $id : parent::normalizeId($id); Chris@14: } Chris@14: Chris@14: /** Chris@18: * Gets removed binding ids. Chris@18: * Chris@18: * @return array Chris@18: * Chris@18: * @internal Chris@18: */ Chris@18: public function getRemovedBindingIds() Chris@18: { Chris@18: return $this->removedBindingIds; Chris@18: } Chris@18: Chris@18: /** Chris@18: * Removes bindings for a service. Chris@18: * Chris@18: * @param string $id The service identifier Chris@18: * Chris@18: * @internal Chris@18: */ Chris@18: public function removeBindings($id) Chris@18: { Chris@18: if ($this->hasDefinition($id)) { Chris@18: foreach ($this->getDefinition($id)->getBindings() as $key => $binding) { Chris@18: list(, $bindingId) = $binding->getValues(); Chris@18: $this->removedBindingIds[(int) $bindingId] = true; Chris@18: } Chris@18: } Chris@18: } Chris@18: Chris@18: /** Chris@0: * Returns the Service Conditionals. Chris@0: * Chris@0: * @param mixed $value An array of conditionals to return Chris@0: * Chris@0: * @return array An array of Service conditionals Chris@14: * Chris@14: * @internal since version 3.4 Chris@0: */ Chris@0: public static function getServiceConditionals($value) Chris@0: { Chris@17: $services = []; Chris@0: Chris@17: if (\is_array($value)) { Chris@0: foreach ($value as $v) { Chris@0: $services = array_unique(array_merge($services, self::getServiceConditionals($v))); Chris@0: } Chris@14: } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) { Chris@0: $services[] = (string) $value; Chris@0: } Chris@0: Chris@0: return $services; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Returns the initialized conditionals. Chris@14: * Chris@14: * @param mixed $value An array of conditionals to return Chris@14: * Chris@14: * @return array An array of uninitialized conditionals Chris@14: * Chris@14: * @internal Chris@14: */ Chris@14: public static function getInitializedConditionals($value) Chris@14: { Chris@17: $services = []; Chris@14: Chris@17: if (\is_array($value)) { Chris@14: foreach ($value as $v) { Chris@14: $services = array_unique(array_merge($services, self::getInitializedConditionals($v))); Chris@14: } Chris@14: } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior()) { Chris@14: $services[] = (string) $value; Chris@14: } Chris@14: Chris@14: return $services; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Computes a reasonably unique hash of a value. Chris@14: * Chris@14: * @param mixed $value A serializable value Chris@14: * Chris@14: * @return string Chris@14: */ Chris@14: public static function hash($value) Chris@14: { Chris@14: $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7); Chris@14: Chris@17: return str_replace(['/', '+'], ['.', '_'], strtolower($hash)); Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@14: protected function getEnv($name) Chris@14: { Chris@14: $value = parent::getEnv($name); Chris@14: $bag = $this->getParameterBag(); Chris@14: Chris@17: if (!\is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) { Chris@14: return $value; Chris@14: } Chris@14: Chris@14: foreach ($bag->getEnvPlaceholders() as $env => $placeholders) { Chris@14: if (isset($placeholders[$value])) { Chris@14: $bag = new ParameterBag($bag->all()); Chris@14: Chris@14: return $bag->unescapeValue($bag->get("env($name)")); Chris@14: } Chris@14: } Chris@14: Chris@14: $this->resolving["env($name)"] = true; Chris@14: try { Chris@14: return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true)); Chris@14: } finally { Chris@14: unset($this->resolving["env($name)"]); Chris@14: } Chris@14: } Chris@14: Chris@14: private function callMethod($service, $call, array &$inlineServices) Chris@0: { Chris@14: foreach (self::getServiceConditionals($call[1]) as $s) { Chris@0: if (!$this->has($s)) { Chris@0: return; Chris@0: } Chris@0: } Chris@14: foreach (self::getInitializedConditionals($call[1]) as $s) { Chris@14: if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE, $inlineServices)) { Chris@14: return; Chris@14: } Chris@14: } Chris@0: Chris@17: \call_user_func_array([$service, $call[0]], $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Shares a given service in the container. Chris@0: * Chris@0: * @param Definition $definition Chris@14: * @param object $service Chris@0: * @param string|null $id Chris@0: */ Chris@14: private function shareService(Definition $definition, $service, $id, array &$inlineServices) Chris@0: { Chris@14: $inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service; Chris@14: Chris@0: if (null !== $id && $definition->isShared()) { Chris@14: $this->services[$id] = $service; Chris@17: unset($this->loading[$id]); Chris@0: } Chris@0: } Chris@0: Chris@0: private function getExpressionLanguage() Chris@0: { Chris@0: if (null === $this->expressionLanguage) { Chris@0: if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { Chris@0: throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); Chris@0: } Chris@0: $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders); Chris@0: } Chris@0: Chris@0: return $this->expressionLanguage; Chris@0: } Chris@14: Chris@14: private function inVendors($path) Chris@14: { Chris@14: if (null === $this->vendors) { Chris@14: $resource = new ComposerResource(); Chris@14: $this->vendors = $resource->getVendors(); Chris@14: $this->addResource($resource); Chris@14: } Chris@14: $path = realpath($path) ?: $path; Chris@14: Chris@14: foreach ($this->vendors as $vendor) { Chris@17: if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) { Chris@14: return true; Chris@14: } Chris@14: } Chris@14: Chris@14: return false; Chris@14: } Chris@0: }