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

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\HttpFoundation\BinaryFileResponse;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  20. use Webmozart\PathUtil\Path;
  21. /**
  22.  * @internal
  23.  */
  24. class ImagesController
  25. {
  26.     /**
  27.      * @var ImageFactoryInterface
  28.      */
  29.     private $imageFactory;
  30.     /**
  31.      * @var ResizerInterface
  32.      */
  33.     private $resizer;
  34.     /**
  35.      * @var string
  36.      */
  37.     private $targetDir;
  38.     /**
  39.      * @var Filesystem
  40.      */
  41.     private $filesystem;
  42.     public function __construct(ImageFactoryInterface $imageFactoryResizerInterface $resizerstring $targetDirFilesystem $filesystem null)
  43.     {
  44.         $this->imageFactory $imageFactory;
  45.         $this->resizer $resizer;
  46.         $this->targetDir $targetDir;
  47.         $this->filesystem $filesystem ?? new Filesystem();
  48.     }
  49.     /**
  50.      * The route is registered dynamically in the Contao\CoreBundle\Routing\ImagesLoader class.
  51.      */
  52.     public function __invoke(string $path): Response
  53.     {
  54.         try {
  55.             try {
  56.                 $image $this->imageFactory->create(Path::join($this->targetDir$path));
  57.             } catch (\InvalidArgumentException $exception) {
  58.                 throw new NotFoundHttpException($exception->getMessage(), $exception);
  59.             }
  60.             if ($image instanceof DeferredImageInterface && $this->resizer instanceof DeferredResizerInterface) {
  61.                 $this->resizer->resizeDeferredImage($image);
  62.             } elseif (!$this->filesystem->exists($image->getPath())) {
  63.                 throw new NotFoundHttpException('Image does not exist');
  64.             }
  65.         } catch (FileNotExistsException $exception) {
  66.             throw new NotFoundHttpException($exception->getMessage(), $exception);
  67.         }
  68.         return new BinaryFileResponse($image->getPath(), 200, ['Cache-Control' => 'private, max-age=31536000'], false);
  69.     }
  70. }