lib/boab/cms-bundle/src/Controller/DownloadController.php line 22

Open in your IDE?
  1. <?php
  2. namespace Boab\CmsBundle\Controller;
  3. use Boab\CmsBundle\Repository\ContentRepositoryInterface;
  4. use Boab\CmsBundle\Filesystem\FilesystemManager;
  5. use Intervention\Image\ImageManager;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\StreamedResponse;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. use Symfony\Component\HttpFoundation\Response;
  10. class DownloadController
  11. {
  12.     private FilesystemManager $filesystemManager;
  13.     public function __construct(FilesystemManager $filesystemManager)
  14.     {
  15.         $this->filesystemManager $filesystemManager;
  16.     }
  17.     public function download(Request $requeststring $fileName)
  18.     {
  19.         $filesystems $this->filesystemManager->getFilesystems();
  20.         $crop $this->parseSizeParameter($request);
  21.         foreach ($filesystems as $filesystem) {
  22.             if (!$filesystem->has($fileName)) {
  23.                 continue;
  24.             }
  25.             // Get the file extension
  26.             $extension pathinfo($fileNamePATHINFO_EXTENSION);
  27.             
  28.             // Exclude non-image file formats from caching
  29.             if ($crop && !$this->isImageExtension($extension)) {
  30.                 $crop null;
  31.             }      
  32.             
  33.             // Get the file stream
  34.             $fileStream $filesystem->readStream($fileName);
  35.             // If crop parameters are provided, perform the image cropping
  36.             if ($crop) {
  37.                 $croppedFileName $this->getCropFilename($fileName$crop);
  38.                 if($filesystem->has($croppedFileName)){
  39.                     $fileStream2 $filesystem->readStream($fileName);
  40.                     return $this->createStreamResponse($fileStream2$extension);
  41.                 }
  42.                 // Save the cropped image to the same filesystem
  43.                 $fileStream $this->getCroppedStream($fileStream$crop);
  44.                 $filesystem->writeStream($croppedFileName$fileStream);
  45.                 return $this->createStreamResponse($fileStream$extension);
  46.             }
  47.             // Set the appropriate content type based on the file extension
  48.            return $this->createStreamResponse($fileStream$extension);
  49.         }
  50.         
  51.         // If the file is not found in any filesystem, throw a NotFoundHttpException
  52.         throw new NotFoundHttpException('File not found.');        
  53.     }
  54.     private function createStreamResponse($fileStream$extensionstring $fileName=""):Response
  55.     {
  56.         // Set the appropriate content type based on the file extension
  57.         $contentType $this->getContentType($extension);
  58.         $response = new StreamedResponse(function() use ($fileStream$fileName) {
  59.             $outputStream fopen('php://output''wb');
  60.             //$fileStream = $cloudStorageAudio->readStream($audio->getPrimaryFile(), false);
  61.             stream_copy_to_stream($fileStream$outputStream);
  62.         });
  63.         $response->headers->set('Content-Type'$contentType);                
  64.         
  65.         return $response;  
  66.     }
  67.     private function getCroppedStream($stream, array $crop)
  68.     {
  69.         $imageManager = new ImageManager();
  70.         $image $imageManager->make($stream);
  71.         //$image->crop($crop['width'], $crop['height'], $crop['x'], $crop['y']);
  72.         $image->resize($crop['width'], $crop['height'], function ($constraint) {
  73.             $constraint->aspectRatio();
  74.             $constraint->upsize();
  75.         });
  76.         $stream $image->stream()->detach();
  77.         return $stream;
  78.     }
  79.     private function getCropFilename(string $filename, array $crop): string
  80.     {
  81.         if ($crop) {
  82.             $cropFilename pathinfo($filenamePATHINFO_FILENAME) . '_' $crop['width'] . 'x' $crop['height'] . '.' pathinfo($filenamePATHINFO_EXTENSION);
  83.             return $cropFilename;
  84.         }
  85.     
  86.         return $filename;
  87.     }    
  88.     
  89.     private function isImageExtension(string $extension): bool
  90.     {
  91.         $imageExtensions = ['jpg''jpeg''png''gif']; // Add more image extensions as needed
  92.     
  93.         return in_array(strtolower($extension), $imageExtensionstrue);
  94.     }  
  95.     
  96.     private function parseSizeParameter(Request $request): ?array
  97.     {
  98.         // Get the size from the query parameters
  99.         $size $request->query->get('size');       
  100.             
  101.         if (!$size) {
  102.             return null;
  103.         }        
  104.         // Split the size parameter into width and height
  105.         $parts explode('x'$size);
  106.         // If both width and height are specified, return the crop parameters
  107.         if (count($parts) === 2) {
  108.             return [
  109.                 'x' => 0,
  110.                 'y' => 0,
  111.                 'width' => (int) $parts[0],
  112.                 'height' => (int) $parts[1],
  113.             ];
  114.         }
  115.         return null;
  116.     }    
  117.     private function getContentType(string $extension): string
  118.     {
  119.         $mappings = [
  120.             'pdf' => 'application/pdf',
  121.             'jpg' => 'image/jpeg',
  122.             'jpeg' => 'image/jpeg',
  123.             'png' => 'image/png',
  124.             // Add more mappings as needed
  125.         ];
  126.     
  127.         // Check if the extension mapping exists, otherwise default to 'application/octet-stream'
  128.         return $mappings[$extension] ?? 'application/octet-stream';
  129.     }    
  130. }