| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace App\Module\Mail\Hooks;
- use App\Module\Notification\Contracts\NotificationHookInterface;
- use App\Module\Notification\Enums\NOTIFICATION_CHANNEL;
- use App\Module\Mail\Services\MailService;
- use Illuminate\Support\Facades\Log;
- class MailNotificationHook implements NotificationHookInterface
- {
- protected $mailService;
- public function __construct(MailService $mailService)
- {
- $this->mailService = $mailService;
- }
- /**
- * 发送前钩子
- *
- * @param array $data
- * @return array
- */
- public function beforeSend(array $data): array
- {
- // 检查是否包含邮件渠道
- if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
- return $data;
- }
- // 检查用户邮箱
- if (empty($data['user']['email'])) {
- Log::warning('用户邮箱为空,跳过邮件发送', [
- 'user_id' => $data['user_id']
- ]);
- $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::MAIL]);
- return $data;
- }
- // 检查邮件模板
- if (empty($data['template']['mail_template_id'])) {
- Log::warning('邮件模板ID为空,跳过邮件发送', [
- 'template_id' => $data['template_id']
- ]);
- $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::MAIL]);
- return $data;
- }
- return $data;
- }
- /**
- * 发送后钩子
- *
- * @param array $data
- * @param bool $result
- * @return void
- */
- public function afterSend(array $data, bool $result): void
- {
- if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
- return;
- }
- // 记录邮件发送统计
- if ($result) {
- // TODO: 实现邮件发送统计
- }
- }
- /**
- * 发送失败钩子
- *
- * @param array $data
- * @param \Exception $exception
- * @return void
- */
- public function onError(array $data, \Exception $exception): void
- {
- if (!in_array(NOTIFICATION_CHANNEL::MAIL, $data['channels'])) {
- return;
- }
- Log::error('邮件发送失败', [
- 'user_id' => $data['user_id'],
- 'error' => $exception->getMessage()
- ]);
- }
- }
|