vendor/contao/core-bundle/src/Controller/FaviconController.php line 54

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\Cache\EntityCacheTags;
  12. use Contao\CoreBundle\Framework\ContaoFramework;
  13. use Contao\FilesModel;
  14. use Contao\PageModel;
  15. use Symfony\Component\Filesystem\Path;
  16. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. /**
  21.  * @Route(defaults={"_scope" = "frontend"})
  22.  *
  23.  * @internal
  24.  */
  25. class FaviconController
  26. {
  27.     private ContaoFramework $framework;
  28.     private string $projectDir;
  29.     private EntityCacheTags $entityCacheTags;
  30.     public function __construct(ContaoFramework $frameworkstring $projectDirEntityCacheTags $entityCacheTags)
  31.     {
  32.         $this->framework $framework;
  33.         $this->projectDir $projectDir;
  34.         $this->entityCacheTags $entityCacheTags;
  35.     }
  36.     /**
  37.      * @Route("/favicon.ico")
  38.      */
  39.     public function __invoke(Request $request): Response
  40.     {
  41.         $this->framework->initialize();
  42.         $pageModel $this->framework->getAdapter(PageModel::class);
  43.         $rootPage $pageModel->findPublishedFallbackByHostname(
  44.             $request->getHost(),
  45.             ['fallbackToEmpty' => true]
  46.         );
  47.         if (null === $rootPage || null === ($favicon $rootPage->favicon)) {
  48.             return new Response(''Response::HTTP_NOT_FOUND);
  49.         }
  50.         $filesModel $this->framework->getAdapter(FilesModel::class);
  51.         $faviconModel $filesModel->findByUuid($favicon);
  52.         if (null === $faviconModel) {
  53.             return new Response(''Response::HTTP_NOT_FOUND);
  54.         }
  55.         // Cache the response for 1 year and tag it, so it is invalidated when the settings are edited
  56.         $response = new BinaryFileResponse(Path::join($this->projectDir$faviconModel->path));
  57.         $response->setSharedMaxAge(31556952);
  58.         switch ($faviconModel->extension) {
  59.             case 'svg':
  60.                 $response->headers->set('Content-Type''image/svg+xml');
  61.                 break;
  62.             case 'ico':
  63.                 $response->headers->set('Content-Type''image/x-icon');
  64.                 break;
  65.         }
  66.         $this->entityCacheTags->tagWithModelInstance($rootPage);
  67.         return $response;
  68.     }
  69. }