<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Response;
class DownloadController extends AbstractController
{
const TEMPORARY_FOLDER = '/tmp';
/**
* @var Filesystem
*/
private Filesystem $filesystem;
/**
* @param Filesystem $filesystem
*/
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* @param string $name
* @param string $extension
* @return Response
*/
public function downloadFileResult(string $name, string $extension = 'csv'): Response
{
$temporaryFile = sprintf('%s/%s', self::TEMPORARY_FOLDER, $name);
$filename = sprintf('%s.%s', $name, $extension);
if (!$this->filesystem->exists($temporaryFile)) {
throw new \RuntimeException('Impossible to download this file.');
}
$response = new Response();
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', sprintf('attachment; filename=%s', $filename));
$response->setContent(file_get_contents($temporaryFile));
return $response;
}
}