MediaService.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Media;
  4. use App\Models\User;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Http\UploadedFile;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Storage;
  9. class MediaService
  10. {
  11. public function getAllBySource(string $source, int $sourceId): Collection
  12. {
  13. return Media::where('source', $source)
  14. ->where('source_id', $sourceId)
  15. ->orderBy('created_at', 'desc')
  16. ->get();
  17. }
  18. public function findById(int $id): ?Media
  19. {
  20. return Media::find($id);
  21. }
  22. public function create(array $data): Media
  23. {
  24. $data['user_id'] = Auth::id();
  25. return Media::create($data);
  26. }
  27. public function upload(UploadedFile $file, string $source, int $sourceId, string $mediaType = 'imagem'): Media
  28. {
  29. $path = $file->store("media/{$source}/{$sourceId}", 's3');
  30. return $this->create([
  31. 'type' => $mediaType,
  32. 'source' => $source,
  33. 'source_id' => $sourceId,
  34. 'path' => $path,
  35. 'name' => $file->getClientOriginalName(),
  36. 'url' => null,
  37. ]);
  38. }
  39. public function uploadLogo(UploadedFile $file, int $sourceId): Media
  40. {
  41. Media::where('source', 'partner_agreement_logo')
  42. ->where('source_id', $sourceId)
  43. ->get()
  44. ->each(function (Media $m) {
  45. Storage::disk('s3')->delete($m->path);
  46. $m->forceDelete();
  47. });
  48. return $this->upload($file, 'partner_agreement_logo', $sourceId, 'imagem');
  49. }
  50. public function delete(int $id): bool
  51. {
  52. $model = $this->findById($id);
  53. if (!$model) {
  54. return false;
  55. }
  56. Storage::disk('s3')->delete($model->path);
  57. return $model->delete();
  58. }
  59. public function uploadUserAvatar(UploadedFile $file, User $user): string
  60. {
  61. if ($user->photo_path) {
  62. Storage::disk('s3')->delete($user->photo_path);
  63. }
  64. $path = $file->store("avatars/users/{$user->id}", 's3');
  65. $user->update(['photo_path' => $path]);
  66. return $path;
  67. }
  68. public function deleteUserAvatar(User $user): void
  69. {
  70. if ($user->photo_path) {
  71. Storage::disk('s3')->delete($user->photo_path);
  72. $user->update(['photo_path' => null]);
  73. }
  74. }
  75. }