HasBuilderEvents.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Dcat\Admin\Traits;
  3. use Dcat\Admin\Admin;
  4. trait HasBuilderEvents
  5. {
  6. public static function resolving(callable $callback, bool $once = false)
  7. {
  8. static::addBuilderListeners('builder:resolving', $callback, $once);
  9. }
  10. protected function callResolving(...$params)
  11. {
  12. $this->fireBuilderEvent('builder:resolving', ...$params);
  13. }
  14. public static function composing(callable $callback, bool $once = false)
  15. {
  16. static::addBuilderListeners('builder:composing', $callback, $once);
  17. }
  18. protected function callComposing(...$params)
  19. {
  20. $this->fireBuilderEvent('builder:composing', ...$params);
  21. }
  22. protected function fireBuilderEvent($key, ...$params)
  23. {
  24. $context = Admin::context();
  25. $key = static::formatEventKey($key);
  26. $listeners = $context->get($key) ?: [];
  27. foreach ($listeners as $k => $listener) {
  28. [$callback, $once] = $listener;
  29. if ($once) {
  30. unset($listeners[$k]);
  31. }
  32. call_user_func($callback, $this, ...$params);
  33. }
  34. $context[$key] = $listeners;
  35. }
  36. protected static function addBuilderListeners($key, $callback, $once)
  37. {
  38. $context = Admin::context();
  39. $key = static::formatEventKey($key);
  40. $listeners = $context->get($key) ?: [];
  41. $listeners[] = [$callback, $once];
  42. $context[$key] = $listeners;
  43. }
  44. protected static function formatEventKey($key)
  45. {
  46. return static::class.':'.$key;
  47. }
  48. }