Files
SIRH/src/State/FormationJustificatifUploadProcessor.php
tristan 4cd30de3e3
Some checks failed
Auto Tag Develop / tag (push) Has been cancelled
feat : ajout d'un onglet formation
2026-04-13 09:41:36 +02:00

76 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Formation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Uid\Uuid;
final readonly class FormationJustificatifUploadProcessor implements ProcessorInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
private RequestStack $requestStack,
#[Autowire('%kernel.project_dir%/var/uploads')]
private string $uploadDir,
) {}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): JsonResponse
{
if (!$data instanceof Formation) {
throw new BadRequestHttpException('Invalid entity.');
}
$request = $this->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);
}
}