EnterService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Services\Goodnight;
  3. use App\Exceptions\AlertException;
  4. use App\Models\Goodnight\ActivityModel;
  5. use App\Models\Goodnight\EnterModel;
  6. class EnterService
  7. {
  8. private $type;
  9. private $uid;
  10. /**
  11. * 报名
  12. * @param $uid
  13. * @param $type
  14. * @return mixed
  15. * @throws AlertException
  16. */
  17. public function enter($uid, $type)
  18. {
  19. $activity = $this->getActivity("报名");
  20. if ($this->repeatedly($type, $uid, $activity->id)) {
  21. throw new AlertException("不可重复报名", 101);
  22. }
  23. $enter = $this->createEnter($type, $uid, $activity->id);
  24. return $enter;
  25. }
  26. /**
  27. * 获取当前可报名的活动
  28. * @return mixed
  29. */
  30. public function getActivity($type = '报名')
  31. {
  32. switch ($type) {
  33. case "报名":
  34. $activity = ActivityModel::where([
  35. ['opened_at', '<', time()],
  36. ['closed_at', '>', time()],
  37. ])->firstOrFail();
  38. break;
  39. case "邀请":
  40. $activity = ActivityModel::whereRaw(
  41. "from_unixtime(`showed_at`, '%Y-%m-%d') = ?",
  42. [
  43. date('Y-m-d'),
  44. ]
  45. )->firstOrFail();
  46. break;
  47. case "匹配":
  48. $activity = ActivityModel::where([
  49. ['closed_at', '<', time()],
  50. ['showed_at', '>', time()],
  51. ])->firstOrFail();
  52. break;
  53. }
  54. return $activity;
  55. }
  56. /**
  57. * 是否重复报名
  58. * @param $type
  59. * @param $uid
  60. * @param $activity_id
  61. * @return bool
  62. */
  63. private function repeatedly($type, $uid, $activity_id)
  64. {
  65. switch ($type) {
  66. case "报名":
  67. return EnterModel::where("uid", $uid)
  68. ->where("type", $type)
  69. ->where("activity_id", $activity_id)
  70. ->first() ? true : false;
  71. break;
  72. case "邀请":
  73. return false;
  74. }
  75. }
  76. /**
  77. * 插入报名列表
  78. * @param $type
  79. * @param $uid
  80. * @param $activity_id
  81. * @return mixed
  82. */
  83. public function createEnter($type, $uid, $activity_id)
  84. {
  85. $enter = EnterModel::create([
  86. 'type' => $type,
  87. 'activity_id' => $activity_id,
  88. 'uid' => $uid,
  89. ]);
  90. return $enter;
  91. }
  92. }