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@0: use Symfony\Component\DependencyInjection\Compiler\Compiler; Chris@0: use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; Chris@0: use Symfony\Component\DependencyInjection\Compiler\PassConfig; 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@0: use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; Chris@0: use Symfony\Component\Config\Resource\FileResource; Chris@0: use Symfony\Component\Config\Resource\ResourceInterface; Chris@0: use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface; Chris@0: use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; 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@0: private $extensions = array(); Chris@0: Chris@0: /** Chris@0: * @var ExtensionInterface[] Chris@0: */ Chris@0: private $extensionsByNs = array(); Chris@0: Chris@0: /** Chris@0: * @var Definition[] Chris@0: */ Chris@0: private $definitions = array(); Chris@0: Chris@0: /** Chris@0: * @var Alias[] Chris@0: */ Chris@0: private $aliasDefinitions = array(); Chris@0: Chris@0: /** Chris@0: * @var ResourceInterface[] Chris@0: */ Chris@0: private $resources = array(); Chris@0: Chris@0: private $extensionConfigs = array(); 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@0: private $expressionLanguageProviders = array(); Chris@0: Chris@0: public function __construct(ParameterBagInterface $parameterBag = null) Chris@0: { Chris@0: parent::__construct($parameterBag); Chris@0: Chris@0: $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * @var string[] with tag names used by findTaggedServiceIds Chris@0: */ Chris@0: private $usedTags = array(); Chris@0: Chris@0: /** Chris@0: * @var string[][] a map of env var names to their placeholders Chris@0: */ Chris@0: private $envPlaceholders = array(); Chris@0: Chris@0: /** Chris@0: * @var int[] a map of env vars to their resolution counter Chris@0: */ Chris@0: private $envCounters = array(); Chris@0: Chris@0: /** 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@0: * @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@0: * @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: * @param InstantiatorInterface $proxyInstantiator Chris@0: */ Chris@0: public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator) Chris@0: { Chris@0: $this->proxyInstantiator = $proxyInstantiator; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers an extension. Chris@0: * Chris@0: * @param ExtensionInterface $extension An extension instance 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@0: return array_unique($this->resources); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds a resource for this configuration. Chris@0: * Chris@0: * @param ResourceInterface $resource A resource instance 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@0: $this->resources[] = $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@0: * @param object $object An object instance Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addObjectResource($object) Chris@0: { Chris@0: if ($this->trackResources) { Chris@0: $this->addClassResource(new \ReflectionClass($object)); 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@0: * @param \ReflectionClass $class Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function addClassResource(\ReflectionClass $class) Chris@0: { Chris@0: if (!$this->trackResources) { Chris@0: return $this; Chris@0: } Chris@0: Chris@0: do { Chris@0: if (is_file($class->getFileName())) { Chris@0: $this->addResource(new FileResource($class->getFileName())); Chris@0: } Chris@0: } while ($class = $class->getParentClass()); Chris@0: Chris@0: return $this; 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@0: * @throws BadMethodCallException When this ContainerBuilder is frozen Chris@0: * @throws \LogicException if the container is frozen Chris@0: */ Chris@0: public function loadFromExtension($extension, array $values = array()) Chris@0: { Chris@0: if ($this->isFrozen()) { Chris@0: throw new BadMethodCallException('Cannot load from an extension on a frozen container.'); 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@0: public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, $priority = 0*/) Chris@0: { Chris@0: if (func_num_args() >= 3) { Chris@0: $priority = func_get_arg(2); Chris@0: } else { Chris@0: if (__CLASS__ !== get_class($this)) { Chris@0: $r = new \ReflectionMethod($this, __FUNCTION__); Chris@0: if (__CLASS__ !== $r->getDeclaringClass()->getName()) { Chris@0: @trigger_error(sprintf('Method %s() will have a third `$priority = 0` argument in version 4.0. Not defining it is deprecated since 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@0: * @throws BadMethodCallException When this ContainerBuilder is frozen Chris@0: */ Chris@0: public function set($id, $service) Chris@0: { Chris@0: $id = strtolower($id); Chris@0: Chris@0: if ($this->isFrozen() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) { Chris@0: // setting a synthetic service on a frozen container is alright Chris@0: throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a frozen container is not allowed.', $id)); Chris@0: } Chris@0: Chris@0: unset($this->definitions[$id], $this->aliasDefinitions[$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@0: unset($this->definitions[strtolower($id)]); 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@0: $id = strtolower($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@0: $id = strtolower($id); Chris@0: Chris@0: if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) { Chris@0: return $service; Chris@0: } Chris@0: Chris@0: if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) { Chris@0: return $this->get((string) $this->aliasDefinitions[$id], $invalidBehavior); 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@0: $this->loading[$id] = true; Chris@0: Chris@0: try { Chris@0: $service = $this->createService($definition, $id); Chris@0: } finally { Chris@0: unset($this->loading[$id]); Chris@0: } Chris@0: Chris@0: return $service; 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@0: * $container = new ContainerBuilder(array('foo' => 'bar')); Chris@0: * $loader = new LoaderXXX($container); Chris@0: * $loader->load('resource_name'); Chris@0: * $container->register('foo', new 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@0: * @param ContainerBuilder $container The ContainerBuilder instance to merge Chris@0: * Chris@0: * @throws BadMethodCallException When this ContainerBuilder is frozen Chris@0: */ Chris@0: public function merge(ContainerBuilder $container) Chris@0: { Chris@0: if ($this->isFrozen()) { Chris@0: throw new BadMethodCallException('Cannot merge on a frozen 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@0: $this->extensionConfigs[$name] = array(); 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@0: $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag()); Chris@0: } Chris@0: Chris@0: foreach ($container->envCounters as $env => $count) { 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@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@0: $this->extensionConfigs[$name] = array(); 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@0: $this->extensionConfigs[$name] = array(); 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@0: */ Chris@0: public function compile() Chris@0: { 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@0: Chris@0: $compiler->compile($this); Chris@0: Chris@0: foreach ($this->definitions as $id => $definition) { Chris@0: if (!$definition->isPublic()) { Chris@0: $this->privates[$id] = true; Chris@0: } Chris@0: if ($this->trackResources && $definition->isLazy() && ($class = $definition->getClass()) && class_exists($class)) { Chris@0: $this->addClassResource(new \ReflectionClass($class)); Chris@0: } Chris@0: } Chris@0: Chris@0: $this->extensionConfigs = array(); Chris@0: $bag = $this->getParameterBag(); Chris@0: Chris@0: parent::compile(); Chris@0: Chris@0: $this->envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : array(); 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@0: * Adds the service aliases. Chris@0: * Chris@0: * @param array $aliases An array of 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: * @param array $aliases An array of aliases Chris@0: */ Chris@0: public function setAliases(array $aliases) Chris@0: { Chris@0: $this->aliasDefinitions = array(); 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@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@0: $alias = strtolower($alias); Chris@0: Chris@0: if (is_string($id)) { Chris@0: $id = new Alias($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@0: unset($this->definitions[$alias]); Chris@0: Chris@0: $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@0: unset($this->aliasDefinitions[strtolower($alias)]); 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@0: return isset($this->aliasDefinitions[strtolower($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@0: $id = strtolower($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@0: * @param string $id The service identifier Chris@0: * @param string $class 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@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@0: $this->definitions = array(); 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@0: * @throws BadMethodCallException When this ContainerBuilder is frozen Chris@0: */ Chris@0: public function setDefinition($id, Definition $definition) Chris@0: { Chris@0: if ($this->isFrozen()) { Chris@0: throw new BadMethodCallException('Adding definition to a frozen container is not allowed'); Chris@0: } Chris@0: Chris@0: $id = strtolower($id); Chris@0: Chris@0: unset($this->aliasDefinitions[$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@0: return isset($this->definitions[strtolower($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@0: $id = strtolower($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@0: $id = strtolower($id); Chris@0: Chris@0: while (isset($this->aliasDefinitions[$id])) { Chris@0: $id = (string) $this->aliasDefinitions[$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@0: private function createService(Definition $definition, $id, $tryProxy = true) Chris@0: { Chris@0: if ($definition instanceof DefinitionDecorator) { 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@0: if ($tryProxy && $definition->isLazy()) { Chris@0: $proxy = $this Chris@0: ->getProxyInstantiator() Chris@0: ->instantiateProxy( Chris@0: $this, Chris@0: $definition, Chris@0: $id, function () use ($definition, $id) { Chris@0: return $this->createService($definition, $id, false); Chris@0: } Chris@0: ); Chris@0: $this->shareService($definition, $proxy, $id); 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@0: $arguments = $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments()))); Chris@0: Chris@0: if (null !== $factory = $definition->getFactory()) { Chris@0: if (is_array($factory)) { Chris@0: $factory = array($this->resolveServices($parameterBag->resolveValue($factory[0])), $factory[1]); Chris@0: } elseif (!is_string($factory)) { Chris@0: throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id)); Chris@0: } Chris@0: Chris@0: $service = call_user_func_array($factory, $arguments); Chris@0: Chris@0: 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@0: $r = new \ReflectionClass($parameterBag->resolveValue($definition->getClass())); Chris@0: Chris@0: $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments); Chris@0: Chris@0: if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ")) { 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@0: $this->shareService($definition, $service, $id); Chris@0: } Chris@0: Chris@0: $properties = $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties()))); Chris@0: foreach ($properties as $name => $value) { Chris@0: $service->$name = $value; Chris@0: } Chris@0: Chris@0: foreach ($definition->getMethodCalls() as $call) { Chris@0: $this->callMethod($service, $call); Chris@0: } Chris@0: Chris@0: if ($callable = $definition->getConfigurator()) { Chris@0: if (is_array($callable)) { Chris@0: $callable[0] = $parameterBag->resolveValue($callable[0]); Chris@0: Chris@0: if ($callable[0] instanceof Reference) { Chris@0: $callable[0] = $this->get((string) $callable[0], $callable[0]->getInvalidBehavior()); Chris@0: } elseif ($callable[0] instanceof Definition) { Chris@0: $callable[0] = $this->createService($callable[0], null); Chris@0: } Chris@0: } Chris@0: Chris@0: if (!is_callable($callable)) { Chris@0: throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', get_class($service))); Chris@0: } Chris@0: Chris@0: 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@0: if (is_array($value)) { Chris@0: foreach ($value as $k => $v) { Chris@0: $value[$k] = $this->resolveServices($v); Chris@0: } Chris@0: } elseif ($value instanceof Reference) { Chris@0: $value = $this->get((string) $value, $value->getInvalidBehavior()); Chris@0: } elseif ($value instanceof Definition) { Chris@0: $value = $this->createService($value, null); Chris@0: } elseif ($value instanceof Expression) { Chris@0: $value = $this->getExpressionLanguage()->evaluate($value, array('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@0: * $container->register('foo')->addTag('my.tag', array('hello' => 'world')); Chris@0: * Chris@0: * $serviceIds = $container->findTaggedServiceIds('my.tag'); Chris@0: * foreach ($serviceIds as $serviceId => $tags) { Chris@0: * foreach ($tags as $tag) { Chris@0: * echo $tag['hello']; Chris@0: * } Chris@0: * } Chris@0: * Chris@0: * @param string $name The tag name 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@0: public function findTaggedServiceIds($name) Chris@0: { Chris@0: $this->usedTags[] = $name; Chris@0: $tags = array(); Chris@0: foreach ($this->getDefinitions() as $id => $definition) { Chris@0: if ($definition->hasTag($name)) { 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@0: $tags = array(); 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@0: * Resolves env parameter placeholders in a string or an array. Chris@0: * Chris@0: * @param mixed $value The value to resolve Chris@0: * @param string|null $format A sprintf() format to use as replacement for env placeholders or null to use the default parameter format Chris@0: * @param array &$usedEnvs Env vars found while resolving are added to this array Chris@0: * Chris@0: * @return string The string with env parameters resolved 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@0: if (is_array($value)) { Chris@0: $result = array(); Chris@0: foreach ($value as $k => $v) { Chris@0: $result[$this->resolveEnvPlaceholders($k, $format, $usedEnvs)] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs); Chris@0: } Chris@0: Chris@0: return $result; Chris@0: } Chris@0: Chris@0: if (!is_string($value)) { Chris@0: return $value; Chris@0: } 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: foreach ($placeholders as $placeholder) { Chris@0: if (false !== stripos($value, $placeholder)) { Chris@0: $value = str_ireplace($placeholder, sprintf($format, $env), $value); Chris@0: $usedEnvs[$env] = $env; Chris@0: $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1; 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@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@0: */ Chris@0: public static function getServiceConditionals($value) Chris@0: { Chris@0: $services = array(); Chris@0: Chris@0: if (is_array($value)) { Chris@0: foreach ($value as $v) { Chris@0: $services = array_unique(array_merge($services, self::getServiceConditionals($v))); Chris@0: } Chris@0: } elseif ($value instanceof Reference && $value->getInvalidBehavior() === ContainerInterface::IGNORE_ON_INVALID_REFERENCE) { Chris@0: $services[] = (string) $value; Chris@0: } Chris@0: Chris@0: return $services; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves the currently set proxy instantiator or instantiates one. Chris@0: * Chris@0: * @return InstantiatorInterface Chris@0: */ Chris@0: private function getProxyInstantiator() Chris@0: { Chris@0: if (!$this->proxyInstantiator) { Chris@0: $this->proxyInstantiator = new RealServiceInstantiator(); Chris@0: } Chris@0: Chris@0: return $this->proxyInstantiator; Chris@0: } Chris@0: Chris@0: private function callMethod($service, $call) Chris@0: { Chris@0: $services = self::getServiceConditionals($call[1]); Chris@0: Chris@0: foreach ($services as $s) { Chris@0: if (!$this->has($s)) { Chris@0: return; Chris@0: } Chris@0: } Chris@0: Chris@0: call_user_func_array(array($service, $call[0]), $this->resolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Shares a given service in the container. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * @param mixed $service Chris@0: * @param string|null $id Chris@0: */ Chris@0: private function shareService(Definition $definition, $service, $id) Chris@0: { Chris@0: if (null !== $id && $definition->isShared()) { Chris@0: $this->services[strtolower($id)] = $service; 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@0: }