SimplesitemapController.php 1.69 KB
Newer Older
Pawel G's avatar
Pawel G committed
1
2
<?php

Pawel G's avatar
Pawel G committed
3
namespace Drupal\simple_sitemap\Controller;
Pawel G's avatar
Pawel G committed
4

5
use Drupal\Core\Cache\CacheableResponse;
6
7
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
Pawel G's avatar
Pawel G committed
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Pawel G's avatar
Pawel G committed
10
11
12
13

/**
 * SimplesitemapController.
 */
14
15
16
17
18
19
20
class SimplesitemapController extends ControllerBase {

  /**
   * The sitemap generator.
   *
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
Pawel G's avatar
Pawel G committed
21
  protected $generator;
Pawel G's avatar
Pawel G committed
22

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

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

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

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