<?php
declare(strict_types=1);
namespace App\Controller;
use App\Repository\ContentRepository;
use App\Repository\Menu\ItemRepository;
use App\Router\Generator\DomainUrlGenerator;
use App\Service\CacheHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class SitemapController extends AbstractController
{
protected ItemRepository $menuRepo;
protected ContentRepository $contentRepo;
protected DomainUrlGenerator $urlGenerator;
protected Request $request;
protected TagAwareCacheInterface $cache;
public function __construct(
ItemRepository $menuRepo,
ContentRepository $contentRepo,
DomainUrlGenerator $urlGenerator,
RequestStack $requestStack,
TagAwareCacheInterface $appCache
) {
$this->menuRepo = $menuRepo;
$this->contentRepo = $contentRepo;
$this->urlGenerator = $urlGenerator;
$this->request = $requestStack->getCurrentRequest() ?? new Request();
$this->cache = $appCache;
}
public function sitemap(string $format, CacheHelper $cacheHelper): Response
{
if ($cacheHelper->cacheEnabled()) {
return $this->cache->get("sitemap.$format", function (CacheItem $item) use ($format) {
$item->expiresAfter(new \DateInterval('P1D'));
return $this->getResponseByFormat($format);
});
} else {
return $this->getResponseByFormat($format);
}
}
protected function getResponseByFormat(string $format): Response
{
$links = $this->menuRepo->findAllItemsStaticPaths();
$this->prependUrlsWithSchemeAndHost($links);
$links += $this->urlGenerator->matchContentArray(
$this->contentRepo->findAllContentWithRoutesForGenerator(),
true,
['full_url' => true]
);
switch ($format) {
case 'xml':
return $this->generateXml($links);
default:
throw new NotFoundHttpException('Unsupported format');
}
}
protected function generateXml(array $links): Response
{
$encoder = new XmlEncoder();
$data = [
'@xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
'url' => [],
];
foreach ($links as $l)
$data['url'][] = ['loc' => $l];
$response = $encoder->encode($data, 'xml' ,[
'xml_encoding' => 'utf-8',
'xml_root_node_name' => 'urlset',
]);
return new Response($response, 200, ['Content-type' => 'application/xml']);
}
protected function prependUrlsWithSchemeAndHost(array &$urls): void
{
$host = $this->request->getSchemeAndHttpHost();
foreach ($urls as &$url)
$url = $host . $url;
}
}