Macro.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace ln\traits;
  3. use BadMethodCallException;
  4. use Closure;
  5. trait Macro
  6. {
  7. protected $macroList = [];
  8. /**
  9. * @param string $name
  10. * @param $macro
  11. * @author xaboy
  12. * @day 2020-04-10
  13. */
  14. public function macro(string $name, $macro)
  15. {
  16. $this->macroList[$name] = $macro;
  17. }
  18. /**
  19. * @param array $names
  20. * @param $macro
  21. * @author xaboy
  22. * @day 2020-04-10
  23. */
  24. public function macros(array $names, $macro)
  25. {
  26. foreach ($names as $name) {
  27. $this->macro($name, $macro);
  28. }
  29. }
  30. /**
  31. * @param string $name
  32. * @return bool
  33. * @author xaboy
  34. * @day 2020-04-10
  35. */
  36. public function hasMacro(string $name): bool
  37. {
  38. return isset($this->macroList[$name]);
  39. }
  40. public function __call($method, $parameters)
  41. {
  42. if (!$this->hasMacro($method)) {
  43. throw new BadMethodCallException("Method {$method} does not exist.");
  44. }
  45. $macro = $this->macroList[$method];
  46. if ($macro instanceof Closure) {
  47. return call_user_func_array($macro->bindTo($this, static::class), $parameters);
  48. }
  49. return call_user_func_array($macro, $parameters);
  50. }
  51. }