Macro.php 1.2 KB

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