src/Controller/FrontController.php line 119

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Page;
  4. use App\Entity\Path;
  5. use App\Entity\Tag;
  6. use App\Repository\PageRepository;
  7. use App\Repository\PathRepository;
  8. use App\Repository\TagRepository;
  9. use App\Service\CacheService;
  10. use App\Service\PageService;
  11. use App\Service\SiteMapService;
  12. use Doctrine\ORM\NonUniqueResultException;
  13. use Doctrine\Persistence\ManagerRegistry;
  14. use Psr\Cache\InvalidArgumentException;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  21. #[Route('/')]
  22. class FrontController extends AbstractController
  23. {
  24.     /**
  25.      * FrontController constructor.
  26.      */
  27.     public function __construct(
  28.         protected CacheService                     $cacheService,
  29.         protected PageService                      $pageService,
  30.         protected SiteMapService                   $siteMapService,
  31.         protected ManagerRegistry                  $registry,
  32.         private readonly CsrfTokenManagerInterface $csrfTokenManager)
  33.     {
  34.     }
  35.     #[Route('/debug/{slug}'name'front_index_debug')]
  36.     public function debug(Request $request): Response
  37.     {
  38.         // replace this example code with whatever you need
  39.         return $this->render('front/layout/debug/'.$request->get('slug').'.html.twig');
  40.     }
  41.     /**
  42.      * @throws \Exception
  43.      */
  44.     #[Route('sitemap.xml'name'front_siteMap_index')]
  45.     public function siteMapMain(Request $request): Response
  46.     {
  47.         /** @var PageRepository $pageRepository */
  48.         $pageRepository $this->registry->getRepository(Page::class);
  49.         $xml $this->siteMapService->getTree($pageRepository$request->getSchemeAndHttpHost());
  50.         $response = new Response($xml);
  51.         $response->headers->set('Content-Type''text/xml');
  52.         return $response;
  53.     }
  54.     /**
  55.      * @throws NonUniqueResultException
  56.      * @throws \Exception
  57.      */
  58.     #[Route('sitemap-{type}.xml'name'front_siteMap_type'requirements: ['type' => ".+[^\/]"])]
  59.     public function siteMapType(Request $requeststring $type): Response
  60.     {
  61.         /** @var PageRepository $pageRepository */
  62.         $pageRepository $this->registry->getRepository(Page::class);
  63.         if (!$pageRepository->findType($type) && 'main' !== $type) {
  64.             throw $this->createNotFoundException('Page not found');
  65.         }
  66.         $xml $this->siteMapService->getTypeTree($pageRepository$request->getSchemeAndHttpHost(), $type);
  67.         $response = new Response($xml);
  68.         $response->headers->set('Content-Type''text/xml');
  69.         return $response;
  70.     }
  71.     #[Route('/amp'name'front_root_amp')]
  72.     public function rootAmp(Request $request): Response
  73.     {
  74.         return $this->forward('App\\Controller\\FrontController::index', [
  75.             'request' => $request,
  76.             'path'    => '',
  77.         ]);
  78.     }
  79.     #[Route('/{path}/amp'name'front_index_amp'requirements: ['path' => ".+[^\/]"])]
  80.     public function indexAmp(Request $requeststring $path ''): Response
  81.     {
  82.         return $this->forward('App\\Controller\\FrontController::index', [
  83.             'request' => $request,
  84.             'path'    => $path,
  85.             'amp'     => true,
  86.         ]);
  87.     }
  88.     /**
  89.      * @throws NonUniqueResultException
  90.      * @throws InvalidArgumentException
  91.      */
  92.     #[Route('/{path}/page/{pagination}'name'front_index_paginated'requirements: ['path' => ".+[^\/]"])]
  93.     public function indexPaginated(Request $requeststring $path ''int $pagination 1bool $amp false): RedirectResponse|Response
  94.     {
  95.         return $this->handleRequest($request$path$amp$pagination);
  96.     }
  97.     /**
  98.      * @throws NonUniqueResultException
  99.      * @throws InvalidArgumentException
  100.      */
  101.     #[Route('/{path}'name'front_index'requirements: ['type' => ".+[^\/]"'path' => '^((?!logout).)*$'])]
  102.     public function index(Request $requeststring $path ''bool $amp false): RedirectResponse|Response
  103.     {
  104.         return $this->handleRequest($request$path$amp);
  105.     }
  106.     /**
  107.      * @throws NonUniqueResultException
  108.      * @throws InvalidArgumentException
  109.      */
  110.     private function handleRequest(Request $requeststring $path ''bool $amp falseint $pagination 1): RedirectResponse|Response
  111.     {
  112.         /** @var PathRepository $pathRepository */
  113.         $pathRepository $this->registry->getRepository(Path::class);
  114.         /** @var PageRepository $pageRepository */
  115.         $pageRepository $this->registry->getRepository(Page::class);
  116.         /** @var TagRepository $tagRepository */
  117.         $tagRepository $this->registry->getRepository(Tag::class);
  118.         $path $pathRepository->findOneSingleByPath($path$request->getLocale());
  119.         if (!$path) {
  120.             throw $this->createNotFoundException('Page not found');
  121.         }
  122.         if (Path::TYPE_REDIRECT == $path->getType()) {
  123.             /** @var Page $page */
  124.             $page $path->getPage();
  125.             if (null == $page || null == $page->getCurrentPath()) {
  126.                 throw $this->createNotFoundException('Page not found');
  127.             }
  128.             return new RedirectResponse($this->pageService->getFrontUrl($page));
  129.         }
  130.         /** @var Page $page */
  131.         $page $path->getPage();
  132.         $preview $request->query->get('preview');
  133.         if ($preview) {
  134.             if (!$this->isGranted('preview'$page)) {
  135.                 throw $this->createNotFoundException('Page not found');
  136.             }
  137.             $user     $this->getUser();
  138.             $cacheKey $this->cacheService->getPreviewCacheKey($user->getId(), $page->getId(), $page->getType());
  139.             $data     $this->cacheService->getAdapter()->getItem($cacheKey);
  140.             if ($data->isHit()) {
  141.                 $page->import($data->get());
  142.             }
  143.         } else {
  144.             if (!$this->isGranted('see-front'$page)) {
  145.                 throw $this->createNotFoundException('Page not found');
  146.             }
  147.         }
  148.         $page $this->pageService->resolveData($page$pageRepository$tagRepository);
  149.         $params = [
  150.             'page' => $page,
  151.         ];
  152.         $params['pagination'] = $pagination;
  153.         if ($page instanceof Page) {
  154.             $params $this->generateContentForSEO($request$page$pageRepository$params);
  155.         }
  156.         return $this->render('front/layout/'.(($amp) ? 'amp/' '').$page->getType().'.html.twig'$params);
  157.     }
  158.     /**
  159.      * @throws \Exception
  160.      */
  161.     public function pages(Request $requeststring $typeint $offset 0int $limit 10): Response
  162.     {
  163.         $locale $request->getLocale();
  164.         /** @var PageRepository $pageRepository */
  165.         $pageRepository $this->registry->getRepository(Page::class);
  166.         $filters = [
  167.             'locale'     => [$locale],
  168.             'status'     => ['published'],
  169.             'visibility' => 'public',
  170.             'expiration' => ['active'],
  171.         ];
  172.         $orderBy = ['created' => 'DESC'];
  173.         $items $pageRepository->paginate($type$filters$orderBy$limit$offset $limit);
  174.         return $this->render('front/section/'.$type.'.html.twig', [
  175.             'items'       => $items,
  176.             'currentPage' => $offset,
  177.         ]);
  178.     }
  179.     public function generateContentForSEO(Request $requestPage $pagePageRepository $pageRepository, array $params): array
  180.     {
  181.         switch ($page->getType()) {
  182.             case 'publications-list':
  183.                 $offset $request->query->get('page');
  184.                 if ($offset === null) {
  185.                     $offset 1;
  186.                 }
  187.                 $types = [
  188.                     "barometer-activity",
  189.                     "activity-report",
  190.                     "study",
  191.                     "thematic-brochure",
  192.                     "practical-guide",
  193.                     "btob-news"
  194.                 ];
  195.                 $publications       $pageRepository->paginateListPages($types, (int)$offset12);
  196.                 $totalPublications  $pageRepository->countPages($types);
  197.                 $params['publications'] = $publications;
  198.                 $params['pagination']   = [
  199.                     'offset'            => $offset,
  200.                     'totalPages'        => ceil($totalPublications[0][1] / 12)
  201.                 ];
  202.                 break;
  203.             case 'news-list':
  204.                 $offset $request->query->get('page');
  205.                 if ($offset === null) {
  206.                     $offset 1;
  207.                 }
  208.                 $types = [
  209.                     "agenda",
  210.                     "event",
  211.                     "article"
  212.                 ];
  213.                 $publications       $pageRepository->paginateListPages($types, (int)$offset12);
  214.                 $totalPublications  $pageRepository->countPages($types);
  215.                 $params['publications'] = $publications;
  216.                 $params['pagination']   = [
  217.                     'offset'            => $offset,
  218.                     'totalPages'        => ceil($totalPublications[0][1] / 12)
  219.                 ];
  220.                 break;
  221.         }
  222.         return $params;
  223.     }
  224.     public function generateCSRF(string $key, ?string $fieldName): Response
  225.     {
  226.         $token $this->csrfTokenManager->getToken($key)->getValue();
  227.         $response $this->render('front/partials/csrf-token.html.twig', [
  228.             'token' => $token,
  229.             'name'  => $fieldName
  230.         ]);
  231.         $response->setPublic();
  232.         $response->setCache([
  233.             'no_cache'          => true,
  234.             'max_age'           => 0,
  235.             'must_revalidate'   => true,
  236.             'no_store'          => true
  237.         ]);
  238.         return $response;
  239.     }
  240. }