src/Service/FileDownloader.php line 22

  1. <?php
  2. namespace App\Service;
  3. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. use Symfony\Component\String\Slugger\SluggerInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use ZipArchive;
  8. class FileDownloader
  9. {
  10.     private $slugger;
  11.     private $filesystem;
  12.     public function __construct(SluggerInterface $sluggerFilesystem $filesystem)
  13.     {
  14.         $this->slugger $slugger;
  15.         $this->filesystem $filesystem;
  16.     }
  17.     public function download(array $folders = [], string $targetDirectory)
  18.     {
  19.         $zip = new ZipArchive();
  20.         $zipfile $targetDirectory."/candidat.zip";
  21.         /*if ($zip->open($zipfile, ZipArchive::CREATE) === true) {
  22.           echo $zip->addGlob($targetDirectory . "*.*", GLOB_BRACE, ["add_path" => "inside/","remove_all_path" => false]) ? "Folder added to zip" : "Error adding folder to zip" ;
  23.           echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ;
  24.         }
  25.         else { echo "Failed to open/create $zipfile"; }
  26.         */
  27.         
  28.         if ($zip->open($zipfileZipArchive::OVERWRITE ZipArchive::CREATE) === true) {
  29.             foreach ($folders as $folder$this->zipall($folder$targetDirectory$zip); 
  30.             echo $zip->close() ? "Zip archive closed" "Error closing zip archive" ;
  31.         }
  32.         
  33.         $response = new Response(file_get_contents($zipfile), Response::HTTP_OK, ['Content-Type' => 'application/zip''Content-Disposition' => 'attachment; filename="' basename($zipfile) . '"''Content-Length' => filesize($zip_name)]);
  34.         unlink($zipfile); 
  35.         return $response;
  36.     }
  37.     public function zipall(string $folderstring $baseZipArchive $ziparchive)
  38.     {
  39.         $options = ["remove_all_path" => false];
  40.         $path $base.$folder.'/';
  41.         if ($folder != $base$options["add_path"] = $path;
  42.         echo $ziparchive->addGlob($folder."*.*"GLOB_BRACE$options) ? "Folder added to zip" "Error adding folder to zip" ;
  43.         $folders glob($folder "*"GLOB_ONLYDIR);
  44.         if (count($folders)!=0) foreach ($folders as $fzipall($f."/"$base$ziparchive);
  45.     }
  46. }