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

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  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\ServiceCircularReferenceException;
  15. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  16. use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
  17. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  18. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  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 <fabien@symfony.com>
  34.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  35.  */
  36. class Container implements ResettableContainerInterface
  37. {
  38.     protected $parameterBag;
  39.     protected $services = [];
  40.     protected $fileMap = [];
  41.     protected $methodMap = [];
  42.     protected $aliases = [];
  43.     protected $loading = [];
  44.     protected $resolving = [];
  45.     protected $syntheticIds = [];
  46.     /**
  47.      * @internal
  48.      */
  49.     protected $privates = [];
  50.     /**
  51.      * @internal
  52.      */
  53.     protected $normalizedIds = [];
  54.     private $underscoreMap = ['_' => '''.' => '_''\\' => '_'];
  55.     private $envCache = [];
  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 Symfony 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 synthetic service to null resets it: 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|null $service The service instance
  148.      */
  149.     public function set($id$service)
  150.     {
  151.         // Runs the internal initializer; used by the dumped container to include always-needed files
  152.         if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
  153.             $initialize $this->privates['service_container'];
  154.             unset($this->privates['service_container']);
  155.             $initialize();
  156.         }
  157.         $id $this->normalizeId($id);
  158.         if ('service_container' === $id) {
  159.             throw new InvalidArgumentException('You cannot set service "service_container".');
  160.         }
  161.         if (isset($this->privates[$id]) || !(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  162.             if (!isset($this->privates[$id]) && !isset($this->getRemovedIds()[$id])) {
  163.                 // no-op
  164.             } elseif (null === $service) {
  165.                 @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);
  166.                 unset($this->privates[$id]);
  167.             } else {
  168.                 @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);
  169.             }
  170.         } elseif (isset($this->services[$id])) {
  171.             if (null === $service) {
  172.                 @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);
  173.             } else {
  174.                 @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);
  175.             }
  176.         }
  177.         if (isset($this->aliases[$id])) {
  178.             unset($this->aliases[$id]);
  179.         }
  180.         if (null === $service) {
  181.             unset($this->services[$id]);
  182.             return;
  183.         }
  184.         $this->services[$id] = $service;
  185.     }
  186.     /**
  187.      * Returns true if the given service is defined.
  188.      *
  189.      * @param string $id The service identifier
  190.      *
  191.      * @return bool true if the service is defined, false otherwise
  192.      */
  193.     public function has($id)
  194.     {
  195.         for ($i 2;;) {
  196.             if (isset($this->privates[$id])) {
  197.                 @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);
  198.             }
  199.             if (isset($this->aliases[$id])) {
  200.                 $id $this->aliases[$id];
  201.             }
  202.             if (isset($this->services[$id])) {
  203.                 return true;
  204.             }
  205.             if ('service_container' === $id) {
  206.                 return true;
  207.             }
  208.             if (isset($this->fileMap[$id]) || isset($this->methodMap[$id])) {
  209.                 return true;
  210.             }
  211.             if (--$i && $id !== $normalizedId $this->normalizeId($id)) {
  212.                 $id $normalizedId;
  213.                 continue;
  214.             }
  215.             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  216.             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  217.             if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this'get'.strtr($id$this->underscoreMap).'Service')) {
  218.                 @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', \E_USER_DEPRECATED);
  219.                 return true;
  220.             }
  221.             return false;
  222.         }
  223.     }
  224.     /**
  225.      * Gets a service.
  226.      *
  227.      * If a service is defined both through a set() method and
  228.      * with a get{$id}Service() method, the former has always precedence.
  229.      *
  230.      * @param string $id              The service identifier
  231.      * @param int    $invalidBehavior The behavior when the service does not exist
  232.      *
  233.      * @return object|null The associated service
  234.      *
  235.      * @throws ServiceCircularReferenceException When a circular reference is detected
  236.      * @throws ServiceNotFoundException          When the service is not defined
  237.      * @throws \Exception                        if an exception has been thrown when the service has been resolved
  238.      *
  239.      * @see Reference
  240.      */
  241.     public function get($id$invalidBehavior /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1)
  242.     {
  243.         // Attempt to retrieve the service by checking first aliases then
  244.         // available services. Service IDs are case insensitive, however since
  245.         // this method can be called thousands of times during a request, avoid
  246.         // calling $this->normalizeId($id) unless necessary.
  247.         for ($i 2;;) {
  248.             if (isset($this->privates[$id])) {
  249.                 @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);
  250.             }
  251.             if (isset($this->aliases[$id])) {
  252.                 $id $this->aliases[$id];
  253.             }
  254.             // Re-use shared service instance if it exists.
  255.             if (isset($this->services[$id])) {
  256.                 return $this->services[$id];
  257.             }
  258.             if ('service_container' === $id) {
  259.                 return $this;
  260.             }
  261.             if (isset($this->loading[$id])) {
  262.                 throw new ServiceCircularReferenceException($idarray_merge(array_keys($this->loading), [$id]));
  263.             }
  264.             $this->loading[$id] = true;
  265.             try {
  266.                 if (isset($this->fileMap[$id])) {
  267.                     return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $this->load($this->fileMap[$id]);
  268.                 } elseif (isset($this->methodMap[$id])) {
  269.                     return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $this->{$this->methodMap[$id]}();
  270.                 } elseif (--$i && $id !== $normalizedId $this->normalizeId($id)) {
  271.                     unset($this->loading[$id]);
  272.                     $id $normalizedId;
  273.                     continue;
  274.                 } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this$method 'get'.strtr($id$this->underscoreMap).'Service')) {
  275.                     // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  276.                     // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  277.                     @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', \E_USER_DEPRECATED);
  278.                     return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $this->{$method}();
  279.                 }
  280.                 break;
  281.             } catch (\Exception $e) {
  282.                 unset($this->services[$id]);
  283.                 throw $e;
  284.             } finally {
  285.                 unset($this->loading[$id]);
  286.             }
  287.         }
  288.         if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ === $invalidBehavior) {
  289.             if (!$id) {
  290.                 throw new ServiceNotFoundException($id);
  291.             }
  292.             if (isset($this->syntheticIds[$id])) {
  293.                 throw new ServiceNotFoundException($idnullnull, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.'$id));
  294.             }
  295.             if (isset($this->getRemovedIds()[$id])) {
  296.                 throw new ServiceNotFoundException($idnullnull, [], 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));
  297.             }
  298.             $alternatives = [];
  299.             foreach ($this->getServiceIds() as $knownId) {
  300.                 $lev levenshtein($id$knownId);
  301.                 if ($lev <= \strlen($id) / || false !== strpos($knownId$id)) {
  302.                     $alternatives[] = $knownId;
  303.                 }
  304.             }
  305.             throw new ServiceNotFoundException($idnullnull$alternatives);
  306.         }
  307.     }
  308.     /**
  309.      * Returns true if the given service has actually been initialized.
  310.      *
  311.      * @param string $id The service identifier
  312.      *
  313.      * @return bool true if service has already been initialized, false otherwise
  314.      */
  315.     public function initialized($id)
  316.     {
  317.         $id $this->normalizeId($id);
  318.         if (isset($this->privates[$id])) {
  319.             @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);
  320.         }
  321.         if (isset($this->aliases[$id])) {
  322.             $id $this->aliases[$id];
  323.         }
  324.         if ('service_container' === $id) {
  325.             return false;
  326.         }
  327.         return isset($this->services[$id]);
  328.     }
  329.     /**
  330.      * {@inheritdoc}
  331.      */
  332.     public function reset()
  333.     {
  334.         $this->services = [];
  335.     }
  336.     /**
  337.      * Gets all service ids.
  338.      *
  339.      * @return string[] An array of all defined service ids
  340.      */
  341.     public function getServiceIds()
  342.     {
  343.         $ids = [];
  344.         if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) {
  345.             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
  346.             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
  347.             @trigger_error('Generating a dumped container without populating the method map is deprecated since Symfony 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', \E_USER_DEPRECATED);
  348.             foreach (get_class_methods($this) as $method) {
  349.                 if (preg_match('/^get(.+)Service$/'$method$match)) {
  350.                     $ids[] = self::underscore($match[1]);
  351.                 }
  352.             }
  353.         }
  354.         $ids[] = 'service_container';
  355.         return array_map('strval'array_unique(array_merge($idsarray_keys($this->methodMap), array_keys($this->fileMap), array_keys($this->aliases), array_keys($this->services))));
  356.     }
  357.     /**
  358.      * Gets service ids that existed at compile time.
  359.      *
  360.      * @return array
  361.      */
  362.     public function getRemovedIds()
  363.     {
  364.         return [];
  365.     }
  366.     /**
  367.      * Camelizes a string.
  368.      *
  369.      * @param string $id A string to camelize
  370.      *
  371.      * @return string The camelized string
  372.      */
  373.     public static function camelize($id)
  374.     {
  375.         return strtr(ucwords(strtr($id, ['_' => ' ''.' => '_ ''\\' => '_ '])), [' ' => '']);
  376.     }
  377.     /**
  378.      * A string to underscore.
  379.      *
  380.      * @param string $id The string to underscore
  381.      *
  382.      * @return string The underscored string
  383.      */
  384.     public static function underscore($id)
  385.     {
  386.         return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/''/([a-z\d])([A-Z])/'], ['\\1_\\2''\\1_\\2'], str_replace('_''.'$id)));
  387.     }
  388.     /**
  389.      * Creates a service by requiring its factory file.
  390.      */
  391.     protected function load($file)
  392.     {
  393.         return require $file;
  394.     }
  395.     /**
  396.      * Fetches a variable from the environment.
  397.      *
  398.      * @param string $name The name of the environment variable
  399.      *
  400.      * @return mixed The value to use for the provided environment variable name
  401.      *
  402.      * @throws EnvNotFoundException When the environment variable is not found and has no default value
  403.      */
  404.     protected function getEnv($name)
  405.     {
  406.         if (isset($this->resolving[$envName "env($name)"])) {
  407.             throw new ParameterCircularReferenceException(array_keys($this->resolving));
  408.         }
  409.         if (isset($this->envCache[$name]) || \array_key_exists($name$this->envCache)) {
  410.             return $this->envCache[$name];
  411.         }
  412.         if (!$this->has($id 'container.env_var_processors_locator')) {
  413.             $this->set($id, new ServiceLocator([]));
  414.         }
  415.         if (!$this->getEnv) {
  416.             $this->getEnv = new \ReflectionMethod($this__FUNCTION__);
  417.             $this->getEnv->setAccessible(true);
  418.             $this->getEnv $this->getEnv->getClosure($this);
  419.         }
  420.         $processors $this->get($id);
  421.         if (false !== $i strpos($name':')) {
  422.             $prefix substr($name0$i);
  423.             $localName substr($name$i);
  424.         } else {
  425.             $prefix 'string';
  426.             $localName $name;
  427.         }
  428.         $processor $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  429.         $this->resolving[$envName] = true;
  430.         try {
  431.             return $this->envCache[$name] = $processor->getEnv($prefix$localName$this->getEnv);
  432.         } finally {
  433.             unset($this->resolving[$envName]);
  434.         }
  435.     }
  436.     /**
  437.      * Returns the case sensitive id used at registration time.
  438.      *
  439.      * @param string $id
  440.      *
  441.      * @return string
  442.      *
  443.      * @internal
  444.      */
  445.     public function normalizeId($id)
  446.     {
  447.         if (!\is_string($id)) {
  448.             $id = (string) $id;
  449.         }
  450.         if (isset($this->normalizedIds[$normalizedId strtolower($id)])) {
  451.             $normalizedId $this->normalizedIds[$normalizedId];
  452.             if ($id !== $normalizedId) {
  453.                 @trigger_error(sprintf('Service identifiers will be made case sensitive in Symfony 4.0. Using "%s" instead of "%s" is deprecated since Symfony 3.3.'$id$normalizedId), \E_USER_DEPRECATED);
  454.             }
  455.         } else {
  456.             $normalizedId $this->normalizedIds[$normalizedId] = $id;
  457.         }
  458.         return $normalizedId;
  459.     }
  460.     private function __clone()
  461.     {
  462.     }
  463. }