feat: add POST /api/imports endpoint

This commit is contained in:
thibaud-leclere
2026-03-29 10:21:02 +02:00
parent 4955c5bde9
commit 2cfbe191cf

View File

@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Import;
use App\Entity\User;
use App\Message\ProcessImportMessage;
use Doctrine\ORM\EntityManagerInterface;
use League\Flysystem\FilesystemOperator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class ImportController extends AbstractController
{
#[Route('/api/imports', methods: ['POST'])]
#[IsGranted('ROLE_USER')]
public function create(
Request $request,
FilesystemOperator $defaultStorage,
EntityManagerInterface $em,
MessageBusInterface $bus,
): JsonResponse {
$file = $request->files->get('file');
if (!$file) {
return $this->json(['error' => 'No file provided.'], Response::HTTP_UNPROCESSABLE_ENTITY);
}
if ('csv' !== $file->getClientOriginalExtension()) {
return $this->json(['error' => 'Only CSV files are accepted.'], Response::HTTP_UNPROCESSABLE_ENTITY);
}
if ($file->getSize() > 5 * 1024 * 1024) {
return $this->json(['error' => 'File too large (max 5 MB).'], Response::HTTP_UNPROCESSABLE_ENTITY);
}
/** @var User $user */
$user = $this->getUser();
$import = new Import();
$import->setUser($user);
$em->persist($import);
$em->flush();
$filePath = sprintf('imports/%d/%d.csv', $user->getId(), $import->getId());
$defaultStorage->write($filePath, file_get_contents($file->getPathname()));
$import->setFilePath($filePath);
$em->flush();
$bus->dispatch(new ProcessImportMessage($import->getId()));
return $this->json([
'id' => $import->getId(),
'status' => $import->getStatus(),
], Response::HTTP_CREATED);
}
}