This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/DependencyInjection/ContainerBuilder.php

1494 lines
49 KiB
PHP
Raw Normal View History

2010-01-04 14:26:20 +00:00
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection;
2010-01-04 14:26:20 +00:00
use Symfony\Component\DependencyInjection\Argument\ClosureProxyArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Compiler\Compiler;
2010-12-14 23:25:33 +00:00
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\Config\Resource\ComposerResource;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Config\Resource\FileExistenceResource;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\ReflectionClassResource;
use Symfony\Component\Config\Resource\ResourceInterface;
2013-03-29 23:21:12 +00:00
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
2017-02-07 18:39:15 +00:00
use Symfony\Component\DependencyInjection\LazyProxy\InheritanceProxyHelper;
use Symfony\Component\DependencyInjection\LazyProxy\InheritanceProxyInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
2010-01-04 14:26:20 +00:00
/**
* ContainerBuilder is a DI container that provides an API to easily describe services.
2010-01-04 14:26:20 +00:00
*
* @author Fabien Potencier <fabien@symfony.com>
2010-01-04 14:26:20 +00:00
*/
2010-08-05 06:34:53 +01:00
class ContainerBuilder extends Container implements TaggedContainerInterface
2010-01-04 14:26:20 +00:00
{
/**
* @var ExtensionInterface[]
*/
private $extensions = array();
/**
* @var ExtensionInterface[]
*/
private $extensionsByNs = array();
/**
* @var Definition[]
*/
private $definitions = array();
/**
* @var Alias[]
*/
private $aliasDefinitions = array();
/**
* @var ResourceInterface[]
*/
private $resources = array();
private $extensionConfigs = array();
/**
* @var Compiler
*/
private $compiler;
2010-12-14 23:25:33 +00:00
private $trackResources = true;
2013-03-29 23:21:12 +00:00
/**
* @var InstantiatorInterface|null
*/
private $proxyInstantiator;
/**
* @var ExpressionLanguage|null
*/
private $expressionLanguage;
/**
* @var ExpressionFunctionProviderInterface[]
*/
private $expressionLanguageProviders = array();
/**
2015-09-28 12:00:47 +01:00
* @var string[] with tag names used by findTaggedServiceIds
*/
private $usedTags = array();
/**
* @var string[][] a map of env var names to their placeholders
*/
private $envPlaceholders = array();
/**
* @var int[] a map of env vars to their resolution counter
*/
private $envCounters = array();
/**
* @var string[] the list of vendor directories
*/
private $vendors;
/**
* Sets the track resources flag.
*
* If you are not using the loaders and therefore don't want
* to depend on the Config component, set this flag to false.
*
2014-11-30 13:33:44 +00:00
* @param bool $track true if you want to track resources, false otherwise
*/
public function setResourceTracking($track)
{
$this->trackResources = (bool) $track;
}
/**
* Checks if resources are tracked.
*
2014-11-30 13:33:44 +00:00
* @return bool true if resources are tracked, false otherwise
*/
public function isTrackingResources()
{
return $this->trackResources;
}
2013-03-29 23:21:12 +00:00
/**
* Sets the instantiator to be used when fetching proxies.
*
* @param InstantiatorInterface $proxyInstantiator
*/
public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)
{
$this->proxyInstantiator = $proxyInstantiator;
}
/**
* Registers an extension.
*
* @param ExtensionInterface $extension An extension instance
*/
public function registerExtension(ExtensionInterface $extension)
{
$this->extensions[$extension->getAlias()] = $extension;
if (false !== $extension->getNamespace()) {
$this->extensionsByNs[$extension->getNamespace()] = $extension;
}
}
/**
* Returns an extension by alias or namespace.
*
* @param string $name An alias or a namespace
*
* @return ExtensionInterface An extension instance
*
* @throws LogicException if the extension is not registered
*/
public function getExtension($name)
{
if (isset($this->extensions[$name])) {
return $this->extensions[$name];
}
if (isset($this->extensionsByNs[$name])) {
return $this->extensionsByNs[$name];
}
throw new LogicException(sprintf('Container extension "%s" is not registered', $name));
}
/**
* Returns all registered extensions.
*
* @return ExtensionInterface[] An array of ExtensionInterface
*/
public function getExtensions()
{
return $this->extensions;
}
2011-02-13 18:06:41 +00:00
/**
* Checks if we have an extension.
*
* @param string $name The name of the extension
2011-12-13 07:50:54 +00:00
*
2014-11-30 13:33:44 +00:00
* @return bool If the extension exists
2011-02-13 18:06:41 +00:00
*/
public function hasExtension($name)
{
return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
}
/**
* Returns an array of resources loaded to build this configuration.
*
* @return ResourceInterface[] An array of resources
*/
public function getResources()
{
return array_values($this->resources);
}
/**
* Adds a resource for this configuration.
*
* @param ResourceInterface $resource A resource instance
*
* @return $this
*/
public function addResource(ResourceInterface $resource)
{
if (!$this->trackResources) {
return $this;
}
$this->resources[(string) $resource] = $resource;
return $this;
}
/**
* Sets the resources for this configuration.
2012-12-11 10:49:22 +00:00
*
* @param ResourceInterface[] $resources An array of resources
2012-12-11 10:49:22 +00:00
*
* @return $this
*/
2011-09-16 12:43:09 +01:00
public function setResources(array $resources)
{
if (!$this->trackResources) {
return $this;
}
2011-09-16 12:43:09 +01:00
$this->resources = $resources;
return $this;
}
/**
* Adds the object class hierarchy as resources.
*
* @param object|string $object An object instance or class name
*
* @return $this
*/
public function addObjectResource($object)
2013-03-29 23:21:12 +00:00
{
if ($this->trackResources) {
if (is_object($object)) {
$object = get_class($object);
}
if (!isset($this->classReflectors[$object])) {
$this->classReflectors[$object] = new \ReflectionClass($object);
}
$class = $this->classReflectors[$object];
foreach ($class->getInterfaceNames() as $name) {
if (null === $interface = &$this->classReflectors[$name]) {
$interface = new \ReflectionClass($name);
}
$file = $interface->getFileName();
if (false !== $file && file_exists($file)) {
$this->fileExists($file);
}
}
do {
$file = $class->getFileName();
if (false !== $file && file_exists($file)) {
$this->fileExists($file);
}
foreach ($class->getTraitNames() as $name) {
$this->addObjectResource($name);
}
} while ($class = $class->getParentClass());
2013-03-29 23:21:12 +00:00
}
return $this;
}
/**
* Adds the given class hierarchy as resources.
*
* @param \ReflectionClass $class
*
* @return $this
*
* @deprecated since version 3.3, to be removed in 4.0. Use addObjectResource() or getReflectionClass() instead.
2013-03-29 23:21:12 +00:00
*/
public function addClassResource(\ReflectionClass $class)
{
@trigger_error('The '.__METHOD__.'() method is deprecated since version 3.3 and will be removed in 4.0. Use the addObjectResource() or the getReflectionClass() method instead.', E_USER_DEPRECATED);
return $this->addObjectResource($class->name);
}
/**
* Retrieves the requested reflection class and registers it for resource tracking.
*
* @param string $class
* @param bool $koWithThrowingAutoloader Whether autoload should be protected against bad parents or not
*
* @return \ReflectionClass|null
*
* @final
*/
public function getReflectionClass($class, $koWithThrowingAutoloader = false)
{
if (!$class = $this->getParameterBag()->resolveValue($class)) {
return;
}
$resource = null;
try {
if (isset($this->classReflectors[$class])) {
$classReflector = $this->classReflectors[$class];
} elseif ($koWithThrowingAutoloader) {
$resource = new ClassExistenceResource($class, ClassExistenceResource::EXISTS_KO_WITH_THROWING_AUTOLOADER);
$classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class);
} else {
$classReflector = new \ReflectionClass($class);
}
} catch (\ReflectionException $e) {
$classReflector = false;
}
if ($this->trackResources) {
if (!$classReflector) {
$this->addResource($resource ?: new ClassExistenceResource($class, ClassExistenceResource::EXISTS_KO));
} elseif (!$classReflector->isInternal()) {
$path = $classReflector->getFileName();
if (!$this->inVendors($path)) {
$this->addResource(new ReflectionClassResource($classReflector, $this->vendors));
}
}
$this->classReflectors[$class] = $classReflector;
}
return $classReflector ?: null;
}
/**
* Checks whether the requested file or directory exists and registers the result for resource tracking.
*
* @param string $path The file or directory path for which to check the existence
* @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed,
* it will be used as pattern for tracking contents of the requested directory
*
* @return bool
*
* @final
*/
public function fileExists($path, $trackContents = true)
{
$exists = file_exists($path);
if (!$this->trackResources || $this->inVendors($path)) {
return $exists;
}
if (!$exists) {
$this->addResource(new FileExistenceResource($path));
return $exists;
}
if ($trackContents && is_dir($path)) {
$this->addResource(new DirectoryResource($path, is_string($trackContents) ? $trackContents : null));
} elseif ($trackContents || is_dir($path)) {
$this->addResource(new FileResource($path));
}
return $exists;
}
/**
* Loads the configuration for an extension.
*
2010-07-20 15:40:57 +01:00
* @param string $extension The extension alias or namespace
* @param array $values An array of values that customizes the extension
*
* @return $this
*
2014-12-21 17:00:50 +00:00
* @throws BadMethodCallException When this ContainerBuilder is frozen
* @throws \LogicException if the container is frozen
*/
public function loadFromExtension($extension, array $values = array())
{
if ($this->isFrozen()) {
throw new BadMethodCallException('Cannot load from an extension on a frozen container.');
}
$namespace = $this->getExtension($extension)->getAlias();
$this->extensionConfigs[$namespace][] = $values;
return $this;
}
2010-12-14 23:25:33 +00:00
/**
* Adds a compiler pass.
2010-12-14 23:25:33 +00:00
*
* @param CompilerPassInterface $pass A compiler pass
* @param string $type The type of compiler pass
* @param int $priority Used to sort the passes
*
* @return $this
2010-12-14 23:25:33 +00:00
*/
public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, $priority = 0*/)
2010-12-14 23:25:33 +00:00
{
if (func_num_args() >= 3) {
$priority = func_get_arg(2);
} else {
if (__CLASS__ !== get_class($this)) {
$r = new \ReflectionMethod($this, __FUNCTION__);
if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
@trigger_error(sprintf('Method %s() will have a third `$priority = 0` argument in version 4.0. Not defining it is deprecated since 3.2.', get_class($this), __FUNCTION__), E_USER_DEPRECATED);
}
}
$priority = 0;
}
$this->getCompiler()->addPass($pass, $type, $priority);
$this->addObjectResource($pass);
return $this;
2010-12-14 23:25:33 +00:00
}
/**
* Returns the compiler pass config which can then be modified.
2010-12-14 23:25:33 +00:00
*
* @return PassConfig The compiler pass config
2010-12-14 23:25:33 +00:00
*/
2010-12-29 19:12:24 +00:00
public function getCompilerPassConfig()
2010-12-14 23:25:33 +00:00
{
return $this->getCompiler()->getPassConfig();
}
/**
* Returns the compiler.
*
* @return Compiler The compiler
*/
public function getCompiler()
{
if (null === $this->compiler) {
$this->compiler = new Compiler();
}
return $this->compiler;
2010-12-14 23:25:33 +00:00
}
/**
* Sets a service.
*
* @param string $id The service identifier
* @param object $service The service instance
*
* @throws BadMethodCallException When this ContainerBuilder is frozen
*/
2015-09-04 20:54:37 +01:00
public function set($id, $service)
2010-01-04 14:26:20 +00:00
{
$id = $this->normalizeId($id);
if ($this->isFrozen() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) {
// setting a synthetic service on a frozen container is alright
throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a frozen container is not allowed.', $id));
}
unset($this->definitions[$id], $this->aliasDefinitions[$id]);
2015-09-04 20:54:37 +01:00
parent::set($id, $service);
2010-01-04 14:26:20 +00:00
}
/**
* Removes a service definition.
*
* @param string $id The service identifier
*/
public function removeDefinition($id)
{
unset($this->definitions[$this->normalizeId($id)]);
}
/**
* Returns true if the given service is defined.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
*
2014-11-30 13:33:44 +00:00
* @return bool true if the service is defined, false otherwise
*/
2010-06-27 17:28:29 +01:00
public function has($id)
{
$id = $this->normalizeId($id);
return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id);
}
/**
* Gets a service.
*
2014-11-30 13:33:44 +00:00
* @param string $id The service identifier
* @param int $invalidBehavior The behavior when the service does not exist
*
* @return object The associated service
*
* @throws InvalidArgumentException when no definitions are available
* @throws ServiceCircularReferenceException When a circular reference is detected
* @throws ServiceNotFoundException When the service is not defined
2013-03-29 23:21:12 +00:00
* @throws \Exception
*
* @see Reference
*/
2010-06-27 17:28:29 +01:00
public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
2010-01-04 14:26:20 +00:00
{
$id = $this->normalizeId($id);
if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
2014-03-27 18:14:17 +00:00
return $service;
}
2014-03-27 18:14:17 +00:00
2016-08-21 13:01:27 +01:00
if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) {
return $this->get((string) $this->aliasDefinitions[$id], $invalidBehavior);
}
try {
$definition = $this->getDefinition($id);
} catch (ServiceNotFoundException $e) {
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
2014-04-16 08:15:58 +01:00
return;
}
throw $e;
}
$this->loading[$id] = true;
try {
$service = $this->createService($definition, $id);
2015-09-28 01:26:11 +01:00
} finally {
unset($this->loading[$id]);
}
2010-01-04 14:26:20 +00:00
return $service;
2010-01-04 14:26:20 +00:00
}
/**
* Merges a ContainerBuilder with the current ContainerBuilder configuration.
*
* Service definitions overrides the current defined ones.
*
* But for parameters, they are overridden by the current ones. It allows
* the parameters passed to the container constructor to have precedence
* over the loaded ones.
*
* $container = new ContainerBuilder(array('foo' => 'bar'));
* $loader = new LoaderXXX($container);
* $loader->load('resource_name');
* $container->register('foo', new stdClass());
*
* In the above example, even if the loaded resource defines a foo
* parameter, the value will still be 'bar' as defined in the ContainerBuilder
* constructor.
2011-02-13 18:06:41 +00:00
*
* @param ContainerBuilder $container The ContainerBuilder instance to merge
*
* @throws BadMethodCallException When this ContainerBuilder is frozen
*/
public function merge(ContainerBuilder $container)
2010-01-04 14:26:20 +00:00
{
if ($this->isFrozen()) {
throw new BadMethodCallException('Cannot merge on a frozen container.');
}
$this->addDefinitions($container->getDefinitions());
$this->addAliases($container->getAliases());
$this->getParameterBag()->add($container->getParameterBag()->all());
if ($this->trackResources) {
foreach ($container->getResources() as $resource) {
$this->addResource($resource);
}
}
foreach ($this->extensions as $name => $extension) {
if (!isset($this->extensionConfigs[$name])) {
$this->extensionConfigs[$name] = array();
}
$this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
}
if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) {
$this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag());
}
foreach ($container->envCounters as $env => $count) {
if (!isset($this->envCounters[$env])) {
$this->envCounters[$env] = $count;
} else {
$this->envCounters[$env] += $count;
}
}
}
/**
* Returns the configuration array for the given extension.
*
* @param string $name The name of the extension
*
* @return array An array of configuration
*/
public function getExtensionConfig($name)
{
if (!isset($this->extensionConfigs[$name])) {
$this->extensionConfigs[$name] = array();
}
return $this->extensionConfigs[$name];
}
/**
* Prepends a config array to the configs of the given extension.
*
2014-11-30 13:33:44 +00:00
* @param string $name The name of the extension
* @param array $config The config to set
*/
public function prependExtensionConfig($name, array $config)
{
if (!isset($this->extensionConfigs[$name])) {
$this->extensionConfigs[$name] = array();
}
array_unshift($this->extensionConfigs[$name], $config);
}
/**
* Compiles the container.
*
* This method passes the container to compiler
* passes whose job is to manipulate and optimize
* the container.
*
* The main compiler passes roughly do four things:
*
* * The extension configurations are merged;
* * Parameter values are resolved;
* * The parameter bag is frozen;
* * Extension loading is disabled.
*
* @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current
* env vars or be replaced by uniquely identifiable placeholders.
* Set to "true" when you want to use the current ContainerBuilder
* directly, keep to "false" when the container is dumped instead.
*/
public function compile(/*$resolveEnvPlaceholders = false*/)
{
if (1 <= func_num_args()) {
$resolveEnvPlaceholders = func_get_arg(0);
} else {
if (__CLASS__ !== static::class) {
$r = new \ReflectionMethod($this, __FUNCTION__);
if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) {
@trigger_error(sprintf('The %s::compile() method expects a first "$resolveEnvPlaceholders" argument since version 3.3. It will be made mandatory in 4.0.', static::class), E_USER_DEPRECATED);
}
}
$resolveEnvPlaceholders = false;
}
$compiler = $this->getCompiler();
if ($this->trackResources) {
foreach ($compiler->getPassConfig()->getPasses() as $pass) {
$this->addObjectResource($pass);
}
2013-11-09 11:47:52 +00:00
}
$bag = $this->getParameterBag();
if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) {
$this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true));
$this->envPlaceholders = $bag->getEnvPlaceholders();
$this->parameterBag = $bag = new ParameterBag($this->resolveEnvPlaceholders($this->parameterBag->all()));
}
2013-11-09 11:47:52 +00:00
$compiler->compile($this);
2013-03-29 23:21:12 +00:00
foreach ($this->definitions as $id => $definition) {
if (!$definition->isPublic()) {
$this->privates[$id] = true;
}
if ($this->trackResources && $definition->isLazy()) {
$this->getReflectionClass($definition->getClass());
2013-03-29 23:21:12 +00:00
}
}
$this->extensionConfigs = array();
parent::compile();
$this->envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : array();
2010-01-04 14:26:20 +00:00
}
/**
* Gets all service ids.
*
* @return array An array of all defined service ids
*/
public function getServiceIds()
2010-01-04 14:26:20 +00:00
{
return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()));
2010-01-04 14:26:20 +00:00
}
/**
* Adds the service aliases.
*
* @param array $aliases An array of aliases
*/
public function addAliases(array $aliases)
{
foreach ($aliases as $alias => $id) {
$this->setAlias($alias, $id);
}
}
/**
* Sets the service aliases.
*
* @param array $aliases An array of aliases
*/
public function setAliases(array $aliases)
{
$this->aliasDefinitions = array();
$this->addAliases($aliases);
}
/**
* Sets an alias for an existing service.
*
2014-11-30 13:33:44 +00:00
* @param string $alias The alias to create
* @param string|Alias $id The service to alias
*
* @throws InvalidArgumentException if the id is not a string or an Alias
* @throws InvalidArgumentException if the alias is for itself
*/
public function setAlias($alias, $id)
2010-01-04 14:26:20 +00:00
{
$alias = $this->normalizeId($alias);
2011-01-07 14:44:29 +00:00
if (is_string($id)) {
$id = new Alias($this->normalizeId($id));
2011-12-18 13:42:59 +00:00
} elseif (!$id instanceof Alias) {
throw new InvalidArgumentException('$id must be a string, or an Alias object.');
2011-01-07 14:44:29 +00:00
}
if ($alias === (string) $id) {
2013-04-10 11:24:37 +01:00
throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
}
unset($this->definitions[$alias]);
$this->aliasDefinitions[$alias] = $id;
2010-01-04 14:26:20 +00:00
}
/**
* Removes an alias.
*
* @param string $alias The alias to remove
*/
public function removeAlias($alias)
{
unset($this->aliasDefinitions[$this->normalizeId($alias)]);
}
/**
* Returns true if an alias exists under the given identifier.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
*
2014-11-30 13:33:44 +00:00
* @return bool true if the alias exists, false otherwise
*/
public function hasAlias($id)
2010-01-04 14:26:20 +00:00
{
return isset($this->aliasDefinitions[$this->normalizeId($id)]);
2010-01-04 14:26:20 +00:00
}
/**
* Gets all defined aliases.
*
* @return Alias[] An array of aliases
*/
public function getAliases()
2010-01-04 14:26:20 +00:00
{
return $this->aliasDefinitions;
2010-01-04 14:26:20 +00:00
}
/**
* Gets an alias.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
*
2012-08-03 10:22:09 +01:00
* @return Alias An Alias instance
*
* @throws InvalidArgumentException if the alias does not exist
*/
public function getAlias($id)
{
$id = $this->normalizeId($id);
if (!isset($this->aliasDefinitions[$id])) {
throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
}
2010-01-04 14:26:20 +00:00
return $this->aliasDefinitions[$id];
}
2010-01-04 14:26:20 +00:00
/**
* Registers a service definition.
*
* This methods allows for simple registration of service definition
* with a fluid interface.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
* @param string $class The service class
*
* @return Definition A Definition instance
*/
public function register($id, $class = null)
2010-01-04 14:26:20 +00:00
{
2015-04-04 18:31:25 +01:00
return $this->setDefinition($id, new Definition($class));
2010-01-04 14:26:20 +00:00
}
/**
* Registers an autowired service definition.
*
* This method implements a shortcut for using setDefinition() with
* an autowired definition.
*
* @param string $id The service identifier
* @param null|string $class The service class
*
* @return Definition The created definition
*/
public function autowire($id, $class = null)
{
return $this->setDefinition($id, (new Definition($class))->setAutowired(true));
}
/**
* Adds the service definitions.
*
* @param Definition[] $definitions An array of service definitions
*/
public function addDefinitions(array $definitions)
2010-01-04 14:26:20 +00:00
{
foreach ($definitions as $id => $definition) {
$this->setDefinition($id, $definition);
}
2010-01-04 14:26:20 +00:00
}
/**
* Sets the service definitions.
*
* @param Definition[] $definitions An array of service definitions
*/
public function setDefinitions(array $definitions)
{
$this->definitions = array();
$this->addDefinitions($definitions);
}
/**
* Gets all service definitions.
*
* @return Definition[] An array of Definition instances
*/
public function getDefinitions()
2010-01-04 14:26:20 +00:00
{
return $this->definitions;
}
2010-01-04 14:26:20 +00:00
/**
* Sets a service definition.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
* @param Definition $definition A Definition instance
*
* @return Definition the service definition
*
* @throws BadMethodCallException When this ContainerBuilder is frozen
*/
public function setDefinition($id, Definition $definition)
{
if ($this->isFrozen()) {
throw new BadMethodCallException('Adding definition to a frozen container is not allowed');
}
$id = $this->normalizeId($id);
unset($this->aliasDefinitions[$id]);
2010-01-04 14:26:20 +00:00
return $this->definitions[$id] = $definition;
2010-01-04 14:26:20 +00:00
}
/**
* Returns true if a service definition exists under the given identifier.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
*
2014-11-30 13:33:44 +00:00
* @return bool true if the service definition exists, false otherwise
*/
public function hasDefinition($id)
2010-01-04 14:26:20 +00:00
{
return isset($this->definitions[$this->normalizeId($id)]);
2010-01-04 14:26:20 +00:00
}
/**
* Gets a service definition.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier
*
* @return Definition A Definition instance
*
* @throws ServiceNotFoundException if the service definition does not exist
*/
public function getDefinition($id)
2010-01-04 14:26:20 +00:00
{
$id = $this->normalizeId($id);
2016-08-21 13:01:27 +01:00
if (!isset($this->definitions[$id])) {
throw new ServiceNotFoundException($id);
}
2010-01-04 14:26:20 +00:00
return $this->definitions[$id];
2010-01-04 14:26:20 +00:00
}
/**
* Gets a service definition by id or alias.
*
* The method "unaliases" recursively to return a Definition instance.
*
2012-05-15 21:19:31 +01:00
* @param string $id The service identifier or alias
*
* @return Definition A Definition instance
*
* @throws ServiceNotFoundException if the service definition does not exist
*/
public function findDefinition($id)
{
$id = $this->normalizeId($id);
while (isset($this->aliasDefinitions[$id])) {
$id = (string) $this->aliasDefinitions[$id];
}
return $this->getDefinition($id);
}
/**
* Creates a service for a service definition.
*
2012-05-15 21:19:31 +01:00
* @param Definition $definition A service definition instance
* @param string $id The service identifier
* @param bool $tryProxy Whether to try proxying the service with a lazy proxy
*
* @return object The service described by the service definition
*
2014-11-30 13:33:44 +00:00
* @throws RuntimeException When the factory definition is incomplete
* @throws RuntimeException When the service is a synthetic service
* @throws InvalidArgumentException When configure callable is not callable
*/
2014-12-03 22:04:33 +00:00
private function createService(Definition $definition, $id, $tryProxy = true)
2010-01-04 14:26:20 +00:00
{
if ($definition instanceof ChildDefinition) {
throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
}
if ($definition->isSynthetic()) {
throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
}
if ($definition->isDeprecated()) {
@trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED);
}
2013-03-29 23:21:12 +00:00
if ($tryProxy && $definition->isLazy()) {
$proxy = $this
->getProxyInstantiator()
->instantiateProxy(
2014-12-03 22:04:33 +00:00
$this,
2013-03-29 23:21:12 +00:00
$definition,
2014-12-03 22:04:33 +00:00
$id, function () use ($definition, $id) {
return $this->createService($definition, $id, false);
2013-03-29 23:21:12 +00:00
}
);
$this->shareService($definition, $proxy, $id);
return $proxy;
}
$parameterBag = $this->getParameterBag();
if (null !== $definition->getFile()) {
require_once $parameterBag->resolveValue($definition->getFile());
2010-01-04 14:26:20 +00:00
}
$arguments = $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())));
if (null !== $factory = $definition->getFactory()) {
2016-12-17 15:24:27 +00:00
if ($definition->getOverriddenGetters()) {
throw new RuntimeException(sprintf('Cannot create service "%s": factories and overridden getters are incompatible with each other.', $id));
}
if (is_array($factory)) {
$factory = array($this->resolveServices($parameterBag->resolveValue($factory[0])), $factory[1]);
} elseif (!is_string($factory)) {
throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
}
$service = call_user_func_array($factory, $arguments);
if (!$definition->isDeprecated() && is_array($factory) && is_string($factory[0])) {
$r = new \ReflectionClass($factory[0]);
if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
@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);
}
}
} else {
$r = new \ReflectionClass($parameterBag->resolveValue($definition->getClass()));
if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
@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);
}
2016-12-17 15:24:27 +00:00
if ($definition->getOverriddenGetters()) {
static $salt;
if (null === $salt) {
$salt = str_replace('.', '', uniqid('', true));
}
2017-02-07 18:39:15 +00:00
$service = sprintf('%s implements \\%s { private $container%4$s; private $getters%4$s; %s }', $r->name, InheritanceProxyInterface::class, $this->generateOverriddenMethods($id, $definition, $r, $salt), $salt);
2016-12-17 15:24:27 +00:00
if (!class_exists($proxyClass = 'SymfonyProxy_'.md5($service), false)) {
eval(sprintf('class %s extends %s', $proxyClass, $service));
}
$r = new \ReflectionClass($proxyClass);
$constructor = $r->getConstructor();
if ($constructor && !defined('HHVM_VERSION') && $constructor->getDeclaringClass()->isInternal()) {
$constructor = null;
}
$service = $constructor ? $r->newInstanceWithoutConstructor() : $r->newInstanceArgs($arguments);
2017-02-07 18:39:15 +00:00
call_user_func(\Closure::bind(function ($c, $g, $s) { $this->{'container'.$s} = $c; $this->{'getters'.$s} = $g; }, $service, $service), $this, $definition->getOverriddenGetters(), $salt);
2016-12-17 15:24:27 +00:00
if ($constructor) {
$constructor->invokeArgs($service, $arguments);
}
} else {
$service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
}
}
2010-01-04 14:26:20 +00:00
2013-03-29 23:21:12 +00:00
if ($tryProxy || !$definition->isLazy()) {
// share only if proxying failed, or if not a proxy
$this->shareService($definition, $service, $id);
}
2010-01-04 14:26:20 +00:00
$properties = $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())));
foreach ($properties as $name => $value) {
$service->$name = $value;
}
foreach ($definition->getMethodCalls() as $call) {
$this->callMethod($service, $call);
}
if ($callable = $definition->getConfigurator()) {
if (is_array($callable)) {
$callable[0] = $parameterBag->resolveValue($callable[0]);
if ($callable[0] instanceof Reference) {
$callable[0] = $this->get((string) $callable[0], $callable[0]->getInvalidBehavior());
} elseif ($callable[0] instanceof Definition) {
$callable[0] = $this->createService($callable[0], null);
}
}
if (!is_callable($callable)) {
throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service)));
}
call_user_func($callable, $service);
}
return $service;
2010-01-04 14:26:20 +00:00
}
/**
* Replaces service references by the real service instance and evaluates expressions.
*
2012-05-15 21:19:31 +01:00
* @param mixed $value A value
*
* @return mixed The same value with all service references replaced by
* the real service instances and all expressions evaluated
*/
public function resolveServices($value)
2010-01-04 14:26:20 +00:00
{
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = $this->resolveServices($v);
}
} elseif ($value instanceof ServiceLocatorArgument) {
$parameterBag = $this->getParameterBag();
$services = array();
foreach ($value->getValues() as $k => $v) {
$services[$k] = function () use ($v, $parameterBag) {
return $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($v)));
};
}
$value = new ServiceLocator($services);
} elseif ($value instanceof IteratorArgument) {
$parameterBag = $this->getParameterBag();
$value = new RewindableGenerator(function () use ($value, $parameterBag) {
foreach ($value->getValues() as $k => $v) {
foreach (self::getServiceConditionals($v) as $s) {
if (!$this->has($s)) {
continue 2;
}
}
yield $k => $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($v)));
}
}, function () use ($value) {
$count = 0;
foreach ($value->getValues() as $v) {
foreach (self::getServiceConditionals($v) as $s) {
if (!$this->has($s)) {
continue 2;
}
}
++$count;
}
return $count;
});
} elseif ($value instanceof ClosureProxyArgument) {
$parameterBag = $this->getParameterBag();
list($reference, $method) = $value->getValues();
if ('service_container' === $id = (string) $reference) {
$class = parent::class;
} elseif (!$this->hasDefinition($id) && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
return;
} else {
$class = $parameterBag->resolveValue($this->findDefinition($id)->getClass());
}
if (!method_exists($class, $method = $parameterBag->resolveValue($method))) {
throw new InvalidArgumentException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" does not exist.', $id, $class, $method));
}
$r = new \ReflectionMethod($class, $method);
if (!$r->isPublic()) {
throw new RuntimeException(sprintf('Cannot create closure-proxy for service "%s": method "%s::%s" must be public.', $id, $class, $method));
}
foreach ($r->getParameters() as $p) {
if ($p->isPassedByReference()) {
throw new RuntimeException(sprintf('Cannot create closure-proxy for service "%s": parameter "$%s" of method "%s::%s" must not be passed by reference.', $id, $p->name, $class, $method));
}
}
$value = function () use ($id, $method) {
return call_user_func_array(array($this->get($id), $method), func_get_args());
};
} elseif ($value instanceof Reference) {
2010-06-27 17:28:29 +01:00
$value = $this->get((string) $value, $value->getInvalidBehavior());
} elseif ($value instanceof Definition) {
$value = $this->createService($value, null);
} elseif ($value instanceof Expression) {
$value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
}
return $value;
2010-01-04 14:26:20 +00:00
}
/**
2010-08-05 06:34:53 +01:00
* Returns service ids for a given tag.
*
* Example:
*
* $container->register('foo')->addTag('my.tag', array('hello' => 'world'));
*
* $serviceIds = $container->findTaggedServiceIds('my.tag');
* foreach ($serviceIds as $serviceId => $tags) {
* foreach ($tags as $tag) {
* echo $tag['hello'];
* }
* }
*
2010-08-05 06:34:53 +01:00
* @param string $name The tag name
*
* @return array An array of tags with the tagged service as key, holding a list of attribute arrays
*/
2010-08-05 06:34:53 +01:00
public function findTaggedServiceIds($name)
{
$this->usedTags[] = $name;
2010-08-05 06:34:53 +01:00
$tags = array();
foreach ($this->getDefinitions() as $id => $definition) {
if ($definition->hasTag($name)) {
2010-08-05 06:34:53 +01:00
$tags[$id] = $definition->getTag($name);
}
}
2010-08-05 06:34:53 +01:00
return $tags;
}
/**
* Returns all tags the defined services use.
*
* @return array An array of tags
*/
public function findTags()
{
$tags = array();
foreach ($this->getDefinitions() as $id => $definition) {
$tags = array_merge(array_keys($definition->getTags()), $tags);
}
return array_unique($tags);
}
/**
2015-09-28 12:00:47 +01:00
* Returns all tags not queried by findTaggedServiceIds.
*
2015-09-28 12:00:47 +01:00
* @return string[] An array of tags
*/
public function findUnusedTags()
{
2015-09-28 12:00:47 +01:00
return array_values(array_diff($this->findTags(), $this->usedTags));
}
public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
{
$this->expressionLanguageProviders[] = $provider;
}
/**
* @return ExpressionFunctionProviderInterface[]
*/
public function getExpressionLanguageProviders()
{
return $this->expressionLanguageProviders;
}
/**
* Resolves env parameter placeholders in a string or an array.
*
* @param mixed $value The value to resolve
* @param string|true|null $format A sprintf() format returning the replacement for each env var name or
* null to resolve back to the original "%env(VAR)%" format or
* true to resolve to the actual values of the referenced env vars
* @param array &$usedEnvs Env vars found while resolving are added to this array
*
* @return string The string with env parameters resolved
*/
public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null)
{
if (null === $format) {
$format = '%%env(%s)%%';
}
if (is_array($value)) {
$result = array();
foreach ($value as $k => $v) {
$result[$this->resolveEnvPlaceholders($k, $format, $usedEnvs)] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs);
}
return $result;
}
if (!is_string($value)) {
return $value;
}
$bag = $this->getParameterBag();
if (true === $format) {
$value = $bag->resolveValue($value);
}
$envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
foreach ($envPlaceholders as $env => $placeholders) {
foreach ($placeholders as $placeholder) {
if (false !== stripos($value, $placeholder)) {
if (true === $format) {
$resolved = $bag->escapeValue($this->getEnv($env));
} else {
$resolved = sprintf($format, $env);
}
$value = str_ireplace($placeholder, $resolved, $value);
$usedEnvs[$env] = $env;
$this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1;
}
}
}
return $value;
}
/**
* Get statistics about env usage.
*
* @return int[] The number of time each env vars has been resolved
*/
public function getEnvCounters()
{
$bag = $this->getParameterBag();
$envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
foreach ($envPlaceholders as $env => $placeholders) {
if (!isset($this->envCounters[$env])) {
$this->envCounters[$env] = 0;
}
}
return $this->envCounters;
}
2017-02-07 18:39:15 +00:00
private function generateOverriddenMethods($id, Definition $definition, \ReflectionClass $class, $salt)
2016-12-17 15:24:27 +00:00
{
if ($class->isFinal()) {
2017-02-07 18:39:15 +00:00
throw new RuntimeException(sprintf('Unable to configure service "%s": class "%s" cannot be marked as final.', $id, $class->name));
2016-12-17 15:24:27 +00:00
}
2017-02-07 18:39:15 +00:00
return $this->generateOverriddenGetters($id, $definition, $class, $salt);
}
private function generateOverriddenGetters($id, Definition $definition, \ReflectionClass $class, $salt)
{
2016-12-17 15:24:27 +00:00
$getters = '';
2017-02-07 18:39:15 +00:00
2016-12-17 15:24:27 +00:00
foreach ($definition->getOverriddenGetters() as $name => $returnValue) {
2017-02-07 18:39:15 +00:00
$r = InheritanceProxyHelper::getGetterReflector($class, $name, $id);
$signature = InheritanceProxyHelper::getSignature($r);
2016-12-17 15:24:27 +00:00
$visibility = $r->isProtected() ? 'protected' : 'public';
$getters .= <<<EOF
2017-02-07 18:39:15 +00:00
{$visibility} function {$signature} {
2016-12-17 15:24:27 +00:00
\$c = \$this->container{$salt};
\$b = \$c->getParameterBag();
2017-02-07 18:39:15 +00:00
\$v = \$this->getters{$salt}['{$name}'];
2016-12-17 15:24:27 +00:00
foreach (\$c->getServiceConditionals(\$v) as \$s) {
if (!\$c->has(\$s)) {
return parent::{$r->name}();
}
}
return \$c->resolveServices(\$b->unescapeValue(\$b->resolveValue(\$v)));
}
EOF;
}
return $getters;
}
/**
* @internal
*/
public function getNormalizedIds()
{
$normalizedIds = array();
foreach ($this->normalizedIds as $k => $v) {
if ($v !== (string) $k) {
$normalizedIds[$k] = $v;
}
}
return $normalizedIds;
}
/**
* @final
*/
public function log(CompilerPassInterface $pass, $message)
{
$this->getCompiler()->log($pass, $message);
}
2011-02-13 18:06:41 +00:00
/**
* Returns the Service Conditionals.
*
* @param mixed $value An array of conditionals to return
2011-12-13 07:50:54 +00:00
*
2011-02-13 18:06:41 +00:00
* @return array An array of Service conditionals
*/
2012-07-09 13:50:58 +01:00
public static function getServiceConditionals($value)
{
$services = array();
if (is_array($value)) {
foreach ($value as $v) {
$services = array_unique(array_merge($services, self::getServiceConditionals($v)));
}
} elseif ($value instanceof Reference && $value->getInvalidBehavior() === ContainerInterface::IGNORE_ON_INVALID_REFERENCE) {
$services[] = (string) $value;
}
2010-01-04 14:26:20 +00:00
return $services;
2010-01-04 14:26:20 +00:00
}
2013-03-29 23:21:12 +00:00
/**
* Retrieves the currently set proxy instantiator or instantiates one.
*
* @return InstantiatorInterface
*/
private function getProxyInstantiator()
{
if (!$this->proxyInstantiator) {
$this->proxyInstantiator = new RealServiceInstantiator();
}
return $this->proxyInstantiator;
}
private function callMethod($service, $call)
{
$services = self::getServiceConditionals($call[1]);
foreach ($services as $s) {
if (!$this->has($s)) {
return;
}
}
call_user_func_array(array($service, $call[0]), $this->resolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1]))));
}
2013-03-29 23:21:12 +00:00
/**
2014-12-21 17:00:50 +00:00
* Shares a given service in the container.
2013-03-29 23:21:12 +00:00
*
* @param Definition $definition
* @param mixed $service
* @param string|null $id
2013-03-29 23:21:12 +00:00
*/
private function shareService(Definition $definition, $service, $id)
{
if (null !== $id && $definition->isShared()) {
$this->services[$this->normalizeId($id)] = $service;
2013-03-29 23:21:12 +00:00
}
}
private function getExpressionLanguage()
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
$this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
}
return $this->expressionLanguage;
}
private function inVendors($path)
{
if (null === $this->vendors) {
$resource = new ComposerResource();
$this->vendors = $resource->getVendors();
$this->addResource($resource);
}
$path = realpath($path) ?: $path;
foreach ($this->vendors as $vendor) {
if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, strlen($vendor), 1), '/'.DIRECTORY_SEPARATOR)) {
return true;
}
}
return false;
}
2010-01-04 14:26:20 +00:00
}