<?php
namespace App\Controller\Api\CsvDownload;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
class CsvDownloadController
{
private string $baseDir;
public function __construct(string $dataOperatorDirectory)
{
$this->baseDir = realpath($dataOperatorDirectory);
}
public function __invoke(Request $request, string $entity, int $cpv): BinaryFileResponse
{
$codeCluster = $request->query->get('codeCluster', null);
$codeInsee = $request->query->get('codeInsee', null);
$codeIris = $request->query->get('codeIris', null);
$subDir = '';
if (strtoupper($entity) === 'PRODUCTION' || strtoupper($entity) === 'PRISES_PARC' || strtoupper($entity) === 'MOBILE') {
$subDir = "dataSFR/processed/" . strtoupper($entity) . "/csv_by_cpv";
if ($codeIris) {
$subDir = "dataSFR/processed/" . strtoupper($entity) . "/csv_by_cod_iris";
}
} else {
throw new NotFoundHttpException('Type d\'entité non reconnu.');
}
$fullBasePath = $this->baseDir . DIRECTORY_SEPARATOR . $subDir;
$fullBasePath = realpath($fullBasePath);
if (!$fullBasePath || !str_starts_with($fullBasePath, $this->baseDir)) {
throw new NotFoundHttpException('Répertoire inaccessible ou invalide.');
}
// Lister les sous-dossiers
$folders = array_filter(glob($fullBasePath . '/*'), 'is_dir');
// Trier par date décroissante
usort($folders, fn($a, $b) => filemtime($b) <=> filemtime($a));
foreach ($folders as $folder) {
$files = glob("$folder/{$cpv}_*.csv");
if (strtoupper($entity) === 'PRISES_PARC') {
$files = glob("$folder/{$cpv}/{$cpv}_*.csv");
}
if ($codeCluster) {
$files = glob("$folder/{$cpv}/{$codeCluster}/{$codeCluster}*.csv");
if ($codeInsee) {
$files = glob("$folder/{$cpv}/{$codeCluster}/{$codeInsee}*.csv");
}
}
if ($codeIris) {
$files = glob("$folder/{$codeIris}/{$codeIris}*.csv");
}
if (!empty($files)) {
$filePath = realpath($files[0]);
// Vérification finale
if ($filePath && str_starts_with($filePath, $this->baseDir) && is_file($filePath)) {
$response = new BinaryFileResponse($filePath);
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
basename($filePath)
);
return $response;
}
}
}
// Aucun fichier trouvé
throw new NotFoundHttpException('Fichier correspondant non trouvé.');
}
}