src/EventListener/CsvSanitizerListener.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Symfony\Component\HttpFoundation\File\UploadedFile;
  5. use App\Config;
  6. class CsvSanitizerListener
  7. {
  8. public function onKernelRequest(RequestEvent $event)
  9. {
  10. $request = $event->getRequest();
  11. $route = $request->attributes->get('_route');
  12. // Check if the request matches one of the target routes
  13. if (!in_array($route, Config::CSV_SANITIZATION_TARGET_ROUTES)) {
  14. return;
  15. }
  16. $csvFile = $request->files->get('file');
  17. if ($csvFile instanceof UploadedFile && $csvFile->getClientMimeType() === 'text/csv') {
  18. // Read the CSV file content
  19. $csvContent = file_get_contents($csvFile->getPathname());
  20. // Sanitize the CSV content
  21. $sanitizedCsvContent = $this->sanitizeCsv($csvContent);
  22. // Save the sanitized content to a temporary file
  23. $tempFilePath = tempnam(sys_get_temp_dir(), 'sanitized_csv');
  24. file_put_contents($tempFilePath, $sanitizedCsvContent);
  25. // Replace the original file with the sanitized one in the request
  26. $request->files->set('file', new \Symfony\Component\HttpFoundation\File\UploadedFile(
  27. $tempFilePath,
  28. $csvFile->getClientOriginalName(),
  29. $csvFile->getClientMimeType(),
  30. null,
  31. true
  32. ));
  33. }
  34. }
  35. private function sanitizeCsv(string $csvContent): string
  36. {
  37. // Remove BOM if it exists
  38. $bom = pack('H*', 'EFBBBF');
  39. $csvContent = preg_replace("/^$bom/", '', $csvContent);
  40. $lines = explode(PHP_EOL, $csvContent);
  41. // Use array_filter with a more comprehensive condition
  42. $sanitizedLines = array_filter($lines, function($line) {
  43. // Trim the line and check if it is empty or contains only commas and whitespace
  44. $trimmedLine = trim($line);
  45. return $trimmedLine !== '' && !preg_match('/^,+$/', $trimmedLine);
  46. });
  47. return implode(PHP_EOL, $sanitizedLines);
  48. }
  49. }