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

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