StudentService.php 2.5 KB

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