MailNotificationHook.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Module\Mail\Hooks;
  3. use App\Module\Notification\Contracts\NotificationHookInterface;
  4. use App\Module\Notification\Enums\NOTIFICATION_CHANNEL;
  5. use App\Module\Mail\Services\MailService;
  6. use Illuminate\Support\Facades\Log;
  7. class MailNotificationHook implements NotificationHookInterface
  8. {
  9. protected $mailService;
  10. public function __construct(MailService $mailService)
  11. {
  12. $this->mailService = $mailService;
  13. }
  14. /**
  15. * 发送前钩子
  16. *
  17. * @param array $data
  18. * @return array
  19. */
  20. public function beforeSend(array $data): array
  21. {
  22. // 检查是否包含邮件渠道
  23. if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
  24. return $data;
  25. }
  26. // 检查用户邮箱
  27. if (empty($data['user']['email'])) {
  28. Log::warning('用户邮箱为空,跳过邮件发送', [
  29. 'user_id' => $data['user_id']
  30. ]);
  31. $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::MAIL]);
  32. return $data;
  33. }
  34. // 检查邮件模板
  35. if (empty($data['template']['mail_template_id'])) {
  36. Log::warning('邮件模板ID为空,跳过邮件发送', [
  37. 'template_id' => $data['template_id']
  38. ]);
  39. $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::MAIL]);
  40. return $data;
  41. }
  42. return $data;
  43. }
  44. /**
  45. * 发送后钩子
  46. *
  47. * @param array $data
  48. * @param bool $result
  49. * @return void
  50. */
  51. public function afterSend(array $data, bool $result): void
  52. {
  53. if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
  54. return;
  55. }
  56. // 记录邮件发送统计
  57. if ($result) {
  58. // TODO: 实现邮件发送统计
  59. }
  60. }
  61. /**
  62. * 发送失败钩子
  63. *
  64. * @param array $data
  65. * @param \Exception $exception
  66. * @return void
  67. */
  68. public function onError(array $data, \Exception $exception): void
  69. {
  70. if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
  71. return;
  72. }
  73. Log::error('邮件发送失败', [
  74. 'user_id' => $data['user_id'],
  75. 'error' => $exception->getMessage()
  76. ]);
  77. }
  78. }