SimplesitemapController.php 1.79 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 14
 * Class SimplesitemapController.
 *
gbyte.co's avatar
gbyte.co committed
15
 * @package Drupal\simple_sitemap\Controller
gbyte.co's avatar
gbyte.co committed
16
 */
17 18 19 20 21 22 23
class SimplesitemapController extends ControllerBase {

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

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

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

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

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

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