Container.php 15 KB

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