ForwardsCalls.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Illuminate\Support\Traits;
  3. use BadMethodCallException;
  4. use Error;
  5. trait ForwardsCalls
  6. {
  7. /**
  8. * Forward a method call to the given object.
  9. *
  10. * @param mixed $object
  11. * @param string $method
  12. * @param array $parameters
  13. * @return mixed
  14. *
  15. * @throws \BadMethodCallException
  16. */
  17. protected function forwardCallTo($object, $method, $parameters)
  18. {
  19. try {
  20. return $object->{$method}(...$parameters);
  21. } catch (Error|BadMethodCallException $e) {
  22. $pattern = '~^Call to undefined method (?P<class>[^:]+)::(?P<method>[^\(]+)\(\)$~';
  23. if (! preg_match($pattern, $e->getMessage(), $matches)) {
  24. throw $e;
  25. }
  26. if ($matches['class'] != get_class($object) ||
  27. $matches['method'] != $method) {
  28. throw $e;
  29. }
  30. static::throwBadMethodCallException($method);
  31. }
  32. }
  33. /**
  34. * Forward a method call to the given object, returning $this if the forwarded call returned itself.
  35. *
  36. * @param mixed $object
  37. * @param string $method
  38. * @param array $parameters
  39. * @return mixed
  40. *
  41. * @throws \BadMethodCallException
  42. */
  43. protected function forwardDecoratedCallTo($object, $method, $parameters)
  44. {
  45. $result = $this->forwardCallTo($object, $method, $parameters);
  46. if ($result === $object) {
  47. return $this;
  48. }
  49. return $result;
  50. }
  51. /**
  52. * Throw a bad method call exception for the given method.
  53. *
  54. * @param string $method
  55. * @return void
  56. *
  57. * @throws \BadMethodCallException
  58. */
  59. protected static function throwBadMethodCallException($method)
  60. {
  61. throw new BadMethodCallException(sprintf(
  62. 'Call to undefined method %s::%s()', static::class, $method
  63. ));
  64. }
  65. }