requestStack->getCurrentRequest(); $file = $request?->files->get('file'); if (null === $file) { throw new BadRequestHttpException('No file uploaded.'); } if ('application/pdf' !== $file->getMimeType()) { throw new BadRequestHttpException('Only PDF files are accepted.'); } $startDate = $data->getStartDate(); $year = $startDate?->format('Y') ?? date('Y'); $monthNumber = $startDate?->format('m') ?? date('m'); $relativePath = sprintf('formations/%s/%s', $year, $monthNumber); $absoluteDir = sprintf('%s/%s', $this->uploadDir, $relativePath); if (!is_dir($absoluteDir)) { mkdir($absoluteDir, 0o755, true); } $filename = Uuid::v4()->toRfc4122().'.pdf'; $fullRelative = sprintf('%s/%s', $relativePath, $filename); $originalName = $file->getClientOriginalName(); $previousPath = $data->getJustificatifPath(); $file->move($absoluteDir, $filename); $data->setJustificatifPath($fullRelative); $data->setJustificatifName($originalName); $this->entityManager->flush(); if (null !== $previousPath) { $previousAbsolute = sprintf('%s/%s', $this->uploadDir, $previousPath); if (file_exists($previousAbsolute)) { unlink($previousAbsolute); } } return new JsonResponse(['path' => $fullRelative, 'name' => $originalName], Response::HTTP_OK); } }