vendor/contao/core-bundle/src/Controller/ImagesController.php line 29

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of Contao.
  5.  *
  6.  * (c) Leo Feyer
  7.  *
  8.  * @license LGPL-3.0-or-later
  9.  */
  10. namespace Contao\CoreBundle\Controller;
  11. use Contao\CoreBundle\Image\ImageFactoryInterface;
  12. use Contao\Image\DeferredImageInterface;
  13. use Contao\Image\DeferredResizerInterface;
  14. use Contao\Image\Exception\FileNotExistsException;
  15. use Contao\Image\ResizerInterface;
  16. use Symfony\Component\Filesystem\Filesystem;
  17. use Symfony\Component\Filesystem\Path;
  18. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  21. /**
  22.  * @internal
  23.  */
  24. class ImagesController
  25. {
  26.     private ImageFactoryInterface $imageFactory;
  27.     private ResizerInterface $resizer;
  28.     private string $targetDir;
  29.     private Filesystem $filesystem;
  30.     public function __construct(ImageFactoryInterface $imageFactoryResizerInterface $resizerstring $targetDirFilesystem $filesystem null)
  31.     {
  32.         $this->imageFactory $imageFactory;
  33.         $this->resizer $resizer;
  34.         $this->targetDir $targetDir;
  35.         $this->filesystem $filesystem ?? new Filesystem();
  36.     }
  37.     /**
  38.      * The route is registered dynamically in the Contao\CoreBundle\Routing\ImagesLoader class.
  39.      */
  40.     public function __invoke(string $path): Response
  41.     {
  42.         try {
  43.             try {
  44.                 $image $this->imageFactory->create(Path::join($this->targetDir$path));
  45.             } catch (\InvalidArgumentException $exception) {
  46.                 throw new NotFoundHttpException($exception->getMessage(), $exception);
  47.             }
  48.             if ($image instanceof DeferredImageInterface && $this->resizer instanceof DeferredResizerInterface) {
  49.                 $this->resizer->resizeDeferredImage($image);
  50.             } elseif (!$this->filesystem->exists($image->getPath())) {
  51.                 throw new NotFoundHttpException('Image does not exist');
  52.             }
  53.         } catch (FileNotExistsException $exception) {
  54.             throw new NotFoundHttpException($exception->getMessage(), $exception);
  55.         }
  56.         return new BinaryFileResponse($image->getPath(), 200, ['Cache-Control' => 'private, max-age=31536000'], false);
  57.     }
  58. }