Notification.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. <?php
  2. namespace App\Services\NoticeService;
  3. use App\Services\NoticeService\Channels\Channel;
  4. use Ramsey\Uuid\Uuid;
  5. class Notification
  6. {
  7. protected $title;
  8. protected $uuid;
  9. protected $to_uid;
  10. public function __construct($to_uid)
  11. {
  12. $this->to_uid = $to_uid;
  13. $this->uuid = Uuid::uuid4()->toString();
  14. }
  15. /**
  16. * 发送
  17. * @return bool
  18. */
  19. public function send()
  20. {
  21. if (!$this->subscribe()) {
  22. return false;
  23. }
  24. if (!$this->throttle()) {
  25. return false;
  26. }
  27. $channels = $this->via();
  28. foreach ($channels as $channel) {
  29. $channel->setUuid($this->uuid);
  30. $channel->setPath($this->getPagePath());
  31. if ($channel->send()) {
  32. $this->logger($channel);
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38. /**
  39. * 订阅开关
  40. * @return bool
  41. */
  42. protected function subscribe()
  43. {
  44. return true;
  45. }
  46. /**
  47. * 节流阀
  48. * @return bool
  49. */
  50. protected function throttle()
  51. {
  52. return true;
  53. }
  54. /**
  55. * 通知渠道
  56. * @return array
  57. */
  58. public function via(): array
  59. {
  60. return [];
  61. }
  62. /**
  63. * 跳转地址
  64. * @return string
  65. */
  66. protected function getPagePath()
  67. {
  68. return 'pages/index/index';
  69. }
  70. /**
  71. * 成功通知日志
  72. * @param Channel $channel
  73. * @return array
  74. */
  75. public function logger(Channel $channel)
  76. {
  77. $log = [
  78. 'uuid' => $this->uuid,
  79. 'title' => $this->title,
  80. 'uid' => $this->to_uid,
  81. 'notice_type' => $channel->getNoticeType(),
  82. 'template_id' => $channel->getTemplateId(),
  83. 'content' => $channel->getContent(),
  84. 'result' => true,
  85. 'page' => $this->getPagePath(),
  86. 'created_at' => time(),
  87. 'date' => date('Y-m-d'),
  88. ];
  89. if (app()->environment() == 'production') {
  90. \DB::connection('mysql_datalog')->table("notice_logs")->insert($log);
  91. }
  92. return $log;
  93. }
  94. /**
  95. * 失败日志
  96. * @param string $account
  97. */
  98. public function failLogger($account)
  99. {
  100. if (app()->environment() == 'production') {
  101. \DB::connection('mysql_datalog')->table("notice_logs")->insert([
  102. 'uuid' => $this->uuid,
  103. 'title' => $this->title,
  104. 'uid' => $this->to_uid,
  105. 'notice_type' => $account,
  106. 'content' => "",
  107. 'result' => false,
  108. 'created_at' => time(),
  109. 'date' => date('Y-m-d'),
  110. ]);
  111. }
  112. }
  113. }