|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace AppBundle\Controller\Admin\Accounting\BankAccounts; |
| 6 | + |
| 7 | +use AppBundle\Accounting\Model\Repository\InvoicingPeriodRepository; |
| 8 | +use DateInterval; |
| 9 | +use DatePeriod; |
| 10 | +use RuntimeException; |
| 11 | +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
| 12 | +use Symfony\Component\HttpFoundation\BinaryFileResponse; |
| 13 | +use Symfony\Component\HttpFoundation\Request; |
| 14 | +use Symfony\Component\HttpFoundation\Response; |
| 15 | +use ZipArchive; |
| 16 | + |
| 17 | +class DownloadStatementAction extends AbstractController |
| 18 | +{ |
| 19 | + public function __construct(private readonly InvoicingPeriodRepository $invoicingPeriodRepository) {} |
| 20 | + |
| 21 | + public function __invoke(Request $request): Response |
| 22 | + { |
| 23 | + $periodId = $request->query->has('periodId') && $request->query->get('periodId') ? (int) $request->query->get('periodId') : null; |
| 24 | + $period = $this->invoicingPeriodRepository->getCurrentPeriod($periodId); |
| 25 | + try { |
| 26 | + $year = $period->getStartDate()->format('Y'); |
| 27 | + |
| 28 | + // Create the zip |
| 29 | + $zipFilename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'afup_justificatifs-' . $year . '.zip'; |
| 30 | + $zip = new ZipArchive(); |
| 31 | + $state = $zip->open($zipFilename, ZipArchive::CREATE); |
| 32 | + if ($state !== true) { |
| 33 | + throw new RuntimeException("Impossible to open the Zip archive."); |
| 34 | + } else { |
| 35 | + $datePeriod = new DatePeriod($period->getStartDate(), new DateInterval('P1M'), $period->getEndDate()); |
| 36 | + /** @var \DateTime $month */ |
| 37 | + foreach ($datePeriod as $month) { |
| 38 | + $searchDir = $month->format('Ym'); |
| 39 | + $zipDir = $month->format('Ym'); |
| 40 | + $options = [ |
| 41 | + 'add_path' => 'afup_justificatifs-' . $year . '/' . $zipDir . '/', |
| 42 | + 'remove_all_path' => true, |
| 43 | + ]; |
| 44 | + $zip->addGlob(AFUP_CHEMIN_RACINE . '/uploads/' . $searchDir . '/*.*', 0, $options); |
| 45 | + } |
| 46 | + $zip->close(); |
| 47 | + |
| 48 | + $response = new BinaryFileResponse($zipFilename, Response::HTTP_OK, [ |
| 49 | + 'Content-Type' => 'application/zip', |
| 50 | + 'Content-Transfer-Encoding' => 'Binary', |
| 51 | + 'Content-Disposition' => 'attachment; filename="' . basename($zipFilename) . '"', |
| 52 | + 'Cache-Control' => 'max-age=0', |
| 53 | + ], false); |
| 54 | + $response->deleteFileAfterSend(true); |
| 55 | + |
| 56 | + return $response; |
| 57 | + } |
| 58 | + } catch (\Exception $exception) { |
| 59 | + return new Response(null, Response::HTTP_BAD_REQUEST, [ |
| 60 | + 'X-Info' => $exception->getMessage(), |
| 61 | + ]); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments