| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace App\Module\Push\Hooks;
- use App\Module\Notification\Contracts\NotificationHookInterface;
- use App\Module\Notification\Enums\NOTIFICATION_CHANNEL;
- use App\Module\Push\Services\PushService;
- use Illuminate\Support\Facades\Log;
- class PushNotificationHook implements NotificationHookInterface
- {
- protected $pushService;
- public function __construct(PushService $pushService)
- {
- $this->pushService = $pushService;
- }
- /**
- * 发送前钩子
- *
- * @param array $data
- * @return array
- */
- public function beforeSend(array $data): array
- {
- // 检查是否包含推送渠道
- if (!in_array(NOTIFICATION_CHANNEL::PUSH, $data['channels'])) {
- return $data;
- }
- // 检查用户设备令牌
- if (empty($data['user']['device_token'])) {
- Log::warning('用户设备令牌为空,跳过推送发送', [
- 'user_id' => $data['user_id']
- ]);
- $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::PUSH]);
- return $data;
- }
- // 检查推送模板
- if (empty($data['template']['push_template_id'])) {
- Log::warning('推送模板ID为空,跳过推送发送', [
- 'template_id' => $data['template_id']
- ]);
- $data['channels'] = array_diff($data['channels'], [NOTIFICATION_CHANNEL::PUSH]);
- 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::PUSH, $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::PUSH, $data['channels'])) {
- return;
- }
- Log::error('推送发送失败', [
- 'user_id' => $data['user_id'],
- 'error' => $exception->getMessage()
- ]);
- }
- }
|