ForwardsCalls.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. return $result === $object ? $this : $result;
  47. }
  48. /**
  49. * Throw a bad method call exception for the given method.
  50. *
  51. * @param string $method
  52. * @return void
  53. *
  54. * @throws \BadMethodCallException
  55. */
  56. protected static function throwBadMethodCallException($method)
  57. {
  58. throw new BadMethodCallException(sprintf(
  59. 'Call to undefined method %s::%s()', static::class, $method
  60. ));
  61. }
  62. }