| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace App\Services;
- use App\Models\Media;
- use App\Models\User;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Storage;
- class MediaService
- {
- public function getAllBySource(string $source, int $sourceId): Collection
- {
- return Media::where('source', $source)
- ->where('source_id', $sourceId)
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?Media
- {
- return Media::find($id);
- }
- public function create(array $data): Media
- {
- $data['user_id'] = Auth::id();
- return Media::create($data);
- }
- public function upload(UploadedFile $file, string $source, int $sourceId, string $mediaType = 'imagem'): Media
- {
- $path = $file->store("media/{$source}/{$sourceId}", 's3');
- return $this->create([
- 'type' => $mediaType,
- 'source' => $source,
- 'source_id' => $sourceId,
- 'path' => $path,
- 'name' => $file->getClientOriginalName(),
- 'url' => null,
- ]);
- }
- public function uploadLogo(UploadedFile $file, int $sourceId): Media
- {
- Media::where('source', 'partner_agreement_logo')
- ->where('source_id', $sourceId)
- ->get()
- ->each(function (Media $m) {
- Storage::disk('s3')->delete($m->path);
- $m->forceDelete();
- });
- return $this->upload($file, 'partner_agreement_logo', $sourceId, 'imagem');
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- Storage::disk('s3')->delete($model->path);
- return $model->delete();
- }
- public function uploadUserAvatar(UploadedFile $file, User $user): string
- {
- if ($user->photo_path) {
- Storage::disk('s3')->delete($user->photo_path);
- }
- $path = $file->store("avatars/users/{$user->id}", 's3');
- $user->update(['photo_path' => $path]);
- return $path;
- }
- public function deleteUserAvatar(User $user): void
- {
- if ($user->photo_path) {
- Storage::disk('s3')->delete($user->photo_path);
- $user->update(['photo_path' => null]);
- }
- }
- }
|