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\Exception\EnvNotFoundException; Chris@0: use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; Chris@0: use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag; Chris@0: use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; Chris@0: Chris@0: /** Chris@0: * Container is a dependency injection container. Chris@0: * Chris@0: * It gives access to object instances (services). Chris@0: * Chris@0: * Services and parameters are simple key/pair stores. Chris@0: * Chris@0: * Parameter and service keys are case insensitive. Chris@0: * Chris@0: * A service can also be defined by creating a method named Chris@0: * getXXXService(), where XXX is the camelized version of the id: Chris@0: * Chris@0: * Chris@0: * Chris@0: * The container can have three possible behaviors when a service does not exist: Chris@0: * Chris@0: * * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default) Chris@0: * * NULL_ON_INVALID_REFERENCE: Returns null Chris@0: * * IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference Chris@0: * (for instance, ignore a setter if the service does not exist) Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * @author Johannes M. Schmitt Chris@0: */ Chris@0: class Container implements ResettableContainerInterface Chris@0: { Chris@0: /** Chris@0: * @var ParameterBagInterface Chris@0: */ Chris@0: protected $parameterBag; Chris@0: Chris@0: protected $services = array(); Chris@0: protected $methodMap = array(); Chris@0: protected $aliases = array(); Chris@0: protected $loading = array(); Chris@0: Chris@12: /** Chris@12: * @internal Chris@12: */ Chris@12: protected $privates = array(); Chris@12: Chris@0: private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_'); Chris@0: private $envCache = array(); Chris@0: Chris@0: /** Chris@0: * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance Chris@0: */ Chris@0: public function __construct(ParameterBagInterface $parameterBag = null) Chris@0: { Chris@0: $this->parameterBag = $parameterBag ?: new EnvPlaceholderParameterBag(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Compiles the container. Chris@0: * Chris@0: * This method does two things: Chris@0: * Chris@0: * * Parameter values are resolved; Chris@0: * * The parameter bag is frozen. Chris@0: */ Chris@0: public function compile() Chris@0: { Chris@0: $this->parameterBag->resolve(); Chris@0: Chris@0: $this->parameterBag = new FrozenParameterBag($this->parameterBag->all()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the container parameter bag are frozen. Chris@0: * Chris@0: * @return bool true if the container parameter bag are frozen, false otherwise Chris@0: */ Chris@0: public function isFrozen() Chris@0: { Chris@0: return $this->parameterBag instanceof FrozenParameterBag; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the service container parameter bag. Chris@0: * Chris@0: * @return ParameterBagInterface A ParameterBagInterface instance Chris@0: */ Chris@0: public function getParameterBag() Chris@0: { Chris@0: return $this->parameterBag; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a parameter. Chris@0: * Chris@0: * @param string $name The parameter name Chris@0: * Chris@0: * @return mixed The parameter value Chris@0: * Chris@0: * @throws InvalidArgumentException if the parameter is not defined Chris@0: */ Chris@0: public function getParameter($name) Chris@0: { Chris@0: return $this->parameterBag->get($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if a parameter exists. Chris@0: * Chris@0: * @param string $name The parameter name Chris@0: * Chris@0: * @return bool The presence of parameter in container Chris@0: */ Chris@0: public function hasParameter($name) Chris@0: { Chris@0: return $this->parameterBag->has($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a parameter. Chris@0: * Chris@0: * @param string $name The parameter name Chris@0: * @param mixed $value The parameter value Chris@0: */ Chris@0: public function setParameter($name, $value) Chris@0: { Chris@0: $this->parameterBag->set($name, $value); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a service. Chris@0: * Chris@0: * Setting a service to null resets the service: has() returns false and get() Chris@0: * behaves in the same way as if the service was never created. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * @param object $service The service instance Chris@0: */ Chris@0: public function set($id, $service) Chris@0: { Chris@0: $id = strtolower($id); Chris@0: Chris@0: if ('service_container' === $id) { Chris@0: throw new InvalidArgumentException('You cannot set service "service_container".'); Chris@0: } Chris@0: Chris@0: if (isset($this->aliases[$id])) { Chris@0: unset($this->aliases[$id]); Chris@0: } Chris@0: Chris@0: $this->services[$id] = $service; Chris@0: Chris@0: if (null === $service) { Chris@0: unset($this->services[$id]); Chris@0: } Chris@0: Chris@0: if (isset($this->privates[$id])) { Chris@0: if (null === $service) { Chris@0: @trigger_error(sprintf('Unsetting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED); Chris@0: unset($this->privates[$id]); Chris@0: } else { Chris@0: @trigger_error(sprintf('Setting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0. A new public service will be created instead.', $id), E_USER_DEPRECATED); Chris@0: } Chris@0: } 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: for ($i = 2;;) { Chris@12: if (isset($this->privates[$id])) { Chris@12: @trigger_error(sprintf('Checking for the existence of the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED); Chris@12: } Chris@12: Chris@0: if ('service_container' === $id Chris@0: || isset($this->aliases[$id]) Chris@0: || isset($this->services[$id]) Chris@0: ) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (isset($this->methodMap[$id])) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (--$i && $id !== $lcId = strtolower($id)) { Chris@0: $id = $lcId; Chris@0: continue; Chris@0: } Chris@0: Chris@0: // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder, Chris@0: // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper) Chris@0: if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, 'get'.strtr($id, $this->underscoreMap).'Service')) { Chris@0: @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a service. Chris@0: * Chris@0: * If a service is defined both through a set() method and Chris@0: * with a get{$id}Service() method, the former has always precedence. 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 ServiceCircularReferenceException When a circular reference is detected Chris@0: * @throws ServiceNotFoundException When the service is not defined Chris@0: * @throws \Exception if an exception has been thrown when the service has been resolved Chris@0: * Chris@0: * @see Reference Chris@0: */ Chris@0: public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) Chris@0: { Chris@0: // Attempt to retrieve the service by checking first aliases then Chris@0: // available services. Service IDs are case insensitive, however since Chris@0: // this method can be called thousands of times during a request, avoid Chris@0: // calling strtolower() unless necessary. Chris@0: for ($i = 2;;) { Chris@12: if (isset($this->privates[$id])) { Chris@12: @trigger_error(sprintf('Requesting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED); Chris@0: } Chris@0: if (isset($this->aliases[$id])) { Chris@0: $id = $this->aliases[$id]; Chris@0: } Chris@12: Chris@0: // Re-use shared service instance if it exists. Chris@0: if (isset($this->services[$id])) { Chris@0: return $this->services[$id]; Chris@0: } Chris@12: if ('service_container' === $id) { Chris@12: return $this; Chris@12: } Chris@0: Chris@0: if (isset($this->loading[$id])) { Chris@0: throw new ServiceCircularReferenceException($id, array_keys($this->loading)); Chris@0: } Chris@0: Chris@0: if (isset($this->methodMap[$id])) { Chris@0: $method = $this->methodMap[$id]; Chris@0: } elseif (--$i && $id !== $lcId = strtolower($id)) { Chris@0: $id = $lcId; Chris@0: continue; Chris@0: } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap).'Service')) { Chris@0: // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder, Chris@0: // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper) Chris@0: @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED); Chris@0: // $method is set to the right value, proceed Chris@0: } else { Chris@0: if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) { Chris@0: if (!$id) { Chris@0: throw new ServiceNotFoundException($id); Chris@0: } Chris@0: Chris@0: $alternatives = array(); Chris@0: foreach ($this->getServiceIds() as $knownId) { Chris@0: $lev = levenshtein($id, $knownId); Chris@0: if ($lev <= strlen($id) / 3 || false !== strpos($knownId, $id)) { Chris@0: $alternatives[] = $knownId; Chris@0: } Chris@0: } Chris@0: Chris@0: throw new ServiceNotFoundException($id, null, null, $alternatives); Chris@0: } Chris@0: Chris@0: return; Chris@0: } Chris@0: Chris@0: $this->loading[$id] = true; Chris@0: Chris@0: try { Chris@0: $service = $this->$method(); Chris@0: } catch (\Exception $e) { Chris@0: unset($this->services[$id]); Chris@0: Chris@0: throw $e; 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: /** Chris@0: * Returns true if the given service has actually been initialized. Chris@0: * Chris@0: * @param string $id The service identifier Chris@0: * Chris@0: * @return bool true if service has already been initialized, false otherwise Chris@0: */ Chris@0: public function initialized($id) Chris@0: { Chris@0: $id = strtolower($id); Chris@0: Chris@12: if (isset($this->aliases[$id])) { Chris@12: $id = $this->aliases[$id]; Chris@12: } Chris@12: Chris@0: if ('service_container' === $id) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: return isset($this->services[$id]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function reset() Chris@0: { Chris@0: $this->services = 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: $ids = array(); Chris@0: Chris@0: if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) { Chris@0: // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder, Chris@0: // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper) Chris@0: @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED); Chris@0: Chris@0: foreach (get_class_methods($this) as $method) { Chris@0: if (preg_match('/^get(.+)Service$/', $method, $match)) { Chris@0: $ids[] = self::underscore($match[1]); Chris@0: } Chris@0: } Chris@0: } Chris@0: $ids[] = 'service_container'; Chris@0: Chris@0: return array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->services))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Camelizes a string. Chris@0: * Chris@0: * @param string $id A string to camelize Chris@0: * Chris@0: * @return string The camelized string Chris@0: */ Chris@0: public static function camelize($id) Chris@0: { Chris@0: return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => '')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * A string to underscore. Chris@0: * Chris@0: * @param string $id The string to underscore Chris@0: * Chris@0: * @return string The underscored string Chris@0: */ Chris@0: public static function underscore($id) Chris@0: { Chris@0: return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Fetches a variable from the environment. Chris@0: * Chris@0: * @param string The name of the environment variable Chris@0: * Chris@0: * @return scalar The value to use for the provided environment variable name Chris@0: * Chris@0: * @throws EnvNotFoundException When the environment variable is not found and has no default value Chris@0: */ Chris@0: protected function getEnv($name) Chris@0: { Chris@0: if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) { Chris@0: return $this->envCache[$name]; Chris@0: } Chris@0: if (isset($_ENV[$name])) { Chris@0: return $this->envCache[$name] = $_ENV[$name]; Chris@0: } Chris@0: if (false !== $env = getenv($name)) { Chris@0: return $this->envCache[$name] = $env; Chris@0: } Chris@0: if (!$this->hasParameter("env($name)")) { Chris@0: throw new EnvNotFoundException($name); Chris@0: } Chris@0: Chris@0: return $this->envCache[$name] = $this->getParameter("env($name)"); Chris@0: } Chris@0: Chris@0: private function __clone() Chris@0: { Chris@0: } Chris@0: }