vendor/symfony/dependency-injection/Container.php line 150

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\Argument\RewindableGenerator;
  12. use Symfony\Component\DependencyInjection\Argument\ServiceLocator as ArgumentServiceLocator;
  13. use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
  14. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  15. use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
  16. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  17. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  18. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  19. use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
  20. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  21. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  22. use Symfony\Contracts\Service\ResetInterface;
  23. // Help opcache.preload discover always-needed symbols
  24. class_exists(RewindableGenerator::class);
  25. class_exists(ArgumentServiceLocator::class);
  26. /**
  27.  * Container is a dependency injection container.
  28.  *
  29.  * It gives access to object instances (services).
  30.  * Services and parameters are simple key/pair stores.
  31.  * The container can have four possible behaviors when a service
  32.  * does not exist (or is not initialized for the last case):
  33.  *
  34.  *  * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
  35.  *  * NULL_ON_INVALID_REFERENCE:      Returns null
  36.  *  * IGNORE_ON_INVALID_REFERENCE:    Ignores the wrapping command asking for the reference
  37.  *                                    (for instance, ignore a setter if the service does not exist)
  38.  *  * IGNORE_ON_UNINITIALIZED_REFERENCE: Ignores/returns null for uninitialized services or invalid references
  39.  *
  40.  * @author Fabien Potencier <fabien@symfony.com>
  41.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  42.  */
  43. class Container implements ContainerInterfaceResetInterface
  44. {
  45.     protected $parameterBag;
  46.     protected $services = [];
  47.     protected $privates = [];
  48.     protected $fileMap = [];
  49.     protected $methodMap = [];
  50.     protected $factories = [];
  51.     protected $aliases = [];
  52.     protected $loading = [];
  53.     protected $resolving = [];
  54.     protected $syntheticIds = [];
  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.      * Gets the service container parameter bag.
  87.      *
  88.      * @return ParameterBagInterface
  89.      */
  90.     public function getParameterBag()
  91.     {
  92.         return $this->parameterBag;
  93.     }
  94.     /**
  95.      * Gets a parameter.
  96.      *
  97.      * @return array|bool|string|int|float|\UnitEnum|null
  98.      *
  99.      * @throws InvalidArgumentException if the parameter is not defined
  100.      */
  101.     public function getParameter(string $name)
  102.     {
  103.         return $this->parameterBag->get($name);
  104.     }
  105.     /**
  106.      * @return bool
  107.      */
  108.     public function hasParameter(string $name)
  109.     {
  110.         return $this->parameterBag->has($name);
  111.     }
  112.     /**
  113.      * Sets a parameter.
  114.      *
  115.      * @param string                                     $name  The parameter name
  116.      * @param array|bool|string|int|float|\UnitEnum|null $value The parameter value
  117.      */
  118.     public function setParameter(string $name$value)
  119.     {
  120.         $this->parameterBag->set($name$value);
  121.     }
  122.     /**
  123.      * Sets a service.
  124.      *
  125.      * Setting a synthetic service to null resets it: has() returns false and get()
  126.      * behaves in the same way as if the service was never created.
  127.      */
  128.     public function set(string $id, ?object $service)
  129.     {
  130.         // Runs the internal initializer; used by the dumped container to include always-needed files
  131.         if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
  132.             $initialize $this->privates['service_container'];
  133.             unset($this->privates['service_container']);
  134.             $initialize();
  135.         }
  136.         if ('service_container' === $id) {
  137.             throw new InvalidArgumentException('You cannot set service "service_container".');
  138.         }
  139.         if (!(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  140.             if (isset($this->syntheticIds[$id]) || !isset($this->getRemovedIds()[$id])) {
  141.                 // no-op
  142.             } elseif (null === $service) {
  143.                 throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot unset it.'$id));
  144.             } else {
  145.                 throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot replace it.'$id));
  146.             }
  147.         } elseif (isset($this->services[$id])) {
  148.             throw new InvalidArgumentException(sprintf('The "%s" service is already initialized, you cannot replace it.'$id));
  149.         }
  150.         if (isset($this->aliases[$id])) {
  151.             unset($this->aliases[$id]);
  152.         }
  153.         if (null === $service) {
  154.             unset($this->services[$id]);
  155.             return;
  156.         }
  157.         $this->services[$id] = $service;
  158.     }
  159.     /**
  160.      * Returns true if the given service is defined.
  161.      *
  162.      * @param string $id The service identifier
  163.      *
  164.      * @return bool
  165.      */
  166.     public function has(string $id)
  167.     {
  168.         if (isset($this->aliases[$id])) {
  169.             $id $this->aliases[$id];
  170.         }
  171.         if (isset($this->services[$id])) {
  172.             return true;
  173.         }
  174.         if ('service_container' === $id) {
  175.             return true;
  176.         }
  177.         return isset($this->fileMap[$id]) || isset($this->methodMap[$id]);
  178.     }
  179.     /**
  180.      * Gets a service.
  181.      *
  182.      * @return object|null
  183.      *
  184.      * @throws ServiceCircularReferenceException When a circular reference is detected
  185.      * @throws ServiceNotFoundException          When the service is not defined
  186.      * @throws \Exception                        if an exception has been thrown when the service has been resolved
  187.      *
  188.      * @see Reference
  189.      */
  190.     public function get(string $idint $invalidBehavior /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1)
  191.     {
  192.         return $this->services[$id]
  193.             ?? $this->services[$id $this->aliases[$id] ?? $id]
  194.             ?? ('service_container' === $id $this : ($this->factories[$id] ?? [$this'make'])($id$invalidBehavior));
  195.     }
  196.     /**
  197.      * Creates a service.
  198.      *
  199.      * As a separate method to allow "get()" to use the really fast `??` operator.
  200.      */
  201.     private function make(string $idint $invalidBehavior)
  202.     {
  203.         if (isset($this->loading[$id])) {
  204.             throw new ServiceCircularReferenceException($idarray_merge(array_keys($this->loading), [$id]));
  205.         }
  206.         $this->loading[$id] = true;
  207.         try {
  208.             if (isset($this->fileMap[$id])) {
  209.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $this->load($this->fileMap[$id]);
  210.             } elseif (isset($this->methodMap[$id])) {
  211.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $this->{$this->methodMap[$id]}();
  212.             }
  213.         } catch (\Exception $e) {
  214.             unset($this->services[$id]);
  215.             throw $e;
  216.         } finally {
  217.             unset($this->loading[$id]);
  218.         }
  219.         if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ === $invalidBehavior) {
  220.             if (!$id) {
  221.                 throw new ServiceNotFoundException($id);
  222.             }
  223.             if (isset($this->syntheticIds[$id])) {
  224.                 throw new ServiceNotFoundException($idnullnull, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.'$id));
  225.             }
  226.             if (isset($this->getRemovedIds()[$id])) {
  227.                 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));
  228.             }
  229.             $alternatives = [];
  230.             foreach ($this->getServiceIds() as $knownId) {
  231.                 if ('' === $knownId || '.' === $knownId[0]) {
  232.                     continue;
  233.                 }
  234.                 $lev levenshtein($id$knownId);
  235.                 if ($lev <= \strlen($id) / || str_contains($knownId$id)) {
  236.                     $alternatives[] = $knownId;
  237.                 }
  238.             }
  239.             throw new ServiceNotFoundException($idnullnull$alternatives);
  240.         }
  241.         return null;
  242.     }
  243.     /**
  244.      * Returns true if the given service has actually been initialized.
  245.      *
  246.      * @return bool
  247.      */
  248.     public function initialized(string $id)
  249.     {
  250.         if (isset($this->aliases[$id])) {
  251.             $id $this->aliases[$id];
  252.         }
  253.         if ('service_container' === $id) {
  254.             return false;
  255.         }
  256.         return isset($this->services[$id]);
  257.     }
  258.     /**
  259.      * {@inheritdoc}
  260.      */
  261.     public function reset()
  262.     {
  263.         $services $this->services $this->privates;
  264.         $this->services $this->factories $this->privates = [];
  265.         foreach ($services as $service) {
  266.             try {
  267.                 if ($service instanceof ResetInterface) {
  268.                     $service->reset();
  269.                 }
  270.             } catch (\Throwable $e) {
  271.                 continue;
  272.             }
  273.         }
  274.     }
  275.     /**
  276.      * Gets all service ids.
  277.      *
  278.      * @return string[]
  279.      */
  280.     public function getServiceIds()
  281.     {
  282.         return array_map('strval'array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->aliases), array_keys($this->services))));
  283.     }
  284.     /**
  285.      * Gets service ids that existed at compile time.
  286.      *
  287.      * @return array
  288.      */
  289.     public function getRemovedIds()
  290.     {
  291.         return [];
  292.     }
  293.     /**
  294.      * Camelizes a string.
  295.      *
  296.      * @return string
  297.      */
  298.     public static function camelize(string $id)
  299.     {
  300.         return strtr(ucwords(strtr($id, ['_' => ' ''.' => '_ ''\\' => '_ '])), [' ' => '']);
  301.     }
  302.     /**
  303.      * A string to underscore.
  304.      *
  305.      * @return string
  306.      */
  307.     public static function underscore(string $id)
  308.     {
  309.         return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/''/([a-z\d])([A-Z])/'], ['\\1_\\2''\\1_\\2'], str_replace('_''.'$id)));
  310.     }
  311.     /**
  312.      * Creates a service by requiring its factory file.
  313.      */
  314.     protected function load(string $file)
  315.     {
  316.         return require $file;
  317.     }
  318.     /**
  319.      * Fetches a variable from the environment.
  320.      *
  321.      * @return mixed
  322.      *
  323.      * @throws EnvNotFoundException When the environment variable is not found and has no default value
  324.      */
  325.     protected function getEnv(string $name)
  326.     {
  327.         if (isset($this->resolving[$envName "env($name)"])) {
  328.             throw new ParameterCircularReferenceException(array_keys($this->resolving));
  329.         }
  330.         if (isset($this->envCache[$name]) || \array_key_exists($name$this->envCache)) {
  331.             return $this->envCache[$name];
  332.         }
  333.         if (!$this->has($id 'container.env_var_processors_locator')) {
  334.             $this->set($id, new ServiceLocator([]));
  335.         }
  336.         if (!$this->getEnv) {
  337.             $this->getEnv = \Closure::fromCallable([$this'getEnv']);
  338.         }
  339.         $processors $this->get($id);
  340.         if (false !== $i strpos($name':')) {
  341.             $prefix substr($name0$i);
  342.             $localName substr($name$i);
  343.         } else {
  344.             $prefix 'string';
  345.             $localName $name;
  346.         }
  347.         $processor $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  348.         $this->resolving[$envName] = true;
  349.         try {
  350.             return $this->envCache[$name] = $processor->getEnv($prefix$localName$this->getEnv);
  351.         } finally {
  352.             unset($this->resolving[$envName]);
  353.         }
  354.     }
  355.     /**
  356.      * @param string|false $registry
  357.      * @param string|bool  $load
  358.      *
  359.      * @return mixed
  360.      *
  361.      * @internal
  362.      */
  363.     final protected function getService($registrystring $id, ?string $method$load)
  364.     {
  365.         if ('service_container' === $id) {
  366.             return $this;
  367.         }
  368.         if (\is_string($load)) {
  369.             throw new RuntimeException($load);
  370.         }
  371.         if (null === $method) {
  372.             return false !== $registry $this->{$registry}[$id] ?? null null;
  373.         }
  374.         if (false !== $registry) {
  375.             return $this->{$registry}[$id] ?? $this->{$registry}[$id] = $load $this->load($method) : $this->{$method}();
  376.         }
  377.         if (!$load) {
  378.             return $this->{$method}();
  379.         }
  380.         return ($factory $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory() : $this->load($method);
  381.     }
  382.     private function __clone()
  383.     {
  384.     }
  385. }