StudentService.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Student;
  4. use App\Models\User;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Http\UploadedFile;
  7. use Illuminate\Support\Facades\Storage;
  8. class StudentService
  9. {
  10. public function getAll(User $user): Collection
  11. {
  12. $unitId = $this->resolveUnitId($user);
  13. return Student::where('unit_id', $unitId)
  14. ->orderBy('created_at', 'desc')
  15. ->get();
  16. }
  17. public function findById(int $id): ?Student
  18. {
  19. return Student::find($id);
  20. }
  21. public function create(User $user, array $data): Student
  22. {
  23. $unitId = $this->resolveUnitId($user);
  24. $data = $this->handlePhoto($data);
  25. return Student::create(array_merge($data, ['unit_id' => $unitId]));
  26. }
  27. public function update(int $id, array $data): ?Student
  28. {
  29. $model = $this->findById($id);
  30. if (!$model) {
  31. return null;
  32. }
  33. $data = $this->handlePhoto($data, $model->photo_url);
  34. $model->update($data);
  35. return $model->fresh();
  36. }
  37. public function delete(int $id): bool
  38. {
  39. $model = $this->findById($id);
  40. if (!$model) {
  41. return false;
  42. }
  43. if ($model->photo_url) {
  44. Storage::delete($model->photo_url);
  45. }
  46. return $model->delete();
  47. }
  48. private function handlePhoto(array $data, ?string $oldPhotoPath = null): array
  49. {
  50. if (!isset($data['avatar'])) {
  51. return $data;
  52. }
  53. if ($data['avatar'] instanceof UploadedFile) {
  54. if ($oldPhotoPath) {
  55. Storage::delete($oldPhotoPath);
  56. }
  57. $data['photo_url'] = $data['avatar']->store('students/photos');
  58. } elseif (is_null($data['avatar'])) {
  59. if ($oldPhotoPath) {
  60. Storage::delete($oldPhotoPath);
  61. }
  62. $data['photo_url'] = null;
  63. }
  64. unset($data['avatar']);
  65. return $data;
  66. }
  67. private function resolveUnitId(User $user): int
  68. {
  69. $unit = $user->units()->first();
  70. abort_if(!$unit, 403, 'Usuário sem unidade associada.');
  71. return $unit->id;
  72. }
  73. }