ForwardsCalls.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Support\Traits;
  12. use BadMethodCallException;
  13. use Error;
  14. use function get_class;
  15. trait ForwardsCalls
  16. {
  17. /**
  18. * Forward a method call to the given object.
  19. *
  20. * @param mixed $object
  21. * @throws Error
  22. */
  23. protected function forwardCallTo($object, string $method, array $parameters)
  24. {
  25. try {
  26. return $object->{$method}(...$parameters);
  27. } catch (BadMethodCallException|Error $e) {
  28. $pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\(]+)\(\)$~';
  29. if (! preg_match($pattern, $e->getMessage(), $matches)) {
  30. throw $e;
  31. }
  32. if ($matches['class'] !== get_class($object) || $matches['method'] !== $method) {
  33. throw $e;
  34. }
  35. static::throwBadMethodCallException($method);
  36. }
  37. }
  38. /**
  39. * Throw a bad method call exception for the given method.
  40. * @throws BadMethodCallException
  41. */
  42. protected static function throwBadMethodCallException(string $method): void
  43. {
  44. throw new BadMethodCallException(sprintf('Call to undefined method %s::%s()', static::class, $method));
  45. }
  46. }