<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Config;
class CsvSanitizerListener
{
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$route = $request->attributes->get('_route');
// Check if the request matches one of the target routes
if (!in_array($route, Config::CSV_SANITIZATION_TARGET_ROUTES)) {
return;
}
$csvFile = $request->files->get('file');
if ($csvFile instanceof UploadedFile && $csvFile->getClientMimeType() === 'text/csv') {
// Read the CSV file content
$csvContent = file_get_contents($csvFile->getPathname());
// Sanitize the CSV content
$sanitizedCsvContent = $this->sanitizeCsv($csvContent);
// Save the sanitized content to a temporary file
$tempFilePath = tempnam(sys_get_temp_dir(), 'sanitized_csv');
file_put_contents($tempFilePath, $sanitizedCsvContent);
// Replace the original file with the sanitized one in the request
$request->files->set('file', new \Symfony\Component\HttpFoundation\File\UploadedFile(
$tempFilePath,
$csvFile->getClientOriginalName(),
$csvFile->getClientMimeType(),
null,
true
));
}
}
private function sanitizeCsv(string $csvContent): string
{
// Remove BOM if it exists
$bom = pack('H*', 'EFBBBF');
$csvContent = preg_replace("/^$bom/", '', $csvContent);
$lines = explode(PHP_EOL, $csvContent);
// Use array_filter with a more comprehensive condition
$sanitizedLines = array_filter($lines, function($line) {
// Trim the line and check if it is empty or contains only commas and whitespace
$trimmedLine = trim($line);
return $trimmedLine !== '' && !preg_match('/^,+$/', $trimmedLine);
});
return implode(PHP_EOL, $sanitizedLines);
}
}