SimplesitemapController.php 1.87 KB
Newer Older
gbyte.co's avatar
gbyte.co committed
1 2
<?php

gbyte.co's avatar
gbyte.co committed
3
namespace Drupal\simple_sitemap\Controller;
gbyte.co's avatar
gbyte.co committed
4

5
use Drupal\Core\Cache\CacheableResponse;
6 7
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
gbyte.co's avatar
gbyte.co committed
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
gbyte.co's avatar
gbyte.co committed
10
use Drupal\simple_sitemap\Simplesitemap;
gbyte.co's avatar
gbyte.co committed
11 12

/**
gbyte.co's avatar
gbyte.co committed
13
 * Class SimplesitemapController
gbyte.co's avatar
gbyte.co committed
14
 * @package Drupal\simple_sitemap\Controller
gbyte.co's avatar
gbyte.co committed
15
 */
16 17 18 19 20 21 22
class SimplesitemapController extends ControllerBase {

  /**
   * The sitemap generator.
   *
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
23
  protected $generator;
gbyte.co's avatar
gbyte.co committed
24

25 26 27
  /**
   * SimplesitemapController constructor.
   *
28
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
29 30
   *   The sitemap generator.
   */
gbyte.co's avatar
gbyte.co committed
31
  public function __construct(Simplesitemap $generator) {
32
    $this->generator = $generator;
33 34
  }

gbyte.co's avatar
gbyte.co committed
35
  /**
36
   * Returns the whole sitemap, a requested sitemap chunk, or the sitemap index file.
37
   *
38
   * @param int $chunk_id
gbyte.co's avatar
gbyte.co committed
39 40
   *   Optional ID of the sitemap chunk. If none provided, the first chunk or
   *   the sitemap index is fetched.
41
   *
42 43
   * @throws NotFoundHttpException
   *
gbyte.co's avatar
gbyte.co committed
44
   * @return object
gbyte.co's avatar
gbyte.co committed
45
   *   Returns an XML response.
gbyte.co's avatar
gbyte.co committed
46
   */
47 48
  public function getSitemap($chunk_id = NULL) {
    $output = $this->generator->getSitemap($chunk_id);
49 50 51
    if (!$output) {
      throw new NotFoundHttpException();
    }
gbyte.co's avatar
gbyte.co committed
52

gbyte.co's avatar
gbyte.co committed
53
    // Display sitemap with correct XML header.
54 55 56 57
    $response = new CacheableResponse($output, Response::HTTP_OK, [
      'content-type' => 'application/xml',
      'X-Robots-Tag' => 'noindex', // Do not index the sitemap itself.
    ]);
58 59 60
    $meta_data = $response->getCacheableMetadata();
    $meta_data->addCacheTags(['simple_sitemap']);
    return $response;
gbyte.co's avatar
gbyte.co committed
61
  }
62 63 64 65 66 67 68

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('simple_sitemap.generator'));
  }
gbyte.co's avatar
gbyte.co committed
69

gbyte.co's avatar
gbyte.co committed
70
}