SimplesitemapController.php 2.1 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 6
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
gbyte.co's avatar
gbyte.co committed
7
use Symfony\Component\HttpFoundation\Response;
8
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
gbyte.co's avatar
gbyte.co committed
9
use Drupal\simple_sitemap\Simplesitemap;
10
use Symfony\Component\HttpFoundation\Request;
11
use Drupal\simple_sitemap\SimplesitemapManager;
gbyte.co's avatar
gbyte.co committed
12 13

/**
gbyte.co's avatar
gbyte.co committed
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
class SimplesitemapController extends ControllerBase {

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

24 25
  /**
   * SimplesitemapController constructor.
26
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
27
   */
28
  public function __construct(Simplesitemap $generator) {
29
    $this->generator = $generator;
30 31 32 33 34 35 36
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
37
      $container->get('simple_sitemap.generator')
38
    );
39 40
  }

gbyte.co's avatar
gbyte.co committed
41
  /**
42
   * Returns the whole sitemap variant, its requested chunk,
43
   * or its sitemap index file.
44
   * Caches the response in case of expected output, prevents caching otherwise.
45
   *
46 47 48
   * @param string $variant
   *  Optional name of sitemap variant.
   *  @see \hook_simple_sitemap_variants_alter()
49
   *  @see SimplesitemapManager::getSitemapVariants()
50
   *
51 52
   * @param \Symfony\Component\HttpFoundation\Request $request
   *  The request object.
53
   *
54 55
   * @throws NotFoundHttpException
   *
gbyte.co's avatar
gbyte.co committed
56
   * @return object
57
   *  Returns an XML response.
gbyte.co's avatar
gbyte.co committed
58
   */
59
  public function getSitemap(Request $request, $variant = NULL) {
60 61 62 63
    $variant = NULL !== $variant
      ? $variant
      : $this->generator->getSetting('default_variant', SimplesitemapManager::DEFAULT_SITEMAP_VARIANT);

64
    $output = $this->generator->getSitemap($variant, $request->query->getInt('page'));
65 66 67
    if (!$output) {
      throw new NotFoundHttpException();
    }
gbyte.co's avatar
gbyte.co committed
68

69
    return new Response($output, Response::HTTP_OK, [
70
      'content-type' => 'application/xml',
71
      'X-Robots-Tag' => 'noindex', // Tell search engines not to index the sitemap itself.
72
    ]);
73
  }
gbyte.co's avatar
gbyte.co committed
74
}