Просмотр файла app/Repositories/StoryRepository.php

Размер файла: 2.48Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Repositories;
  6.  
  7. use App\Models\Story;
  8. use App\Models\Tag;
  9. use MotorORM\Collection;
  10. use MotorORM\CollectionPaginate;
  11.  
  12. class StoryRepository implements RepositoryInterface
  13. {
  14. /**
  15. * Get by id
  16. *
  17. * @param int $id
  18. *
  19. * @return Story|null
  20. */
  21. public function getById(int $id): ?Story
  22. {
  23. return Story::query()->find($id);
  24. }
  25.  
  26. /**
  27. * Get by slug
  28. *
  29. * @param string $slug
  30. *
  31. * @return Story|null
  32. */
  33. public function getBySlug(string $slug): ?Story
  34. {
  35. $data = explode('-', $slug);
  36.  
  37. return Story::query()->find(end($data));
  38. }
  39.  
  40. /**
  41. * Get stories
  42. *
  43. * @param int $perPage
  44. *
  45. * @return CollectionPaginate<Story>
  46. */
  47. public function getStories(int $perPage): CollectionPaginate
  48. {
  49. return Story::query()
  50. ->orderByDesc('locked')
  51. ->orderByDesc('created_at')
  52. ->with(['user', 'poll', 'comments', 'favorite', 'favorites'])
  53. ->paginate($perPage);
  54. }
  55.  
  56. /**
  57. * Get user stories
  58. *
  59. * @param int $userId
  60. * @param int $perPage
  61. *
  62. * @return CollectionPaginate
  63. */
  64. public function getStoriesByUserId(int $userId, int $perPage): CollectionPaginate
  65. {
  66. return Story::query()
  67. ->where('user_id', $userId)
  68. ->orderByDesc('locked')
  69. ->orderByDesc('created_at')
  70. ->with(['user', 'poll', 'comments', 'favorite', 'favorites'])
  71. ->paginate($perPage);
  72. }
  73.  
  74. /**
  75. * Get stories by tag
  76. *
  77. * @param string $tag
  78. * @param int $perPage
  79. *
  80. * @return CollectionPaginate<Story>
  81. */
  82. public function getStoriesByTag(string $tag, int $perPage): CollectionPaginate
  83. {
  84. $tags = Tag::query()
  85. ->where('tag', 'like', $tag)
  86. ->get()
  87. ->pluck('story_id');
  88.  
  89. return Story::query()
  90. ->whereIn('id', $tags)
  91. ->orderByDesc('created_at')
  92. ->paginate($perPage);
  93. }
  94.  
  95. /**
  96. * Get stories by search
  97. *
  98. * @param string $search
  99. * @param int $perPage
  100. *
  101. * @return CollectionPaginate<Story>
  102. */
  103. public function getStoriesBySearch(string $search, int $perPage): CollectionPaginate
  104. {
  105. return Story::query()
  106. ->where('text', 'like', $search)
  107. ->orderByDesc('created_at')
  108. ->paginate($perPage)
  109. ->appends(['search' => $search]);
  110. }
  111. }