AutowirePass.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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\Compiler;
  11. use Symfony\Component\DependencyInjection\ContainerBuilder;
  12. use Symfony\Component\DependencyInjection\Definition;
  13. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. /**
  16. * Guesses constructor arguments of services definitions and try to instantiate services if necessary.
  17. *
  18. * @author Kévin Dunglas <dunglas@gmail.com>
  19. */
  20. class AutowirePass implements CompilerPassInterface
  21. {
  22. private $container;
  23. private $reflectionClasses = array();
  24. private $definedTypes = array();
  25. private $types;
  26. private $notGuessableTypes = array();
  27. private $autowired = array();
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function process(ContainerBuilder $container)
  32. {
  33. $throwingAutoloader = function ($class) { throw new \ReflectionException(sprintf('Class %s does not exist', $class)); };
  34. spl_autoload_register($throwingAutoloader);
  35. try {
  36. $this->container = $container;
  37. foreach ($container->getDefinitions() as $id => $definition) {
  38. if ($definition->isAutowired()) {
  39. $this->completeDefinition($id, $definition);
  40. }
  41. }
  42. } catch (\Exception $e) {
  43. } catch (\Throwable $e) {
  44. }
  45. spl_autoload_unregister($throwingAutoloader);
  46. // Free memory and remove circular reference to container
  47. $this->container = null;
  48. $this->reflectionClasses = array();
  49. $this->definedTypes = array();
  50. $this->types = null;
  51. $this->notGuessableTypes = array();
  52. $this->autowired = array();
  53. if (isset($e)) {
  54. throw $e;
  55. }
  56. }
  57. /**
  58. * Wires the given definition.
  59. *
  60. * @param string $id
  61. * @param Definition $definition
  62. *
  63. * @throws RuntimeException
  64. */
  65. private function completeDefinition($id, Definition $definition)
  66. {
  67. if ($definition->getFactory() || $definition->getFactoryClass(false) || $definition->getFactoryService(false)) {
  68. throw new RuntimeException(sprintf('Service "%s" can use either autowiring or a factory, not both.', $id));
  69. }
  70. if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
  71. return;
  72. }
  73. $this->container->addClassResource($reflectionClass);
  74. if (!$constructor = $reflectionClass->getConstructor()) {
  75. return;
  76. }
  77. $parameters = $constructor->getParameters();
  78. if (method_exists('ReflectionMethod', 'isVariadic') && $constructor->isVariadic()) {
  79. array_pop($parameters);
  80. }
  81. $arguments = $definition->getArguments();
  82. foreach ($parameters as $index => $parameter) {
  83. if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
  84. continue;
  85. }
  86. try {
  87. if (!$typeHint = $parameter->getClass()) {
  88. if (isset($arguments[$index])) {
  89. continue;
  90. }
  91. // no default value? Then fail
  92. if (!$parameter->isOptional()) {
  93. throw new RuntimeException(sprintf('Unable to autowire argument index %d ($%s) for the service "%s". If this is an object, give it a type-hint. Otherwise, specify this argument\'s value explicitly.', $index, $parameter->name, $id));
  94. }
  95. // specifically pass the default value
  96. $arguments[$index] = $parameter->getDefaultValue();
  97. continue;
  98. }
  99. if (isset($this->autowired[$typeHint->name])) {
  100. $arguments[$index] = $this->autowired[$typeHint->name] ? new Reference($this->autowired[$typeHint->name]) : null;
  101. continue;
  102. }
  103. if (null === $this->types) {
  104. $this->populateAvailableTypes();
  105. }
  106. if (isset($this->types[$typeHint->name]) && !isset($this->notGuessableTypes[$typeHint->name])) {
  107. $value = new Reference($this->types[$typeHint->name]);
  108. } else {
  109. try {
  110. $value = $this->createAutowiredDefinition($typeHint, $id);
  111. } catch (RuntimeException $e) {
  112. if ($parameter->isDefaultValueAvailable()) {
  113. $value = $parameter->getDefaultValue();
  114. } elseif ($parameter->allowsNull()) {
  115. $value = null;
  116. } else {
  117. throw $e;
  118. }
  119. $this->autowired[$typeHint->name] = false;
  120. }
  121. }
  122. } catch (\ReflectionException $e) {
  123. // Typehint against a non-existing class
  124. if (!$parameter->isDefaultValueAvailable()) {
  125. throw new RuntimeException(sprintf('Cannot autowire argument %s for %s because the type-hinted class does not exist (%s).', $index + 1, $definition->getClass(), $e->getMessage()), 0, $e);
  126. }
  127. $value = $parameter->getDefaultValue();
  128. }
  129. $arguments[$index] = $value;
  130. }
  131. if ($parameters && !isset($arguments[++$index])) {
  132. while (0 <= --$index) {
  133. $parameter = $parameters[$index];
  134. if (!$parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== $arguments[$index]) {
  135. break;
  136. }
  137. unset($arguments[$index]);
  138. }
  139. }
  140. // it's possible index 1 was set, then index 0, then 2, etc
  141. // make sure that we re-order so they're injected as expected
  142. ksort($arguments);
  143. $definition->setArguments($arguments);
  144. }
  145. /**
  146. * Populates the list of available types.
  147. */
  148. private function populateAvailableTypes()
  149. {
  150. $this->types = array();
  151. foreach ($this->container->getDefinitions() as $id => $definition) {
  152. $this->populateAvailableType($id, $definition);
  153. }
  154. }
  155. /**
  156. * Populates the list of available types for a given definition.
  157. *
  158. * @param string $id
  159. * @param Definition $definition
  160. */
  161. private function populateAvailableType($id, Definition $definition)
  162. {
  163. // Never use abstract services
  164. if ($definition->isAbstract()) {
  165. return;
  166. }
  167. foreach ($definition->getAutowiringTypes() as $type) {
  168. $this->definedTypes[$type] = true;
  169. $this->types[$type] = $id;
  170. unset($this->notGuessableTypes[$type]);
  171. }
  172. if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
  173. return;
  174. }
  175. foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
  176. $this->set($reflectionInterface->name, $id);
  177. }
  178. do {
  179. $this->set($reflectionClass->name, $id);
  180. } while ($reflectionClass = $reflectionClass->getParentClass());
  181. }
  182. /**
  183. * Associates a type and a service id if applicable.
  184. *
  185. * @param string $type
  186. * @param string $id
  187. */
  188. private function set($type, $id)
  189. {
  190. if (isset($this->definedTypes[$type])) {
  191. return;
  192. }
  193. if (!isset($this->types[$type])) {
  194. $this->types[$type] = $id;
  195. return;
  196. }
  197. if ($this->types[$type] === $id) {
  198. return;
  199. }
  200. if (!isset($this->notGuessableTypes[$type])) {
  201. $this->notGuessableTypes[$type] = true;
  202. $this->types[$type] = (array) $this->types[$type];
  203. }
  204. $this->types[$type][] = $id;
  205. }
  206. /**
  207. * Registers a definition for the type if possible or throws an exception.
  208. *
  209. * @param \ReflectionClass $typeHint
  210. * @param string $id
  211. *
  212. * @return Reference A reference to the registered definition
  213. *
  214. * @throws RuntimeException
  215. */
  216. private function createAutowiredDefinition(\ReflectionClass $typeHint, $id)
  217. {
  218. if (isset($this->notGuessableTypes[$typeHint->name])) {
  219. $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
  220. $matchingServices = implode(', ', $this->types[$typeHint->name]);
  221. throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s". Multiple services exist for this %s (%s).', $typeHint->name, $id, $classOrInterface, $matchingServices));
  222. }
  223. if (!$typeHint->isInstantiable()) {
  224. $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
  225. throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.', $typeHint->name, $id, $classOrInterface));
  226. }
  227. $this->autowired[$typeHint->name] = $argumentId = sprintf('autowired.%s', $typeHint->name);
  228. $argumentDefinition = $this->container->register($argumentId, $typeHint->name);
  229. $argumentDefinition->setPublic(false);
  230. try {
  231. $this->completeDefinition($argumentId, $argumentDefinition);
  232. } catch (RuntimeException $e) {
  233. $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
  234. $message = sprintf('Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.', $typeHint->name, $id, $classOrInterface);
  235. throw new RuntimeException($message, 0, $e);
  236. }
  237. return new Reference($argumentId);
  238. }
  239. /**
  240. * Retrieves the reflection class associated with the given service.
  241. *
  242. * @param string $id
  243. * @param Definition $definition
  244. *
  245. * @return \ReflectionClass|false
  246. */
  247. private function getReflectionClass($id, Definition $definition)
  248. {
  249. if (isset($this->reflectionClasses[$id])) {
  250. return $this->reflectionClasses[$id];
  251. }
  252. // Cannot use reflection if the class isn't set
  253. if (!$class = $definition->getClass()) {
  254. return false;
  255. }
  256. $class = $this->container->getParameterBag()->resolveValue($class);
  257. if ($deprecated = $definition->isDeprecated()) {
  258. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  259. return (E_USER_DEPRECATED === $level || !$prevErrorHandler) ? false : $prevErrorHandler($level, $message, $file, $line);
  260. });
  261. }
  262. $e = null;
  263. try {
  264. $reflector = new \ReflectionClass($class);
  265. } catch (\Exception $e) {
  266. } catch (\Throwable $e) {
  267. }
  268. if ($deprecated) {
  269. restore_error_handler();
  270. }
  271. if (null !== $e) {
  272. if (!$e instanceof \ReflectionException) {
  273. throw $e;
  274. }
  275. $reflector = false;
  276. }
  277. return $this->reflectionClasses[$id] = $reflector;
  278. }
  279. }