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

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