vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Container.php line 297

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
  14. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  15. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  17. use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
  18. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  19. /**
  20.  * Container is a dependency injection container.
  21.  *
  22.  * It gives access to object instances (services).
  23.  * Services and parameters are simple key/pair stores.
  24.  * The container can have four possible behaviors when a service
  25.  * does not exist (or is not initialized for the last case):
  26.  *
  27.  *  * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  28.  *  * NULL_ON_INVALID_REFERENCE:      Returns null
  29.  *  * IGNORE_ON_INVALID_REFERENCE:    Ignores the wrapping command asking for the reference
  30.  *                                    (for instance, ignore a setter if the service does not exist)
  31.  *  * IGNORE_ON_UNINITIALIZED_REFERENCE: Ignores/returns null for uninitialized services or invalid references
  32.  *
  33.  * @author Fabien Potencier <[email protected]>
  34.  * @author Johannes M. Schmitt <[email protected]>
  35.  */
  36. class Container implements ResettableContainerInterface
  37. {
  38.     protected $parameterBag;
  39.     protected $services = array();
  40.     protected $fileMap = array();
  41.     protected $methodMap = array();
  42.     protected $aliases = array();
  43.     protected $loading = array();
  44.     protected $resolving = array();
  45.     protected $syntheticIds = array();
  46.     /**
  47.      * @internal
  48.      */
  49.     protected $privates = array();
  50.     /**
  51.      * @internal
  52.      */
  53.     protected $normalizedIds = array();
  54.     private $underscoreMap = array('_' => '''.' => '_''\\' => '_');
  55.     private $envCache = array();
  56.     private $compiled false;
  57.     private $getEnv;
  58.     public function __construct(ParameterBagInterface $parameterBag null)
  59.     {
  60.         $this->parameterBag $parameterBag ?: new EnvPlaceholderParameterBag();
  61.     }
  62.     /**
  63.      * Compiles the container.
  64.      *
  65.      * This method does two things:
  66.      *
  67.      *  * Parameter values are resolved;
  68.      *  * The parameter bag is frozen.
  69.      */
  70.     public function compile()
  71.     {
  72.         $this->parameterBag->resolve();
  73.         $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
  74.         $this->compiled true;
  75.     }
  76.     /**
  77.      * Returns true if the container is compiled.
  78.      *
  79.      * @return bool
  80.      */
  81.     public function isCompiled()
  82.     {
  83.         return $this->compiled;
  84.     }
  85.     /**
  86.      * Returns true if the container parameter bag are frozen.
  87.      *
  88.      * @deprecated since version 3.3, to be removed in 4.0.
  89.      *
  90.      * @return bool true if the container parameter bag are frozen, false otherwise
  91.      */
  92.     public function isFrozen()
  93.     {
  94.         @trigger_error(sprintf('The %s() method is deprecated since version 3.3 and will be removed in 4.0. Use the isCompiled() method instead.'__METHOD__), E_USER_DEPRECATED);
  95.         return $this->parameterBag instanceof FrozenParameterBag;
  96.     }
  97.     /**
  98.      * Gets the service container parameter bag.
  99.      *
  100.      * @return ParameterBagInterface A ParameterBagInterface instance
  101.      */
  102.     public function getParameterBag()
  103.     {
  104.         return $this->parameterBag;
  105.     }
  106.     /**
  107.      * Gets a parameter.
  108.      *
  109.      * @param string $name The parameter name
  110.      *
  111.      * @return mixed The parameter value
  112.      *
  113.      * @throws InvalidArgumentException if the parameter is not defined
  114.      */
  115.     public function getParameter($name)
  116.     {
  117.         return $this->parameterBag->get($name);
  118.     }
  119.     /**
  120.      * Checks if a parameter exists.
  121.      *
  122.      * @param string $name The parameter name
  123.      *
  124.      * @return bool The presence of parameter in container
  125.      */
  126.     public function hasParameter($name)
  127.     {
  128.         return $this->parameterBag->has($name);
  129.     }
  130.     /**
  131.      * Sets a parameter.
  132.      *
  133.      * @param string $name  The parameter name
  134.      * @param mixed  $value The parameter value
  135.      */
  136.     public function setParameter($name$value)
  137.     {
  138.         $this->parameterBag->set($name$value);
  139.     }
  140.     /**
  141.      * Sets a service.
  142.      *
  143.      * Setting a service to null resets the service: has() returns false and get()
  144.      * behaves in the same way as if the service was never created.
  145.      *
  146.      * @param string $id      The service identifier
  147.      * @param object $service The service instance
  148.      */
  149.     public function set($id$service)
  150.     {
  151.         $id $this->normalizeId($id);
  152.         if ('service_container' === $id) {
  153.             throw new InvalidArgumentException('You cannot set service "service_container".');
  154.         }
  155.         if (isset($this->privates[$id]) || !(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  156.             if (!isset($this->privates[$id]) && !isset($this->getRemovedIds()[$id])) {
  157.                 // no-op
  158.             } elseif (null === $service) {
  159.                 @trigger_error(sprintf('The "%s" service is private, unsetting it is deprecated since Symfony 3.2 and will fail in 4.0.'$id), E_USER_DEPRECATED);
  160.                 unset($this->privates[$id]);
  161.             } else {
  162.                 @trigger_error(sprintf('The "%s" service is private, replacing it is deprecated since Symfony 3.2 and will fail in 4.0.'$id), E_USER_DEPRECATED);
  163.             }
  164.         } elseif (isset($this->services[$id])) {
  165.             if (null === $service) {
  166.                 @trigger_error(sprintf('The "%s" service is already initialized, unsetting it is deprecated since Symfony 3.3 and will fail in 4.0.'$id), E_USER_DEPRECATED);
  167.             } else {
  168.                 @trigger_error(sprintf('The "%s" service is already initialized, replacing it is deprecated since Symfony 3.3 and will fail in 4.0.'$id), E_USER_DEPRECATED);
  169.             }
  170.         }
  171.         if (isset($this->aliases[$id])) {
  172.             unset($this->aliases[$id]);
  173.         }
  174.         if (null === $service) {
  175.             unset($this->services[$id]);
  176.             return;
  177.         }
  178.         $this->services[$id] = $service;
  179.     }
  180.     /**
  181.      * Returns true if the given service is defined.
  182.      *
  183.      * @param string $id The service identifier
  184.      *
  185.      * @return bool true if the service is defined, false otherwise
  186.      */
  187.     public function has($id)
  188.     {
  189.         for ($i 2;;) {
  190.             if (isset($this->privates[$id])) {
  191.                 @trigger_error(sprintf('The "%s" service is private, checking for its existence is deprecated since Symfony 3.2 and will fail in 4.0.'$id), E_USER_DEPRECATED);
  192.             }
  193.             if (isset($this->aliases[$id])) {
  194.                 $id $this->aliases[$id];
  195.             }
  196.             if (isset($this->services[$id])) {
  197.                 return true;
  198.             }
  199.             if ('service_container' === $id) {
  200.                 return true;
  201.             }
  202.             if (isset($this->fileMap[$id]) || isset($this->methodMap[$id])) {
  203.                 return true;
  204.             }
  205.             if (--$i && $id !== $normalizedId $this->normalizeId($id)) {
  206.                 $id $normalizedId;
  207.                 continue;
  208.             }
  209.             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  210.             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  211.             if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this'get'.strtr($id$this->underscoreMap).'Service')) {
  212.                 @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);
  213.                 return true;
  214.             }
  215.             return false;
  216.         }
  217.     }
  218.     /**
  219.      * Gets a service.
  220.      *
  221.      * If a service is defined both through a set() method and
  222.      * with a get{$id}Service() method, the former has always precedence.
  223.      *
  224.      * @param string $id              The service identifier
  225.      * @param int    $invalidBehavior The behavior when the service does not exist
  226.      *
  227.      * @return object The associated service
  228.      *
  229.      * @throws ServiceCircularReferenceException When a circular reference is detected
  230.      * @throws ServiceNotFoundException          When the service is not defined
  231.      * @throws \Exception                        if an exception has been thrown when the service has been resolved
  232.      *
  233.      * @see Reference
  234.      */
  235.     public function get($id$invalidBehavior self::EXCEPTION_ON_INVALID_REFERENCE)
  236.     {
  237.         // Attempt to retrieve the service by checking first aliases then
  238.         // available services. Service IDs are case insensitive, however since
  239.         // this method can be called thousands of times during a request, avoid
  240.         // calling $this->normalizeId($id) unless necessary.
  241.         for ($i 2;;) {
  242.             if (isset($this->privates[$id])) {
  243.                 @trigger_error(sprintf('The "%s" service is private, getting it from the container is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead.'$id), E_USER_DEPRECATED);
  244.             }
  245.             if (isset($this->aliases[$id])) {
  246.                 $id $this->aliases[$id];
  247.             }
  248.             // Re-use shared service instance if it exists.
  249.             if (isset($this->services[$id])) {
  250.                 return $this->services[$id];
  251.             }
  252.             if ('service_container' === $id) {
  253.                 return $this;
  254.             }
  255.             if (isset($this->loading[$id])) {
  256.                 throw new ServiceCircularReferenceException($idarray_keys($this->loading));
  257.             }
  258.             $this->loading[$id] = true;
  259.             try {
  260.                 if (isset($this->fileMap[$id])) {
  261.                     return self::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior null $this->load($this->fileMap[$id]);
  262.                 } elseif (isset($this->methodMap[$id])) {
  263.                     return self::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior null $this->{$this->methodMap[$id]}();
  264.                 } elseif (--$i && $id !== $normalizedId $this->normalizeId($id)) {
  265.                     unset($this->loading[$id]);
  266.                     $id $normalizedId;
  267.                     continue;
  268.                 } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this$method 'get'.strtr($id$this->underscoreMap).'Service')) {
  269.                     // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  270.                     // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  271.                     @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);
  272.                     return self::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior null $this->{$method}();
  273.                 }
  274.                 break;
  275.             } catch (\Exception $e) {
  276.                 unset($this->services[$id]);
  277.                 throw $e;
  278.             } finally {
  279.                 unset($this->loading[$id]);
  280.             }
  281.         }
  282.         if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  283.             if (!$id) {
  284.                 throw new ServiceNotFoundException($id);
  285.             }
  286.             if (isset($this->syntheticIds[$id])) {
  287.                 throw new ServiceNotFoundException($idnullnull, array(), sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.'$id));
  288.             }
  289.             if (isset($this->getRemovedIds()[$id])) {
  290.                 throw new ServiceNotFoundException($idnullnull, array(), sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.'$id));
  291.             }
  292.             $alternatives = array();
  293.             foreach ($this->getServiceIds() as $knownId) {
  294.                 $lev levenshtein($id$knownId);
  295.                 if ($lev <= strlen($id) / || false !== strpos($knownId$id)) {
  296.                     $alternatives[] = $knownId;
  297.                 }
  298.             }
  299.             throw new ServiceNotFoundException($idnullnull$alternatives);
  300.         }
  301.     }
  302.     /**
  303.      * Returns true if the given service has actually been initialized.
  304.      *
  305.      * @param string $id The service identifier
  306.      *
  307.      * @return bool true if service has already been initialized, false otherwise
  308.      */
  309.     public function initialized($id)
  310.     {
  311.         $id $this->normalizeId($id);
  312.         if (isset($this->privates[$id])) {
  313.             @trigger_error(sprintf('Checking for the initialization of the "%s" private service is deprecated since Symfony 3.4 and won\'t be supported anymore in Symfony 4.0.'$id), E_USER_DEPRECATED);
  314.         }
  315.         if (isset($this->aliases[$id])) {
  316.             $id $this->aliases[$id];
  317.         }
  318.         if ('service_container' === $id) {
  319.             return false;
  320.         }
  321.         return isset($this->services[$id]);
  322.     }
  323.     /**
  324.      * {@inheritdoc}
  325.      */
  326.     public function reset()
  327.     {
  328.         $this->services = array();
  329.     }
  330.     /**
  331.      * Gets all service ids.
  332.      *
  333.      * @return array An array of all defined service ids
  334.      */
  335.     public function getServiceIds()
  336.     {
  337.         $ids = array();
  338.         if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) {
  339.             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  340.             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  341.             @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);
  342.             foreach (get_class_methods($this) as $method) {
  343.                 if (preg_match('/^get(.+)Service$/'$method$match)) {
  344.                     $ids[] = self::underscore($match[1]);
  345.                 }
  346.             }
  347.         }
  348.         $ids[] = 'service_container';
  349.         return array_unique(array_merge($idsarray_keys($this->methodMap), array_keys($this->fileMap), array_keys($this->services)));
  350.     }
  351.     /**
  352.      * Gets service ids that existed at compile time.
  353.      *
  354.      * @return array
  355.      */
  356.     public function getRemovedIds()
  357.     {
  358.         return array();
  359.     }
  360.     /**
  361.      * Camelizes a string.
  362.      *
  363.      * @param string $id A string to camelize
  364.      *
  365.      * @return string The camelized string
  366.      */
  367.     public static function camelize($id)
  368.     {
  369.         return strtr(ucwords(strtr($id, array('_' => ' ''.' => '_ ''\\' => '_ '))), array(' ' => ''));
  370.     }
  371.     /**
  372.      * A string to underscore.
  373.      *
  374.      * @param string $id The string to underscore
  375.      *
  376.      * @return string The underscored string
  377.      */
  378.     public static function underscore($id)
  379.     {
  380.         return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/''/([a-z\d])([A-Z])/'), array('\\1_\\2''\\1_\\2'), str_replace('_''.'$id)));
  381.     }
  382.     /**
  383.      * Creates a service by requiring its factory file.
  384.      *
  385.      * @return object The service created by the file
  386.      */
  387.     protected function load($file)
  388.     {
  389.         return require $file;
  390.     }
  391.     /**
  392.      * Fetches a variable from the environment.
  393.      *
  394.      * @param string $name The name of the environment variable
  395.      *
  396.      * @return mixed The value to use for the provided environment variable name
  397.      *
  398.      * @throws EnvNotFoundException When the environment variable is not found and has no default value
  399.      */
  400.     protected function getEnv($name)
  401.     {
  402.         if (isset($this->resolving[$envName "env($name)"])) {
  403.             throw new ParameterCircularReferenceException(array_keys($this->resolving));
  404.         }
  405.         if (isset($this->envCache[$name]) || array_key_exists($name$this->envCache)) {
  406.             return $this->envCache[$name];
  407.         }
  408.         if (!$this->has($id 'container.env_var_processors_locator')) {
  409.             $this->set($id, new ServiceLocator(array()));
  410.         }
  411.         if (!$this->getEnv) {
  412.             $this->getEnv = new \ReflectionMethod($this__FUNCTION__);
  413.             $this->getEnv->setAccessible(true);
  414.             $this->getEnv $this->getEnv->getClosure($this);
  415.         }
  416.         $processors $this->get($id);
  417.         if (false !== $i strpos($name':')) {
  418.             $prefix substr($name0$i);
  419.             $localName substr($name$i);
  420.         } else {
  421.             $prefix 'string';
  422.             $localName $name;
  423.         }
  424.         $processor $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  425.         $this->resolving[$envName] = true;
  426.         try {
  427.             return $this->envCache[$name] = $processor->getEnv($prefix$localName$this->getEnv);
  428.         } finally {
  429.             unset($this->resolving[$envName]);
  430.         }
  431.     }
  432.     /**
  433.      * Returns the case sensitive id used at registration time.
  434.      *
  435.      * @param string $id
  436.      *
  437.      * @return string
  438.      *
  439.      * @internal
  440.      */
  441.     public function normalizeId($id)
  442.     {
  443.         if (!is_string($id)) {
  444.             $id = (string) $id;
  445.         }
  446.         if (isset($this->normalizedIds[$normalizedId strtolower($id)])) {
  447.             $normalizedId $this->normalizedIds[$normalizedId];
  448.             if ($id !== $normalizedId) {
  449.                 @trigger_error(sprintf('Service identifiers will be made case sensitive in Symfony 4.0. Using "%s" instead of "%s" is deprecated since version 3.3.'$id$normalizedId), E_USER_DEPRECATED);
  450.             }
  451.         } else {
  452.             $normalizedId $this->normalizedIds[$normalizedId] = $id;
  453.         }
  454.         return $normalizedId;
  455.     }
  456.     private function __clone()
  457.     {
  458.     }
  459. }