BoundMethod.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. namespace Illuminate\Container;
  3. use Closure;
  4. use Illuminate\Contracts\Container\BindingResolutionException;
  5. use InvalidArgumentException;
  6. use ReflectionFunction;
  7. use ReflectionMethod;
  8. class BoundMethod
  9. {
  10. /**
  11. * Call the given Closure / class@method and inject its dependencies.
  12. *
  13. * @param \Illuminate\Container\Container $container
  14. * @param callable|string $callback
  15. * @param array $parameters
  16. * @param string|null $defaultMethod
  17. * @return mixed
  18. *
  19. * @throws \ReflectionException
  20. * @throws \InvalidArgumentException
  21. */
  22. public static function call($container, $callback, array $parameters = [], $defaultMethod = null)
  23. {
  24. if (is_string($callback) && ! $defaultMethod && method_exists($callback, '__invoke')) {
  25. $defaultMethod = '__invoke';
  26. }
  27. if (static::isCallableWithAtSign($callback) || $defaultMethod) {
  28. return static::callClass($container, $callback, $parameters, $defaultMethod);
  29. }
  30. return static::callBoundMethod($container, $callback, function () use ($container, $callback, $parameters) {
  31. return $callback(...array_values(static::getMethodDependencies($container, $callback, $parameters)));
  32. });
  33. }
  34. /**
  35. * Call a string reference to a class using Class@method syntax.
  36. *
  37. * @param \Illuminate\Container\Container $container
  38. * @param string $target
  39. * @param array $parameters
  40. * @param string|null $defaultMethod
  41. * @return mixed
  42. *
  43. * @throws \InvalidArgumentException
  44. */
  45. protected static function callClass($container, $target, array $parameters = [], $defaultMethod = null)
  46. {
  47. $segments = explode('@', $target);
  48. // We will assume an @ sign is used to delimit the class name from the method
  49. // name. We will split on this @ sign and then build a callable array that
  50. // we can pass right back into the "call" method for dependency binding.
  51. $method = count($segments) === 2
  52. ? $segments[1] : $defaultMethod;
  53. if (is_null($method)) {
  54. throw new InvalidArgumentException('Method not provided.');
  55. }
  56. return static::call(
  57. $container, [$container->make($segments[0]), $method], $parameters
  58. );
  59. }
  60. /**
  61. * Call a method that has been bound to the container.
  62. *
  63. * @param \Illuminate\Container\Container $container
  64. * @param callable $callback
  65. * @param mixed $default
  66. * @return mixed
  67. */
  68. protected static function callBoundMethod($container, $callback, $default)
  69. {
  70. if (! is_array($callback)) {
  71. return Util::unwrapIfClosure($default);
  72. }
  73. // Here we need to turn the array callable into a Class@method string we can use to
  74. // examine the container and see if there are any method bindings for this given
  75. // method. If there are, we can call this method binding callback immediately.
  76. $method = static::normalizeMethod($callback);
  77. if ($container->hasMethodBinding($method)) {
  78. return $container->callMethodBinding($method, $callback[0]);
  79. }
  80. return Util::unwrapIfClosure($default);
  81. }
  82. /**
  83. * Normalize the given callback into a Class@method string.
  84. *
  85. * @param callable $callback
  86. * @return string
  87. */
  88. protected static function normalizeMethod($callback)
  89. {
  90. $class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]);
  91. return "{$class}@{$callback[1]}";
  92. }
  93. /**
  94. * Get all dependencies for a given method.
  95. *
  96. * @param \Illuminate\Container\Container $container
  97. * @param callable|string $callback
  98. * @param array $parameters
  99. * @return array
  100. *
  101. * @throws \ReflectionException
  102. */
  103. protected static function getMethodDependencies($container, $callback, array $parameters = [])
  104. {
  105. $dependencies = [];
  106. foreach (static::getCallReflector($callback)->getParameters() as $parameter) {
  107. static::addDependencyForCallParameter($container, $parameter, $parameters, $dependencies);
  108. }
  109. return array_merge($dependencies, array_values($parameters));
  110. }
  111. /**
  112. * Get the proper reflection instance for the given callback.
  113. *
  114. * @param callable|string $callback
  115. * @return \ReflectionFunctionAbstract
  116. *
  117. * @throws \ReflectionException
  118. */
  119. protected static function getCallReflector($callback)
  120. {
  121. if (is_string($callback) && str_contains($callback, '::')) {
  122. $callback = explode('::', $callback);
  123. } elseif (is_object($callback) && ! $callback instanceof Closure) {
  124. $callback = [$callback, '__invoke'];
  125. }
  126. return is_array($callback)
  127. ? new ReflectionMethod($callback[0], $callback[1])
  128. : new ReflectionFunction($callback);
  129. }
  130. /**
  131. * Get the dependency for the given call parameter.
  132. *
  133. * @param \Illuminate\Container\Container $container
  134. * @param \ReflectionParameter $parameter
  135. * @param array $parameters
  136. * @param array $dependencies
  137. * @return void
  138. *
  139. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  140. */
  141. protected static function addDependencyForCallParameter($container, $parameter,
  142. array &$parameters, &$dependencies)
  143. {
  144. if (array_key_exists($paramName = $parameter->getName(), $parameters)) {
  145. $dependencies[] = $parameters[$paramName];
  146. unset($parameters[$paramName]);
  147. } elseif (! is_null($className = Util::getParameterClassName($parameter))) {
  148. if (array_key_exists($className, $parameters)) {
  149. $dependencies[] = $parameters[$className];
  150. unset($parameters[$className]);
  151. } elseif ($parameter->isVariadic()) {
  152. $variadicDependencies = $container->make($className);
  153. $dependencies = array_merge($dependencies, is_array($variadicDependencies)
  154. ? $variadicDependencies
  155. : [$variadicDependencies]);
  156. } else {
  157. $dependencies[] = $container->make($className);
  158. }
  159. } elseif ($parameter->isDefaultValueAvailable()) {
  160. $dependencies[] = $parameter->getDefaultValue();
  161. } elseif (! $parameter->isOptional() && ! array_key_exists($paramName, $parameters)) {
  162. $message = "Unable to resolve dependency [{$parameter}] in class {$parameter->getDeclaringClass()->getName()}";
  163. throw new BindingResolutionException($message);
  164. }
  165. }
  166. /**
  167. * Determine if the given string is in Class@method syntax.
  168. *
  169. * @param mixed $callback
  170. * @return bool
  171. */
  172. protected static function isCallableWithAtSign($callback)
  173. {
  174. return is_string($callback) && str_contains($callback, '@');
  175. }
  176. }