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

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 at compilation time (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. * * RUNTIME_EXCEPTION_ON_INVALID_REFERENCE: Throws an exception at runtime
  40. *
  41. * @author Fabien Potencier <fabien@symfony.com>
  42. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  43. */
  44. class Container implements ContainerInterface, ResetInterface
  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 $envCache = [];
  57. private $compiled = false;
  58. private $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. * @return bool
  81. */
  82. public function isCompiled()
  83. {
  84. return $this->compiled;
  85. }
  86. /**
  87. * Gets the service container parameter bag.
  88. *
  89. * @return ParameterBagInterface
  90. */
  91. public function getParameterBag()
  92. {
  93. return $this->parameterBag;
  94. }
  95. /**
  96. * Gets a parameter.
  97. *
  98. * @return array|bool|string|int|float|\UnitEnum|null
  99. *
  100. * @throws InvalidArgumentException if the parameter is not defined
  101. */
  102. public function getParameter(string $name)
  103. {
  104. return $this->parameterBag->get($name);
  105. }
  106. /**
  107. * @return bool
  108. */
  109. public function hasParameter(string $name)
  110. {
  111. return $this->parameterBag->has($name);
  112. }
  113. /**
  114. * Sets a parameter.
  115. *
  116. * @param string $name The parameter name
  117. * @param array|bool|string|int|float|\UnitEnum|null $value The parameter value
  118. */
  119. public function setParameter(string $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. public function set(string $id, ?object $service)
  130. {
  131. // Runs the internal initializer; used by the dumped container to include always-needed files
  132. if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
  133. $initialize = $this->privates['service_container'];
  134. unset($this->privates['service_container']);
  135. $initialize();
  136. }
  137. if ('service_container' === $id) {
  138. throw new InvalidArgumentException('You cannot set service "service_container".');
  139. }
  140. if (!(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  141. if (isset($this->syntheticIds[$id]) || !isset($this->getRemovedIds()[$id])) {
  142. // no-op
  143. } elseif (null === $service) {
  144. throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot unset it.', $id));
  145. } else {
  146. throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot replace it.', $id));
  147. }
  148. } elseif (isset($this->services[$id])) {
  149. throw new InvalidArgumentException(sprintf('The "%s" service is already initialized, you cannot replace it.', $id));
  150. }
  151. if (isset($this->aliases[$id])) {
  152. unset($this->aliases[$id]);
  153. }
  154. if (null === $service) {
  155. unset($this->services[$id]);
  156. return;
  157. }
  158. $this->services[$id] = $service;
  159. }
  160. /**
  161. * Returns true if the given service is defined.
  162. *
  163. * @param string $id The service identifier
  164. *
  165. * @return bool
  166. */
  167. public function has(string $id)
  168. {
  169. if (isset($this->aliases[$id])) {
  170. $id = $this->aliases[$id];
  171. }
  172. if (isset($this->services[$id])) {
  173. return true;
  174. }
  175. if ('service_container' === $id) {
  176. return true;
  177. }
  178. return isset($this->fileMap[$id]) || isset($this->methodMap[$id]);
  179. }
  180. /**
  181. * Gets a service.
  182. *
  183. * @return object|null
  184. *
  185. * @throws ServiceCircularReferenceException When a circular reference is detected
  186. * @throws ServiceNotFoundException When the service is not defined
  187. * @throws \Exception if an exception has been thrown when the service has been resolved
  188. *
  189. * @see Reference
  190. */
  191. public function get(string $id, int $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1)
  192. {
  193. return $this->services[$id]
  194. ?? $this->services[$id = $this->aliases[$id] ?? $id]
  195. ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? [$this, 'make'])($id, $invalidBehavior));
  196. }
  197. /**
  198. * Creates a service.
  199. *
  200. * As a separate method to allow "get()" to use the really fast `??` operator.
  201. */
  202. private function make(string $id, int $invalidBehavior)
  203. {
  204. if (isset($this->loading[$id])) {
  205. throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id]));
  206. }
  207. $this->loading[$id] = true;
  208. try {
  209. if (isset($this->fileMap[$id])) {
  210. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->load($this->fileMap[$id]);
  211. } elseif (isset($this->methodMap[$id])) {
  212. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$this->methodMap[$id]}();
  213. }
  214. } catch (\Exception $e) {
  215. unset($this->services[$id]);
  216. throw $e;
  217. } finally {
  218. unset($this->loading[$id]);
  219. }
  220. if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ 1 === $invalidBehavior) {
  221. if (!$id) {
  222. throw new ServiceNotFoundException($id);
  223. }
  224. if (isset($this->syntheticIds[$id])) {
  225. throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id));
  226. }
  227. if (isset($this->getRemovedIds()[$id])) {
  228. throw new ServiceNotFoundException($id, null, null, [], 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));
  229. }
  230. $alternatives = [];
  231. foreach ($this->getServiceIds() as $knownId) {
  232. if ('' === $knownId || '.' === $knownId[0]) {
  233. continue;
  234. }
  235. $lev = levenshtein($id, $knownId);
  236. if ($lev <= \strlen($id) / 3 || str_contains($knownId, $id)) {
  237. $alternatives[] = $knownId;
  238. }
  239. }
  240. throw new ServiceNotFoundException($id, null, null, $alternatives);
  241. }
  242. return null;
  243. }
  244. /**
  245. * Returns true if the given service has actually been initialized.
  246. *
  247. * @return bool
  248. */
  249. public function initialized(string $id)
  250. {
  251. if (isset($this->aliases[$id])) {
  252. $id = $this->aliases[$id];
  253. }
  254. if ('service_container' === $id) {
  255. return false;
  256. }
  257. return isset($this->services[$id]);
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function reset()
  263. {
  264. $services = $this->services + $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. $this->services = $this->factories = $this->privates = [];
  275. }
  276. /**
  277. * Gets all service ids.
  278. *
  279. * @return string[]
  280. */
  281. public function getServiceIds()
  282. {
  283. 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))));
  284. }
  285. /**
  286. * Gets service ids that existed at compile time.
  287. *
  288. * @return array
  289. */
  290. public function getRemovedIds()
  291. {
  292. return [];
  293. }
  294. /**
  295. * Camelizes a string.
  296. *
  297. * @return string
  298. */
  299. public static function camelize(string $id)
  300. {
  301. return strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']);
  302. }
  303. /**
  304. * A string to underscore.
  305. *
  306. * @return string
  307. */
  308. public static function underscore(string $id)
  309. {
  310. return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], str_replace('_', '.', $id)));
  311. }
  312. /**
  313. * Creates a service by requiring its factory file.
  314. */
  315. protected function load(string $file)
  316. {
  317. return require $file;
  318. }
  319. /**
  320. * Fetches a variable from the environment.
  321. *
  322. * @return mixed
  323. *
  324. * @throws EnvNotFoundException When the environment variable is not found and has no default value
  325. */
  326. protected function getEnv(string $name)
  327. {
  328. if (isset($this->resolving[$envName = "env($name)"])) {
  329. throw new ParameterCircularReferenceException(array_keys($this->resolving));
  330. }
  331. if (isset($this->envCache[$name]) || \array_key_exists($name, $this->envCache)) {
  332. return $this->envCache[$name];
  333. }
  334. if (!$this->has($id = 'container.env_var_processors_locator')) {
  335. $this->set($id, new ServiceLocator([]));
  336. }
  337. if (!$this->getEnv) {
  338. $this->getEnv = \Closure::fromCallable([$this, 'getEnv']);
  339. }
  340. $processors = $this->get($id);
  341. if (false !== $i = strpos($name, ':')) {
  342. $prefix = substr($name, 0, $i);
  343. $localName = substr($name, 1 + $i);
  344. } else {
  345. $prefix = 'string';
  346. $localName = $name;
  347. }
  348. $processor = $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  349. if (false === $i) {
  350. $prefix = '';
  351. }
  352. $this->resolving[$envName] = true;
  353. try {
  354. return $this->envCache[$name] = $processor->getEnv($prefix, $localName, $this->getEnv);
  355. } finally {
  356. unset($this->resolving[$envName]);
  357. }
  358. }
  359. /**
  360. * @param string|false $registry
  361. * @param string|bool $load
  362. *
  363. * @return mixed
  364. *
  365. * @internal
  366. */
  367. final protected function getService($registry, string $id, ?string $method, $load)
  368. {
  369. if ('service_container' === $id) {
  370. return $this;
  371. }
  372. if (\is_string($load)) {
  373. throw new RuntimeException($load);
  374. }
  375. if (null === $method) {
  376. return false !== $registry ? $this->{$registry}[$id] ?? null : null;
  377. }
  378. if (false !== $registry) {
  379. return $this->{$registry}[$id] ?? $this->{$registry}[$id] = $load ? $this->load($method) : $this->{$method}();
  380. }
  381. if (!$load) {
  382. return $this->{$method}();
  383. }
  384. return ($factory = $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory() : $this->load($method);
  385. }
  386. private function __clone()
  387. {
  388. }
  389. }