EventService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Event;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Http\UploadedFile;
  6. use Illuminate\Support\Facades\Storage;
  7. class EventService
  8. {
  9. public function __construct(protected MediaService $mediaService) {}
  10. public function getAll(): Collection
  11. {
  12. return Event::with('media')->orderBy('order')->orderBy('id')->get();
  13. }
  14. public function findById(int $id): ?Event
  15. {
  16. return Event::with('media')->find($id);
  17. }
  18. public function create(array $data): Event
  19. {
  20. if (!isset($data['order'])) {
  21. $data['order'] = Event::max('order') + 1;
  22. }
  23. $event = Event::create($data);
  24. return $event->load('media');
  25. }
  26. public function update(int $id, array $data): ?Event
  27. {
  28. $model = Event::find($id);
  29. if (!$model) {
  30. return null;
  31. }
  32. $model->update($data);
  33. return $model->fresh('media');
  34. }
  35. public function reorder(array $items): void
  36. {
  37. foreach ($items as $item) {
  38. Event::where('id', $item['id'])->update(['order' => $item['order']]);
  39. }
  40. }
  41. public function delete(int $id): bool
  42. {
  43. $model = Event::find($id);
  44. if (!$model) {
  45. return false;
  46. }
  47. if ($model->cover_path) {
  48. Storage::disk('s3')->delete($model->cover_path);
  49. }
  50. $model->media->each(fn($media) => $this->mediaService->delete($media->id));
  51. return $model->delete();
  52. }
  53. public function uploadCover(int $id, UploadedFile $file): ?Event
  54. {
  55. $model = Event::find($id);
  56. if (!$model) {
  57. return null;
  58. }
  59. if ($model->cover_path) {
  60. Storage::disk('s3')->delete($model->cover_path);
  61. }
  62. $model->cover_path = $file->store("events/{$id}/cover", 's3');
  63. $model->save();
  64. return $model->fresh('media');
  65. }
  66. public function removeCover(int $id): ?Event
  67. {
  68. $model = Event::find($id);
  69. if (!$model) {
  70. return null;
  71. }
  72. if ($model->cover_path) {
  73. Storage::disk('s3')->delete($model->cover_path);
  74. $model->cover_path = null;
  75. $model->save();
  76. }
  77. return $model->fresh('media');
  78. }
  79. }