<?php
declare(strict_types=1);
namespace Hitso\Bundle\SeoBundle\Controller\Front;
use Hitso\Bundle\SeoBundle\Service\SitemapGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
/**
* Class SitemapController
*
* @package Hitso\Bundle\SeoBundle\Controller\Front
*/
class SitemapController extends Controller
{
protected $generator;
protected $cache;
protected $cacheNamePrefix = '';
protected $page;
protected $section;
protected $sharedMaxAge = 3600;
public function __construct(SitemapGenerator $generator)
{
$this->generator = $generator;
$this->cache = new FilesystemAdapter();
$cacheNamePrefix = isset($_ENV['APP_NAME'])?$_ENV['APP_NAME'].'_':'';
$cacheNamePrefix .= isset($_ENV['APP_ENV'])?$_ENV['APP_ENV'].'_':'';
$this->cacheNamePrefix = $cacheNamePrefix;
}
/**
* @Route("/sitemap.xml", name="hitso_sitemap_front_index")
*/
public function indexAction(ParameterBagInterface $params): Response
{
$this->sharedMaxAge = $params->get('hitso.sitemap.cache.shared_max_age');
$index = $this->cache->get($this->cacheNamePrefix . 'sitemap_index', function (ItemInterface $item) {
$item->expiresAfter($this->sharedMaxAge);
return $this->generator->generateIndex();
});
return $this->render('HitsoSeoBundle::Sitemap/index.xml.twig', [
'sitemap_index' => $index,
], $this->getEmptyXmlResponse($params));
}
/**
* @Route("/sitemap.{section}.{page}.xml", name="hitso_sitemap_front_section")
*/
public function sectionAction(SitemapGenerator $generator, string $section, int $page, ParameterBagInterface $params): Response
{
$this->sharedMaxAge = $params->get('hitso.sitemap.cache.shared_max_age');
$this->section = $section;
$this->page = $page;
$sitemapSectionPage = $this->cache->get($this->cacheNamePrefix . 'sitemap_section_' . $section . '_' . $page, function (ItemInterface $item) {
$item->expiresAfter($this->sharedMaxAge);
return $this->generator->generateSectionPage($this->section, $this->page);
});
if ($sitemapSectionPage->getCount() === 0) {
return new Response('Requested page is out of range', Response::HTTP_NOT_FOUND);
}
return $this->render('HitsoSeoBundle::Sitemap/section.xml.twig', [
'sitemap_section' => $sitemapSectionPage,
], $this->getEmptyXmlResponse($params));
}
private function getEmptyXmlResponse(ParameterBagInterface $params): Response
{
$response = new Response(null, Response::HTTP_OK, [
'Content-type' => 'text/xml',
'X-Robots-Tag' => 'noindex',
]);
$sharedMaxAge = $params->get('hitso.sitemap.cache.shared_max_age');
$response->setSharedMaxAge($sharedMaxAge);
return $response;
}
}