0e6d371809cf7e7ce66d5c9501a279c87af400d7
[yaffs-website] / web / modules / contrib / simple_sitemap / src / Controller / SimplesitemapController.php
1 <?php
2
3 namespace Drupal\simple_sitemap\Controller;
4
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;
12
13 /**
14  * Class SimplesitemapController
15  * @package Drupal\simple_sitemap\Controller
16  */
17 class SimplesitemapController extends ControllerBase {
18
19   /**
20    * @var \Drupal\simple_sitemap\Simplesitemap
21    */
22   protected $generator;
23
24   /**
25    * @var \Drupal\Core\PageCache\ResponsePolicy\KillSwitch
26    */
27   protected $cacheKillSwitch;
28
29   /**
30    * SimplesitemapController constructor.
31    * @param \Drupal\simple_sitemap\Simplesitemap $generator
32    * @param \Drupal\Core\PageCache\ResponsePolicy\KillSwitch $cache_kill_switch
33    */
34   public function __construct(Simplesitemap $generator, KillSwitch $cache_kill_switch) {
35     $this->generator = $generator;
36     $this->cacheKillSwitch = $cache_kill_switch;
37   }
38
39   /**
40    * {@inheritdoc}
41    */
42   public static function create(ContainerInterface $container) {
43     return new static(
44       $container->get('simple_sitemap.generator'),
45       $container->get('page_cache_kill_switch')
46     );
47   }
48
49   /**
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.
52    *
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.
56    *
57    * @throws NotFoundHttpException
58    *
59    * @return object
60    *   Returns an XML response.
61    */
62   public function getSitemap($chunk_id = NULL) {
63     $output = $this->generator->getSitemap($chunk_id);
64     if (!$output) {
65       $this->cacheKillSwitch->trigger();
66       throw new NotFoundHttpException();
67     }
68
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.
73     ]);
74
75     // Cache output.
76     $meta_data = $response->getCacheableMetadata();
77     $meta_data->addCacheTags(['simple_sitemap']);
78
79     return $response;
80   }
81 }