PollService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Poll;
  4. use App\Models\PollVote;
  5. use App\Status;
  6. use Illuminate\Support\Facades\Cache;
  7. class PollService
  8. {
  9. const CACHE_KEY = 'pf:services:poll:status_id:';
  10. public static function get($id, $profileId = false)
  11. {
  12. $key = self::CACHE_KEY . $id;
  13. $res = Cache::remember($key, 1800, function() use($id) {
  14. $poll = Poll::whereStatusId($id)->firstOrFail();
  15. return [
  16. 'id' => (string) $poll->id,
  17. 'expires_at' => $poll->expires_at->format('c'),
  18. 'expired' => null,
  19. 'multiple' => $poll->multiple,
  20. 'votes_count' => $poll->votes_count,
  21. 'voters_count' => null,
  22. 'voted' => false,
  23. 'own_votes' => [],
  24. 'options' => collect($poll->poll_options)->map(function($option, $key) use($poll) {
  25. $tally = $poll->cached_tallies && isset($poll->cached_tallies[$key]) ? $poll->cached_tallies[$key] : 0;
  26. return [
  27. 'title' => $option,
  28. 'votes_count' => $tally
  29. ];
  30. })->toArray(),
  31. 'emojis' => []
  32. ];
  33. });
  34. if($profileId) {
  35. $res['voted'] = self::voted($id, $profileId);
  36. $res['own_votes'] = self::ownVotes($id, $profileId);
  37. }
  38. return $res;
  39. }
  40. public static function getById($id, $pid)
  41. {
  42. $poll = Poll::findOrFail($id);
  43. return self::get($poll->status_id, $pid);
  44. }
  45. public static function del($id)
  46. {
  47. Cache::forget(self::CACHE_KEY . $id);
  48. }
  49. public static function voted($id, $profileId = false)
  50. {
  51. return !$profileId ? false : PollVote::whereStatusId($id)
  52. ->whereProfileId($profileId)
  53. ->exists();
  54. }
  55. public static function votedStory($id, $profileId = false)
  56. {
  57. return !$profileId ? false : PollVote::whereStoryId($id)
  58. ->whereProfileId($profileId)
  59. ->exists();
  60. }
  61. public static function storyResults($sid)
  62. {
  63. $key = self::CACHE_KEY . 'story_poll_results:' . $sid;
  64. return Cache::remember($key, 60, function() use($sid) {
  65. return Poll::whereStoryId($sid)
  66. ->firstOrFail()
  67. ->cached_tallies;
  68. });
  69. }
  70. public static function storyChoice($id, $profileId = false)
  71. {
  72. return !$profileId ? false : PollVote::whereStoryId($id)
  73. ->whereProfileId($profileId)
  74. ->pluck('choice')
  75. ->first();
  76. }
  77. public static function ownVotes($id, $profileId = false)
  78. {
  79. return !$profileId ? [] : PollVote::whereStatusId($id)
  80. ->whereProfileId($profileId)
  81. ->pluck('choice') ?? [];
  82. }
  83. }