3 namespace Drupal\simple_sitemap\Controller;
5 use Drupal\Core\Controller\ControllerBase;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
7 use Symfony\Component\HttpFoundation\Response;
8 use Drupal\Core\Cache\CacheableResponse;
9 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
10 use Drupal\simple_sitemap\Simplesitemap;
11 use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
14 * Class SimplesitemapController
15 * @package Drupal\simple_sitemap\Controller
17 class SimplesitemapController extends ControllerBase {
20 * @var \Drupal\simple_sitemap\Simplesitemap
25 * @var \Drupal\Core\PageCache\ResponsePolicy\KillSwitch
27 protected $cacheKillSwitch;
30 * SimplesitemapController constructor.
31 * @param \Drupal\simple_sitemap\Simplesitemap $generator
32 * @param \Drupal\Core\PageCache\ResponsePolicy\KillSwitch $cache_kill_switch
34 public function __construct(Simplesitemap $generator, KillSwitch $cache_kill_switch) {
35 $this->generator = $generator;
36 $this->cacheKillSwitch = $cache_kill_switch;
42 public static function create(ContainerInterface $container) {
44 $container->get('simple_sitemap.generator'),
45 $container->get('page_cache_kill_switch')
50 * Returns the whole sitemap, a requested sitemap chunk, or the sitemap index file.
51 * Caches the response in case of expected output, prevents caching otherwise.
53 * @param int $chunk_id
54 * Optional ID of the sitemap chunk. If none provided, the first chunk or
55 * the sitemap index is fetched.
57 * @throws NotFoundHttpException
60 * Returns an XML response.
62 public function getSitemap($chunk_id = NULL) {
63 $output = $this->generator->getSitemap($chunk_id);
65 $this->cacheKillSwitch->trigger();
66 throw new NotFoundHttpException();
69 // Display sitemap with correct XML header.
70 $response = new CacheableResponse($output, Response::HTTP_OK, [
71 'content-type' => 'application/xml',
72 'X-Robots-Tag' => 'noindex', // Do not index the sitemap itself.
76 $meta_data = $response->getCacheableMetadata();
77 $meta_data->addCacheTags(['simple_sitemap']);