HookManager.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Module\Notification\Services;
  3. use App\Module\Notification\Contracts\NotificationHookInterface;
  4. use Illuminate\Support\Collection;
  5. class HookManager
  6. {
  7. protected Collection $hooks;
  8. public function __construct()
  9. {
  10. $this->hooks = collect();
  11. }
  12. /**
  13. * 注册Hook
  14. *
  15. * @param NotificationHookInterface $hook
  16. * @return void
  17. */
  18. public function register(NotificationHookInterface $hook): void
  19. {
  20. $this->hooks->push($hook);
  21. }
  22. /**
  23. * 执行发送前钩子
  24. *
  25. * @param array $data
  26. * @return array
  27. */
  28. public function executeBeforeSend(array $data): array
  29. {
  30. foreach ($this->hooks as $hook) {
  31. $data = $hook->beforeSend($data);
  32. }
  33. return $data;
  34. }
  35. /**
  36. * 执行发送后钩子
  37. *
  38. * @param array $data
  39. * @param bool $result
  40. * @return void
  41. */
  42. public function executeAfterSend(array $data, bool $result): void
  43. {
  44. foreach ($this->hooks as $hook) {
  45. $hook->afterSend($data, $result);
  46. }
  47. }
  48. /**
  49. * 执行错误钩子
  50. *
  51. * @param array $data
  52. * @param \Exception $exception
  53. * @return void
  54. */
  55. public function executeOnError(array $data, \Exception $exception): void
  56. {
  57. foreach ($this->hooks as $hook) {
  58. $hook->onError($data, $exception);
  59. }
  60. }
  61. }