Macro.php 1.3 KB

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