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

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