Macro.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\traits;
  12. use BadMethodCallException;
  13. use Closure;
  14. trait Macro
  15. {
  16. protected $macroList = [];
  17. /**
  18. * @param string $name
  19. * @param $macro
  20. * @author xaboy
  21. * @day 2020-04-10
  22. */
  23. public function macro(string $name, $macro)
  24. {
  25. $this->macroList[$name] = $macro;
  26. }
  27. /**
  28. * @param array $names
  29. * @param $macro
  30. * @author xaboy
  31. * @day 2020-04-10
  32. */
  33. public function macros(array $names, $macro)
  34. {
  35. foreach ($names as $name) {
  36. $this->macro($name, $macro);
  37. }
  38. }
  39. /**
  40. * @param string $name
  41. * @return bool
  42. * @author xaboy
  43. * @day 2020-04-10
  44. */
  45. public function hasMacro(string $name): bool
  46. {
  47. return isset($this->macroList[$name]);
  48. }
  49. public function __call($method, $parameters)
  50. {
  51. if (!$this->hasMacro($method)) {
  52. throw new BadMethodCallException("Method {$method} does not exist.");
  53. }
  54. $macro = $this->macroList[$method];
  55. if ($macro instanceof Closure) {
  56. return call_user_func_array($macro->bindTo($this, static::class), $parameters);
  57. }
  58. return call_user_func_array($macro, $parameters);
  59. }
  60. }