Container.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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|null $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|null 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. $service = $this->services[$id]
  200. ?? $this->services[$id = $this->aliases[$id] ?? $id]
  201. ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? [$this, 'make'])($id, $invalidBehavior));
  202. if (!\is_object($service) && null !== $service) {
  203. @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);
  204. }
  205. return $service;
  206. }
  207. /**
  208. * Creates a service.
  209. *
  210. * As a separate method to allow "get()" to use the really fast `??` operator.
  211. */
  212. private function make(string $id, int $invalidBehavior)
  213. {
  214. if (isset($this->loading[$id])) {
  215. throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id]));
  216. }
  217. $this->loading[$id] = true;
  218. try {
  219. if (isset($this->fileMap[$id])) {
  220. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->load($this->fileMap[$id]);
  221. } elseif (isset($this->methodMap[$id])) {
  222. return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$this->methodMap[$id]}();
  223. }
  224. } catch (\Exception $e) {
  225. unset($this->services[$id]);
  226. throw $e;
  227. } finally {
  228. unset($this->loading[$id]);
  229. }
  230. if (/* self::EXCEPTION_ON_INVALID_REFERENCE */ 1 === $invalidBehavior) {
  231. if (!$id) {
  232. throw new ServiceNotFoundException($id);
  233. }
  234. if (isset($this->syntheticIds[$id])) {
  235. 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));
  236. }
  237. if (isset($this->getRemovedIds()[$id])) {
  238. 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));
  239. }
  240. $alternatives = [];
  241. foreach ($this->getServiceIds() as $knownId) {
  242. if ('' === $knownId || '.' === $knownId[0]) {
  243. continue;
  244. }
  245. $lev = levenshtein($id, $knownId);
  246. if ($lev <= \strlen($id) / 3 || false !== strpos($knownId, $id)) {
  247. $alternatives[] = $knownId;
  248. }
  249. }
  250. throw new ServiceNotFoundException($id, null, null, $alternatives);
  251. }
  252. return null;
  253. }
  254. /**
  255. * Returns true if the given service has actually been initialized.
  256. *
  257. * @param string $id The service identifier
  258. *
  259. * @return bool true if service has already been initialized, false otherwise
  260. */
  261. public function initialized($id)
  262. {
  263. if (isset($this->aliases[$id])) {
  264. $id = $this->aliases[$id];
  265. }
  266. if ('service_container' === $id) {
  267. return false;
  268. }
  269. return isset($this->services[$id]);
  270. }
  271. /**
  272. * {@inheritdoc}
  273. */
  274. public function reset()
  275. {
  276. $services = $this->services + $this->privates;
  277. $this->services = $this->factories = $this->privates = [];
  278. foreach ($services as $service) {
  279. try {
  280. if ($service instanceof ResetInterface) {
  281. $service->reset();
  282. }
  283. } catch (\Throwable $e) {
  284. continue;
  285. }
  286. }
  287. }
  288. /**
  289. * Gets all service ids.
  290. *
  291. * @return string[] An array of all defined service ids
  292. */
  293. public function getServiceIds()
  294. {
  295. 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))));
  296. }
  297. /**
  298. * Gets service ids that existed at compile time.
  299. *
  300. * @return array
  301. */
  302. public function getRemovedIds()
  303. {
  304. return [];
  305. }
  306. /**
  307. * Camelizes a string.
  308. *
  309. * @param string $id A string to camelize
  310. *
  311. * @return string The camelized string
  312. */
  313. public static function camelize($id)
  314. {
  315. return strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']);
  316. }
  317. /**
  318. * A string to underscore.
  319. *
  320. * @param string $id The string to underscore
  321. *
  322. * @return string The underscored string
  323. */
  324. public static function underscore($id)
  325. {
  326. return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], str_replace('_', '.', $id)));
  327. }
  328. /**
  329. * Creates a service by requiring its factory file.
  330. */
  331. protected function load($file)
  332. {
  333. return require $file;
  334. }
  335. /**
  336. * Fetches a variable from the environment.
  337. *
  338. * @param string $name The name of the environment variable
  339. *
  340. * @return mixed The value to use for the provided environment variable name
  341. *
  342. * @throws EnvNotFoundException When the environment variable is not found and has no default value
  343. */
  344. protected function getEnv($name)
  345. {
  346. if (isset($this->resolving[$envName = "env($name)"])) {
  347. throw new ParameterCircularReferenceException(array_keys($this->resolving));
  348. }
  349. if (isset($this->envCache[$name]) || \array_key_exists($name, $this->envCache)) {
  350. return $this->envCache[$name];
  351. }
  352. if (!$this->has($id = 'container.env_var_processors_locator')) {
  353. $this->set($id, new ServiceLocator([]));
  354. }
  355. if (!$this->getEnv) {
  356. $this->getEnv = new \ReflectionMethod($this, __FUNCTION__);
  357. $this->getEnv->setAccessible(true);
  358. $this->getEnv = $this->getEnv->getClosure($this);
  359. }
  360. $processors = $this->get($id);
  361. if (false !== $i = strpos($name, ':')) {
  362. $prefix = substr($name, 0, $i);
  363. $localName = substr($name, 1 + $i);
  364. } else {
  365. $prefix = 'string';
  366. $localName = $name;
  367. }
  368. $processor = $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  369. $this->resolving[$envName] = true;
  370. try {
  371. return $this->envCache[$name] = $processor->getEnv($prefix, $localName, $this->getEnv);
  372. } finally {
  373. unset($this->resolving[$envName]);
  374. }
  375. }
  376. /**
  377. * @param string|false $registry
  378. * @param string|bool $load
  379. *
  380. * @return mixed
  381. *
  382. * @internal
  383. */
  384. final protected function getService($registry, string $id, ?string $method, $load)
  385. {
  386. if ('service_container' === $id) {
  387. return $this;
  388. }
  389. if (\is_string($load)) {
  390. throw new RuntimeException($load);
  391. }
  392. if (null === $method) {
  393. return false !== $registry ? $this->{$registry}[$id] ?? null : null;
  394. }
  395. if (false !== $registry) {
  396. return $this->{$registry}[$id] ?? $this->{$registry}[$id] = $load ? $this->load($method) : $this->{$method}();
  397. }
  398. if (!$load) {
  399. return $this->{$method}();
  400. }
  401. return ($factory = $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory() : $this->load($method);
  402. }
  403. private function __clone()
  404. {
  405. }
  406. }