Container.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 ResettableContainerInterface
  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 A ParameterBagInterface instance
  89. */
  90. public function getParameterBag()
  91. {
  92. return $this->parameterBag;
  93. }
  94. /**
  95. * Gets a parameter.
  96. *
  97. * @param string $name The parameter name
  98. *
  99. * @return array|bool|float|int|string|null The parameter value
  100. *
  101. * @throws InvalidArgumentException if the parameter is not defined
  102. */
  103. public function getParameter($name)
  104. {
  105. return $this->parameterBag->get($name);
  106. }
  107. /**
  108. * Checks if a parameter exists.
  109. *
  110. * @param string $name The parameter name
  111. *
  112. * @return bool The presence of parameter in container
  113. */
  114. public function hasParameter($name)
  115. {
  116. return $this->parameterBag->has($name);
  117. }
  118. /**
  119. * Sets a parameter.
  120. *
  121. * @param string $name The parameter name
  122. * @param mixed $value The parameter value
  123. */
  124. public function setParameter($name, $value)
  125. {
  126. $this->parameterBag->set($name, $value);
  127. }
  128. /**
  129. * Sets a service.
  130. *
  131. * Setting a synthetic service to null resets it: has() returns false and get()
  132. * behaves in the same way as if the service was never created.
  133. *
  134. * @param string $id The service identifier
  135. * @param object|null $service The service instance
  136. */
  137. public function set($id, $service)
  138. {
  139. // Runs the internal initializer; used by the dumped container to include always-needed files
  140. if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
  141. $initialize = $this->privates['service_container'];
  142. unset($this->privates['service_container']);
  143. $initialize();
  144. }
  145. if ('service_container' === $id) {
  146. throw new InvalidArgumentException('You cannot set service "service_container".');
  147. }
  148. if (!(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  149. if (isset($this->syntheticIds[$id]) || !isset($this->getRemovedIds()[$id])) {
  150. // no-op
  151. } elseif (null === $service) {
  152. throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot unset it.', $id));
  153. } else {
  154. throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot replace it.', $id));
  155. }
  156. } elseif (isset($this->services[$id])) {
  157. throw new InvalidArgumentException(sprintf('The "%s" service is already initialized, you cannot replace it.', $id));
  158. }
  159. if (isset($this->aliases[$id])) {
  160. unset($this->aliases[$id]);
  161. }
  162. if (null === $service) {
  163. unset($this->services[$id]);
  164. return;
  165. }
  166. $this->services[$id] = $service;
  167. }
  168. /**
  169. * Returns true if the given service is defined.
  170. *
  171. * @param string $id The service identifier
  172. *
  173. * @return bool true if the service is defined, false otherwise
  174. */
  175. public function has($id)
  176. {
  177. if (isset($this->aliases[$id])) {
  178. $id = $this->aliases[$id];
  179. }
  180. if (isset($this->services[$id])) {
  181. return true;
  182. }
  183. if ('service_container' === $id) {
  184. return true;
  185. }
  186. return isset($this->fileMap[$id]) || isset($this->methodMap[$id]);
  187. }
  188. /**
  189. * Gets a service.
  190. *
  191. * @param string $id The service identifier
  192. * @param int $invalidBehavior The behavior when the service does not exist
  193. *
  194. * @return object|null The associated service
  195. *
  196. * @throws ServiceCircularReferenceException When a circular reference is detected
  197. * @throws ServiceNotFoundException When the service is not defined
  198. * @throws \Exception if an exception has been thrown when the service has been resolved
  199. *
  200. * @see Reference
  201. */
  202. public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1)
  203. {
  204. $service = $this->services[$id]
  205. ?? $this->services[$id = $this->aliases[$id] ?? $id]
  206. ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? [$this, 'make'])($id, $invalidBehavior));
  207. if (!\is_object($service) && null !== $service) {
  208. @trigger_error(sprintf('Non-object services are deprecated since Symfony 4.4, please fix the "%s" service which is of type "%s" right now.', $id, \gettype($service)), \E_USER_DEPRECATED);
  209. }
  210. return $service;
  211. }
  212. /**
  213. * Creates a service.
  214. *
  215. * As a separate method to allow "get()" to use the really fast `??` operator.
  216. */
  217. private function make(string $id, int $invalidBehavior)
  218. {
  219. if (isset($this->loading[$id])) {
  220. throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id]));
  221. }
  222. $this->loading[$id] = true;
  223. try {
  224. if (isset($this->fileMap[$id])) {
  225. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->load($this->fileMap[$id]);
  226. } elseif (isset($this->methodMap[$id])) {
  227. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$this->methodMap[$id]}();
  228. }
  229. } catch (\Exception $e) {
  230. unset($this->services[$id]);
  231. throw $e;
  232. } finally {
  233. unset($this->loading[$id]);
  234. }
  235. if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ 1 === $invalidBehavior) {
  236. if (!$id) {
  237. throw new ServiceNotFoundException($id);
  238. }
  239. if (isset($this->syntheticIds[$id])) {
  240. 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));
  241. }
  242. if (isset($this->getRemovedIds()[$id])) {
  243. 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));
  244. }
  245. $alternatives = [];
  246. foreach ($this->getServiceIds() as $knownId) {
  247. if ('' === $knownId || '.' === $knownId[0]) {
  248. continue;
  249. }
  250. $lev = levenshtein($id, $knownId);
  251. if ($lev <= \strlen($id) / 3 || false !== strpos($knownId, $id)) {
  252. $alternatives[] = $knownId;
  253. }
  254. }
  255. throw new ServiceNotFoundException($id, null, null, $alternatives);
  256. }
  257. return null;
  258. }
  259. /**
  260. * Returns true if the given service has actually been initialized.
  261. *
  262. * @param string $id The service identifier
  263. *
  264. * @return bool true if service has already been initialized, false otherwise
  265. */
  266. public function initialized($id)
  267. {
  268. if (isset($this->aliases[$id])) {
  269. $id = $this->aliases[$id];
  270. }
  271. if ('service_container' === $id) {
  272. return false;
  273. }
  274. return isset($this->services[$id]);
  275. }
  276. /**
  277. * {@inheritdoc}
  278. */
  279. public function reset()
  280. {
  281. $services = $this->services + $this->privates;
  282. $this->services = $this->factories = $this->privates = [];
  283. foreach ($services as $service) {
  284. try {
  285. if ($service instanceof ResetInterface) {
  286. $service->reset();
  287. }
  288. } catch (\Throwable $e) {
  289. continue;
  290. }
  291. }
  292. }
  293. /**
  294. * Gets all service ids.
  295. *
  296. * @return string[] An array of all defined service ids
  297. */
  298. public function getServiceIds()
  299. {
  300. 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))));
  301. }
  302. /**
  303. * Gets service ids that existed at compile time.
  304. *
  305. * @return array
  306. */
  307. public function getRemovedIds()
  308. {
  309. return [];
  310. }
  311. /**
  312. * Camelizes a string.
  313. *
  314. * @param string $id A string to camelize
  315. *
  316. * @return string The camelized string
  317. */
  318. public static function camelize($id)
  319. {
  320. return strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']);
  321. }
  322. /**
  323. * A string to underscore.
  324. *
  325. * @param string $id The string to underscore
  326. *
  327. * @return string The underscored string
  328. */
  329. public static function underscore($id)
  330. {
  331. return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], str_replace('_', '.', $id)));
  332. }
  333. /**
  334. * Creates a service by requiring its factory file.
  335. */
  336. protected function load($file)
  337. {
  338. return require $file;
  339. }
  340. /**
  341. * Fetches a variable from the environment.
  342. *
  343. * @param string $name The name of the environment variable
  344. *
  345. * @return mixed The value to use for the provided environment variable name
  346. *
  347. * @throws EnvNotFoundException When the environment variable is not found and has no default value
  348. */
  349. protected function getEnv($name)
  350. {
  351. if (isset($this->resolving[$envName = "env($name)"])) {
  352. throw new ParameterCircularReferenceException(array_keys($this->resolving));
  353. }
  354. if (isset($this->envCache[$name]) || \array_key_exists($name, $this->envCache)) {
  355. return $this->envCache[$name];
  356. }
  357. if (!$this->has($id = 'container.env_var_processors_locator')) {
  358. $this->set($id, new ServiceLocator([]));
  359. }
  360. if (!$this->getEnv) {
  361. $this->getEnv = new \ReflectionMethod($this, __FUNCTION__);
  362. $this->getEnv->setAccessible(true);
  363. $this->getEnv = $this->getEnv->getClosure($this);
  364. }
  365. $processors = $this->get($id);
  366. if (false !== $i = strpos($name, ':')) {
  367. $prefix = substr($name, 0, $i);
  368. $localName = substr($name, 1 + $i);
  369. } else {
  370. $prefix = 'string';
  371. $localName = $name;
  372. }
  373. $processor = $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  374. $this->resolving[$envName] = true;
  375. try {
  376. return $this->envCache[$name] = $processor->getEnv($prefix, $localName, $this->getEnv);
  377. } finally {
  378. unset($this->resolving[$envName]);
  379. }
  380. }
  381. /**
  382. * @param string|false $registry
  383. * @param string|bool $load
  384. *
  385. * @return mixed
  386. *
  387. * @internal
  388. */
  389. final protected function getService($registry, string $id, ?string $method, $load)
  390. {
  391. if ('service_container' === $id) {
  392. return $this;
  393. }
  394. if (\is_string($load)) {
  395. throw new RuntimeException($load);
  396. }
  397. if (null === $method) {
  398. return false !== $registry ? $this->{$registry}[$id] ?? null : null;
  399. }
  400. if (false !== $registry) {
  401. return $this->{$registry}[$id] ?? $this->{$registry}[$id] = $load ? $this->load($method) : $this->{$method}();
  402. }
  403. if (!$load) {
  404. return $this->{$method}();
  405. }
  406. return ($factory = $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory() : $this->load($method);
  407. }
  408. private function __clone()
  409. {
  410. }
  411. }