diff --git a/src/Entity/XmlSitemap.php b/src/Entity/XmlSitemap.php
index d5c8472..2f76a08 100644
--- a/src/Entity/XmlSitemap.php
+++ b/src/Entity/XmlSitemap.php
@@ -175,7 +175,7 @@ class XmlSitemap extends ConfigEntityBase implements XmlSitemapInterface {
   /**
    * {@inheritdoc}
    */
-  public function setContext($context) {
+  public function setContext($context = []) {
     $this->context = $context;
     return $this;
   }
@@ -205,4 +205,11 @@ class XmlSitemap extends ConfigEntityBase implements XmlSitemapInterface {
     return NULL;
   }
 
+  /**
+   * {@inheritdoc}
+   */
+  public function getUri() {
+    return $this->uri;
+  }
+
 }
diff --git a/src/Form/XmlSitemapForm.php b/src/Form/XmlSitemapForm.php
index b63d0cd..07a6a6b 100644
--- a/src/Form/XmlSitemapForm.php
+++ b/src/Form/XmlSitemapForm.php
@@ -7,6 +7,7 @@ use Drupal\Core\Entity\EntityStorageException;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\Core\Render\Element;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\xmlsitemap\XmlSitemapInterface;
 
 /**
  * Provides a form for creating and editing xmlsitemap entities.
@@ -25,11 +26,18 @@ class XmlSitemapForm extends EntityForm {
    */
   public function form(array $form, FormStateInterface $form_state) {
     $form = parent::form($form, $form_state);
+    if ($this->entity instanceof XmlSitemapInterface) {
+      $xmlsitemap = $this->entity;
+    }
+    else {
+      return FALSE;
+    }
+
     if ($this->entity->getContext() == NULL) {
-      $this->entity->context = array();
+      $this->entity->setContext([]);
       $this->entity->setOriginalId(NULL);
     }
-    $xmlsitemap = $this->entity;
+
     $form['#entity'] = $xmlsitemap;
     $form['label'] = array(
       '#type' => 'textfield',
@@ -67,20 +75,25 @@ class XmlSitemapForm extends EntityForm {
       }
     }
     $context = $form_state->getValue('context');
-    $this->entity->context = $context;
-    $this->entity->label = $form_state->getValue('label');
-    $this->entity->id = xmlsitemap_sitemap_get_context_hash($context);
+
+    if (!($this->entity instanceof XmlSitemapInterface)) {
+      return;
+    }
+
+    $this->entity->setContext($context);
+    $this->entity->setLabel($form_state->getValue('label'));
+    $this->entity->setId(xmlsitemap_sitemap_get_context_hash($context));
 
     try {
       $status = $this->entity->save();
       if ($status == SAVED_NEW) {
         drupal_set_message($this->t('Saved the %label sitemap.', array(
-              '%label' => $this->entity->label(),
+          '%label' => $this->entity->label(),
         )));
       }
-      else if ($status == SAVED_UPDATED) {
+      elseif ($status == SAVED_UPDATED) {
         drupal_set_message($this->t('Updated the %label sitemap.', array(
-              '%label' => $this->entity->label(),
+          '%label' => $this->entity->label(),
         )));
       }
     }
@@ -95,10 +108,8 @@ class XmlSitemapForm extends EntityForm {
    * {@inheritdoc}
    */
   public function delete(array $form, FormStateInterface $form_state) {
-    $destination = array();
     $request = $this->getRequest();
     if ($request->query->has('destination')) {
-      $destination = drupal_get_destination();
       $request->query->remove('destination');
     }
     $form_state->setRedirect('xmlsitemap.admin_delete', array('xmlsitemap' => $this->entity->id()));
diff --git a/src/Form/XmlSitemapRebuildForm.php b/src/Form/XmlSitemapRebuildForm.php
index 773da0e..ad38352 100644
--- a/src/Form/XmlSitemapRebuildForm.php
+++ b/src/Form/XmlSitemapRebuildForm.php
@@ -8,6 +8,8 @@ use Drupal\Core\State\StateInterface;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\Url;
 use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\RequestStack;
+use Drupal\xmlsitemap\XmlSitemapGenerator;
 
 /**
  * Configure xmlsitemap settings for this site.
@@ -22,26 +24,44 @@ class XmlSitemapRebuildForm extends ConfigFormBase {
   protected $state;
 
   /**
+   * The Xmlsitemap generator.
+   *
+   * @var \Drupal\xmlsitemap\XmlSitemapGenerator
+   */
+  protected $generator;
+
+  /**
    * Constructs a new XmlSitemapRebuildForm object.
    *
    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
    *   The factory for configuration objects.
    * @param \Drupal\Core\State\StateInterface $state
    *   The state service.
+   * @param \Drupal\xmlsitemap\XmlSitemapGenerator $generator
+   *   The Xmlsitemap generator.
    */
-  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state) {
+  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, XmlSitemapGenerator $generator) {
     parent::__construct($config_factory);
 
     $this->state = $state;
+    $this->generator = $generator;
   }
 
   /**
    * {@inheritdoc}
    */
   public static function create(ContainerInterface $container) {
+    /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
+    $config_factory = $container->get('config.factory');
+    /** @var \Drupal\Core\State\StateInterface $state */
+    $state = $container->get('state');
+    /** @var \Drupal\xmlsitemap\XmlSitemapGenerator $generator */
+    $generator = $container->get('xmlsitemap_generator');
+
     return new static(
-      $container->get('config.factory'),
-      $container->get('state')
+      $config_factory,
+      $state,
+      $generator
     );
   }
 
@@ -64,45 +84,78 @@ class XmlSitemapRebuildForm extends ConfigFormBase {
    */
   public function buildForm(array $form, FormStateInterface $form_state) {
     $request = $this->getRequest();
+
     if (!$request->request && !$this->state->get('xmlsitemap_rebuild_needed')) {
       if (!$this->state->get('xmlsitemap_regenerate_needed')) {
         drupal_set_message(t('Your sitemap is up to date and does not need to be rebuilt.'), 'error');
       }
       else {
         $request->query->set('destination', 'admin/config/search/xmlsitemap');
-        drupal_set_message(t('A rebuild is not necessary. If you are just wanting to regenerate the XML sitemap files, you can <a href="@link-cron">run cron manually</a>.', array('@link-cron' => Url::fromRoute('system.run_cron', [], array('query' => drupal_get_destination())))), 'warning');
-        $this->setRequest($request);
+        drupal_set_message(
+          t(
+            'A rebuild is not necessary. If you are just wanting to regenerate the XML sitemap files, you can <a href=":link-cron">run cron manually</a>.',
+            [
+              ':link-cron' => Url::fromRoute('system.run_cron', [], ['query' => \Drupal::destination()->getAsArray()]),
+            ]
+          ),
+          'warning'
+        );
+        $requestStack = new RequestStack();
+        $requestStack->push($request);
+        $this->setRequestStack($requestStack);
       }
     }
 
     // Build a list of rebuildable link types.
     $rebuild_types = xmlsitemap_get_rebuildable_link_types();
-    $rebuild_types = array_combine($rebuild_types, $rebuild_types);
+    $options = [];
+    $default_value = [];
+    foreach ($rebuild_types as $type) {
+      $options[$type] = [
+        'label' => \Drupal::entityTypeManager()->getDefinition($type)->getLabel(),
+        'count' => \Drupal::entityQuery($type)->count()->execute(),
+      ];
+      if ($this->state->get('xmlsitemap_rebuild_needed') || !$this->state->get('xmlsitemap_developer_mode')) {
+        $default_value[$type] = TRUE;
+      }
+    }
+
+    $form = parent::buildForm($form, $form_state);
+
     $form['entity_type_ids'] = array(
-      '#type' => 'select',
+      '#type' => 'tableselect',
+      '#header' => [
+        'label' => t('Enttiy type'),
+        'count' => t('Count'),
+      ],
+      '#tableselect' => TRUE,
+      '#options' => $options,
       '#title' => t('Select which link types you would like to rebuild'),
       '#description' => t('If no link types are selected, the sitemap files will just be regenerated.'),
-      '#multiple' => TRUE,
-      '#options' => $rebuild_types,
-      '#default_value' => $this->state->get('xmlsitemap_rebuild_needed') || !$this->state->get('xmlsitemap_developer_mode') ? $rebuild_types : array(),
-      '#access' => $this->state->get('xmlsitemap_developer_mode'),
+      '#default_value' => $default_value,
     );
+
     $form['save_custom'] = array(
       '#type' => 'checkbox',
       '#title' => t('Save and restore any custom inclusion and priority links.'),
       '#default_value' => TRUE,
     );
-    return parent::buildForm($form, $form_state);
+
+    return $form;
   }
 
   /**
    * {@inheritdoc}
    */
   public function submitForm(array &$form, FormStateInterface $form_state) {
-    // Save any changes to the frontpage link.
-    $entity_type_ids = $form_state->getValue('entity_type_ids');
+    $entity_type_ids = [];
+    foreach ($form_state->getValue('entity_type_ids') as $type => $value) {
+      if (!empty($value)) {
+        $entity_type_ids[] = $type;
+      }
+    }
     $save_custom = $form_state->getValue('save_custom');
-    $batch = xmlsitemap_rebuild_batch($entity_type_ids, $save_custom);
+    $batch = $this->generator->createRebuildBatch($entity_type_ids, $save_custom);
     batch_set($batch);
 
     $form_state->setRedirect('xmlsitemap.admin_search');
diff --git a/src/XmlSitemapException.php b/src/XmlSitemapException.php
index f3cdacd..d7552f0 100644
--- a/src/XmlSitemapException.php
+++ b/src/XmlSitemapException.php
@@ -5,4 +5,4 @@ namespace Drupal\xmlsitemap;
 /**
  * Base XmlSitemapException class.
  */
-class XmlSitemapException extends \Exception { }
+class XmlSitemapException extends \Exception {}
diff --git a/src/XmlSitemapGenerationException.php b/src/XmlSitemapGenerationException.php
index afc1a5e..d442640 100644
--- a/src/XmlSitemapGenerationException.php
+++ b/src/XmlSitemapGenerationException.php
@@ -5,4 +5,4 @@ namespace Drupal\xmlsitemap;
 /**
  * Exception thrown at sitemap generation.
  */
-class XmlSitemapGenerationException extends XmlSitemapException { }
+class XmlSitemapGenerationException extends XmlSitemapException {}
diff --git a/src/XmlSitemapGenerator.php b/src/XmlSitemapGenerator.php
index e0805dd..a03923a 100644
--- a/src/XmlSitemapGenerator.php
+++ b/src/XmlSitemapGenerator.php
@@ -9,6 +9,7 @@ use Drupal\Core\State\StateInterface;
 use Drupal\Core\Language\LanguageManagerInterface;
 use Drupal\Core\Url;
 use Psr\Log\LoggerInterface;
+use Drupal\Core\Database\Database;
 
 /**
  * XmlSitemap generator service class.
@@ -30,14 +31,14 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
    *
    * @var string
    */
-  public static $last_language;
+  public static $lastLanguage;
 
   /**
    * Memory used before generation process.
    *
    * @var integer
    */
-  public static $memory_start;
+  public static $memoryStart;
 
   /**
    * The xmlsitemap.settings config object.
@@ -74,6 +75,8 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
    *   The config factory object.
    * @param \Drupal\Core\State\StateInterface $state
    *   The state handler.
+   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
+   *   The language manager.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    */
@@ -87,23 +90,24 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function getPathAlias($path, $language) {
-    $query = db_select('url_alias', 'u');
+  public function getPathAlias($path, LanguageInterface $language) {
+    $language_id = $language->getId();
+    $query = Database::getConnection()->select('url_alias', 'u');
     $query->fields('u', array('source', 'alias'));
     if (!isset(static::$aliases)) {
       $query->condition('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED, '=');
       static::$aliases[LanguageInterface::LANGCODE_NOT_SPECIFIED] = $query->execute()->fetchAllKeyed();
     }
-    if ($language != LanguageInterface::LANGCODE_NOT_SPECIFIED && static::$last_language != $language) {
-      unset(static::$aliases[static::$last_language]);
-      $query->condition('langcode', $language, '=');
+    if ($language_id != LanguageInterface::LANGCODE_NOT_SPECIFIED && static::$lastLanguage != $language_id) {
+      unset(static::$aliases[static::$lastLanguage]);
+      $query->condition('langcode', $language_id, '=');
       $query->orderBy('pid');
-      static::$aliases[$language] = $query->execute()->fetchAllKeyed();
-      static::$last_language = $language;
+      static::$aliases[$language_id] = $query->execute()->fetchAllKeyed();
+      static::$lastLanguage = $language_id;
     }
 
-    if ($language != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset(static::$aliases[$language][$path])) {
-      return static::$aliases[$language][$path];
+    if ($language_id != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset(static::$aliases[$language_id][$path])) {
+      return static::$aliases[$language_id][$path];
     }
     elseif (isset(static::$aliases[LanguageInterface::LANGCODE_NOT_SPECIFIED][$path])) {
       return static::$aliases[LanguageInterface::LANGCODE_NOT_SPECIFIED][$path];
@@ -116,32 +120,32 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function regenerateBefore() {
+  public static function regenerateBefore() {
     // Attempt to increase the memory limit.
-    $this->setMemoryLimit();
+    self::setMemoryLimit();
 
-    if ($this->state->get('xmlsitemap_developer_mode')) {
-      $this->logger->notice('Starting XML sitemap generation. Memory usage: @memory-peak.', array(
-        array('@memory-peak' => format_size(memory_get_peak_usage(TRUE)),
-      )));
+    if (\Drupal::state()->get('xmlsitemap_developer_mode')) {
+      \Drupal::logger('xmlsitemap')->notice('Starting XML sitemap generation. Memory usage: @memory-peak.', [
+        '@memory-peak' => format_size(memory_get_peak_usage(TRUE)),
+      ]);
     }
   }
 
   /**
    * {@inheritdoc}
    */
-  public function getMemoryUsage($start = FALSE) {
+  public static function getMemoryUsage($start = FALSE) {
     $current = memory_get_peak_usage(TRUE);
-    if (!isset(self::$memory_start) || $start) {
-      self::$memory_start = $current;
+    if (!isset(self::$memoryStart) || $start) {
+      self::$memoryStart = $current;
     }
-    return $current - self::$memory_start;
+    return $current - self::$memoryStart;
   }
 
   /**
    * {@inheritdoc}
    */
-  public function getOptimalMemoryLimit() {
+  public static function getOptimalMemoryLimit() {
     $optimal_limit = &drupal_static(__FUNCTION__);
     if (!isset($optimal_limit)) {
       // Set the base memory amount from the provided core constant.
@@ -151,8 +155,8 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
       $optimal_limit += xmlsitemap_get_chunk_size() * 500;
 
       // Add memory for storing the url aliases.
-      if ($this->config->get('prefetch_aliases')) {
-        $aliases = db_query("SELECT COUNT(pid) FROM {url_alias}")->fetchField();
+      if (\Drupal::configFactory()->getEditable('xmlsitemap.settings')->get('prefetch_aliases')) {
+        $aliases = Database::getConnection()->query("SELECT COUNT(pid) FROM {url_alias}")->fetchField();
         $optimal_limit += $aliases * 250;
       }
     }
@@ -162,14 +166,14 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function setMemoryLimit($new_limit = NULL) {
+  public static function setMemoryLimit($new_limit = NULL) {
     $current_limit = @ini_get('memory_limit');
     if ($current_limit && $current_limit != -1) {
       if (!is_null($new_limit)) {
-        $new_limit = $this->getOptimalMemoryLimit();
+        $new_limit = self::getOptimalMemoryLimit();
       }
       if (Bytes::toInt($current_limit) < $new_limit) {
-        return @ini_set('memory_limit', $new_limit);
+        @ini_set('memory_limit', $new_limit);
       }
     }
   }
@@ -177,15 +181,15 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function generatePage(XmlSitemapInterface $sitemap, $page) {
+  public static function generatePage(XmlSitemapInterface $sitemap, $page) {
     try {
       $writer = new XmlSitemapWriter($sitemap, $page);
       $writer->startDocument();
       $writer->generateXML();
       $writer->endDocument();
     }
-    catch (Exception $e) {
-      $this->logger->error($e);
+    catch (\Exception $e) {
+      \Drupal::logger('xmlsitemap')->error($e);
       throw $e;
     }
 
@@ -198,7 +202,7 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   public function generateChunk(XmlSitemapInterface $sitemap, XmlSitemapWriter $writer, $chunk) {
     $lastmod_format = $this->config->get('lastmod_format');
 
-    $url_options = $sitemap->uri['options'];
+    $url_options = $sitemap->getUri()['options'];
     $url_options += array(
       'absolute' => TRUE,
       'xmlsitemap_base_url' => $this->state->get('xmlsitemap_base_url'),
@@ -209,8 +213,17 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
     $last_url = '';
     $link_count = 0;
 
-    $query = db_select('xmlsitemap', 'x');
-    $query->fields('x', array('loc', 'lastmod', 'changefreq', 'changecount', 'priority', 'language', 'access', 'status'));
+    $query = Database::getConnection()->select('xmlsitemap', 'x');
+    $query->fields('x', [
+      'loc',
+      'lastmod',
+      'changefreq',
+      'changecount',
+      'priority',
+      'language',
+      'access',
+      'status',
+    ]);
     $query->condition('x.access', 1);
     $query->condition('x.status', 1);
     $query->orderBy('x.language', 'DESC');
@@ -226,7 +239,7 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
     while ($link = $links->fetchAssoc()) {
       $link['language'] = $link['language'] != LanguageInterface::LANGCODE_NOT_SPECIFIED ? xmlsitemap_language_load($link['language']) : $url_options['language'];
       if ($url_options['alias']) {
-        $link['loc'] = $this->getPathAlias($link['loc'], $link['language']->getId());
+        $link['loc'] = $this->getPathAlias($link['loc'], $link['language']);
       }
       if ($url_options['base_url']) {
         $link['loc'] = rtrim($url_options['base_url'], '/') . '/' . ltrim($link['loc'], '/');
@@ -238,7 +251,7 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
       );
       // @todo Add a separate hook_xmlsitemap_link_url_alter() here?
       $link['loc'] = empty($link['loc']) ? '<front>' : $link['loc'];
-      $link_url = Url::fromUri($link['loc'], [], $link_options + $url_options)->toString();
+      $link_url = Url::fromUri($link['loc'], $link_options + $url_options)->toString();
 
       // Skip this link if it was a duplicate of the last one.
       // @todo Figure out a way to do this before generation so we can report
@@ -287,10 +300,9 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
       $writer->generateXML();
       $writer->endDocument();
     }
-    catch (Exception $e) {
+    catch (\Exception $e) {
       $this->logger->error($e);
       throw $e;
-      return FALSE;
     }
 
     return $writer->getSitemapElementCount();
@@ -299,12 +311,13 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function regenerateBatchGenerate($smid, array &$context) {
+  public static function regenerateBatchGenerate($smid, array &$context) {
     if (!isset($context['sandbox']['sitemap'])) {
+      /** @var \Drupal\xmlsitemap\XmlSitemapInterface $sitemap */
       $sitemap = xmlsitemap_sitemap_load($smid);
+      $sitemap->setChunks(1);
+      $sitemap->setLinks(0);
       $context['sandbox']['sitemap'] = $sitemap;
-      $context['sandbox']['sitemap']->setChunks(1);
-      $context['sandbox']['sitemap']->setLinks(0);
       $context['sandbox']['max'] = XMLSITEMAP_MAX_SITEMAP_LINKS;
 
       // Clear the cache directory for this sitemap before generating any files.
@@ -312,8 +325,17 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
       xmlsitemap_clear_directory($context['sandbox']['sitemap']);
     }
     $sitemap = &$context['sandbox']['sitemap'];
-    $links = $this->generatePage($sitemap, $sitemap->getChunks());
-    $context['message'] = t('Now generating %sitemap-url.', array('%sitemap-url' => Url::fromRoute('xmlsitemap.sitemap_xml', [], $sitemap->uri['options'] + array('query' => array('page' => $sitemap->getChunks())))->toString()));
+    $links = self::generatePage($sitemap, $sitemap->getChunks());
+    $context['message'] = t(
+      'Now generating %sitemap-url.',
+      [
+        '%sitemap-url' => Url::fromRoute(
+          'xmlsitemap.sitemap_xml',
+          [],
+          $sitemap->getUri()['options'] + ['query' => ['page' => $sitemap->getChunks()]]
+        )->toString(),
+      ]
+    );
 
     if ($links) {
       $sitemap->setLinks($sitemap->getLinks() + $links);
@@ -342,24 +364,30 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function regenerateBatchGenerateIndex($smid, array &$context) {
-    $sitemap = xmlsitemap_sitemap_load($smid);
+  public static function regenerateBatchGenerateIndex($smid, array &$context) {
+    /** @var \Drupal\xmlsitemap\XmlSitemapInterface $sitemap */
+    $sitemap = \Drupal::entityTypeManager()->getStorage('xmlsitemap')->load($smid);
     if ($sitemap != NULL && $sitemap->getChunks() > 1) {
-      $this->generateIndex($sitemap);
-      $context['message'] = t('Now generating sitemap index %sitemap-url.', array('%sitemap-url' => Url::fromRoute('xmlsitemap.sitemap_xml', [], $sitemap->uri['options'])->toString()));
+      self::generateIndex($sitemap);
+      $context['message'] = t(
+        'Now generating sitemap index %sitemap-url.',
+        [
+          '%sitemap-url' => Url::fromRoute('xmlsitemap.sitemap_xml', [], $sitemap->getUri()['options'])->toString(),
+        ]
+      );
     }
   }
 
   /**
    * {@inheritdoc}
    */
-  public function regenerateBatchFinished($success, $results, $operations, $elapsed) {
-    if ($success && $this->state->get('xmlsitemap_regenerate_needed') == FALSE) {
-      $this->state->set('xmlsitemap_generated_last', REQUEST_TIME);
+  public static function regenerateBatchFinished($success, $results, $operations, $elapsed) {
+    if ($success && \Drupal::state()->get('xmlsitemap_regenerate_needed') == FALSE) {
+      \Drupal::state()->set('xmlsitemap_generated_last', REQUEST_TIME);
       drupal_set_message(t('The sitemaps were regenerated.'));
 
       // Show a watchdog message that the sitemap was regenerated.
-      $this->logger->notice('Finished XML sitemap generation in @elapsed. Memory usage: @memory-peak.', ['@elapsed' => $elapsed, '@memory-peak' => format_size(memory_get_peak_usage(TRUE))]);
+      \Drupal::logger('xmlsitemap')->notice('Finished XML sitemap generation in @elapsed. Memory usage: @memory-peak.', ['@elapsed' => $elapsed, '@memory-peak' => format_size(memory_get_peak_usage(TRUE))]);
     }
     else {
       drupal_set_message(t('The sitemaps were not successfully regenerated.'), 'error');
@@ -369,9 +397,9 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function rebuildBatchClear(array $entity_type_ids, $save_custom, &$context) {
+  public static function rebuildBatchClear(array $entity_type_ids, $save_custom, &$context) {
     if (!empty($entity_type_ids)) {
-      $query = db_delete('xmlsitemap');
+      $query = Database::getConnection()->delete('xmlsitemap');
       $query->condition('type', $entity_type_ids, 'IN');
 
       // If we want to save the custom data, make sure to exclude any links
@@ -390,7 +418,7 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function rebuildBatchFetch($entity_type_id, &$context) {
+  public static function rebuildBatchFetch($entity_type_id, &$context) {
     if (!isset($context['sandbox']['info'])) {
       $context['sandbox']['info'] = xmlsitemap_get_link_info($entity_type_id);
       $context['sandbox']['progress'] = 0;
@@ -419,8 +447,8 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
     // PostgreSQL cannot have the ORDERED BY in the count query.
     $query->sort($entity_type->getKey('id'));
 
-    // get batch limit
-    $limit = $this->config->get('batch_limit');
+    // Get batch limit.
+    $limit = \Drupal::config('xmlsitemap.settings')->get('batch_limit');
     $query->range(0, $limit);
 
     $result = $query->execute();
@@ -428,7 +456,15 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
     $info['xmlsitemap']['process callback']($entity_type_id, $result);
     $context['sandbox']['last_id'] = end($result);
     $context['sandbox']['progress'] += count($result);
-    $context['message'] = t('Now processing %entity_type_id @last_id (@progress of @count).', array('%entity_type_id' => $entity_type_id, '@last_id' => $context['sandbox']['last_id'], '@progress' => $context['sandbox']['progress'], '@count' => $context['sandbox']['max']));
+    $context['message'] = t(
+      'Now processing %entity_type_id @last_id (@progress of @count).',
+      [
+        '%entity_type_id' => $entity_type_id,
+        '@last_id' => $context['sandbox']['last_id'],
+        '@progress' => $context['sandbox']['progress'],
+        '@count' => $context['sandbox']['max'],
+      ]
+    );
 
     if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
       $context['finished'] = 1;
@@ -441,7 +477,7 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function rebuildBatchFinished($success, $results, $operations, $elapsed) {
+  public static function rebuildBatchFinished($success, $results, $operations, $elapsed) {
     if ($success && !\Drupal::state()->get('xmlsitemap_rebuild_needed', FALSE)) {
       drupal_set_message(t('The sitemap links were rebuilt.'));
     }
@@ -453,18 +489,122 @@ class XmlSitemapGenerator implements XmlSitemapGeneratorInterface {
   /**
    * {@inheritdoc}
    */
-  public function batchVariableSet(array $variables) {
+  public static function batchVariableSet(array $variables) {
+    /** @var \Drupal\Core\Config\Config $config */
+    $config = \Drupal::configFactory()->getEditable('xmlsitemap.settings');
+    $state = \Drupal::state();
+
     $state_variables = xmlsitemap_state_variables();
-    $config_variables = xmlsitemap_config_variables();
     foreach ($variables as $variable => $value) {
       if (isset($state_variables[$variable])) {
-        $this->state->set($variable, $value);
+        $state->set($variable, $value);
       }
       else {
-        $this->config->set($variable, $value);
+        $config->set($variable, $value);
       }
     }
-    $this->config->save();
+    $config->save();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function createRebuildBatch(array $entity_type_ids, $save_custom = FALSE) {
+    $batch = [
+      'operations' => [],
+      'finished' => [self::class, 'rebuildBatchFinished'],
+      'title' => t('Rebuilding Sitemap'),
+    ];
+
+    // Set the rebuild flag in case something fails during the rebuild.
+    $batch['operations'][] = [
+      [self::class, 'batchVariableSet'],
+      [
+        ['xmlsitemap_rebuild_needed' => TRUE],
+      ],
+    ];
+
+    // Purge any links first.
+    $batch['operations'][] = [
+      [self::class, 'rebuildBatchClear'],
+      [
+        $entity_type_ids,
+        (bool) $save_custom,
+      ],
+    ];
+
+    // Fetch all the sitemap links and save them to the {xmlsitemap} table.
+    foreach ($entity_type_ids as $entity_type_id) {
+      $info = xmlsitemap_get_link_info($entity_type_id);
+      $batch['operations'][] = [$info['xmlsitemap']['rebuild callback'], [$entity_type_id]];
+    }
+
+    // Clear the rebuild flag.
+    $batch['operations'][] = [
+      [self::class, 'batchVariableSet'],
+      [
+        ['xmlsitemap_rebuild_needed' => FALSE],
+      ],
+    ];
+
+    // Add the regeneration batch.
+    $regenerate_batch = $this->createRegenerateBatch();
+    $batch['operations'] = array_merge($batch['operations'], $regenerate_batch['operations']);
+
+    return $batch;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function createRegenerateBatch(array $smids = []) {
+    if (empty($smids)) {
+      $sitemaps = \Drupal::entityTypeManager()->getStorage('xmlsitemap')->loadMultiple();
+      foreach ($sitemaps as $sitemap) {
+        $smids[] = $sitemap->id();
+      }
+    }
+
+    $t = 't';
+    $batch = [
+      'operations' => [],
+      'error_message' => $t('An error has occurred.'),
+      'finished' => [self::class, 'regenerateBatchFinished'],
+      'title' => t('Regenerating Sitemap'),
+    ];
+
+    // Set the regenerate flag in case something fails during file generation.
+    $batch['operations'][] = [
+      [self::class, 'batchVariableSet'],
+      [
+        ['xmlsitemap_regenerate_needed' => TRUE],
+      ],
+    ];
+
+    // @todo Get rid of this batch operation.
+    $batch['operations'][] = [[self::class, 'regenerateBefore'], []];
+
+    // Generate all the sitemap pages for each context.
+    foreach ($smids as $smid) {
+      $batch['operations'][] = [
+        [self::class, 'regenerateBatchGenerate'],
+        [$smid],
+      ];
+      $batch['operations'][] = [
+        [self::class, 'regenerateBatchGenerateIndex'],
+        [$smid],
+      ];
+    }
+
+    // Clear the regeneration flag.
+    $batch['operations'][] = [
+      [self::class, 'batchVariableSet'],
+      [
+        ['xmlsitemap_regenerate_needed' => FALSE],
+      ],
+    ];
+
+    return $batch;
   }
 
 }
diff --git a/src/XmlSitemapGeneratorInterface.php b/src/XmlSitemapGeneratorInterface.php
index 5f35a3a..4c952c3 100644
--- a/src/XmlSitemapGeneratorInterface.php
+++ b/src/XmlSitemapGeneratorInterface.php
@@ -2,6 +2,8 @@
 
 namespace Drupal\xmlsitemap;
 
+use Drupal\Core\Language\LanguageInterface;
+
 /**
  * Provides an interface defining a XmlSitemapGenerator service.
  */
@@ -16,25 +18,26 @@ interface XmlSitemapGeneratorInterface {
    *
    * @param string $path
    *   An internal Drupal path.
-   * @param Drupal\Core\Language\LanguageInterface $language
+   * @param \Drupal\Core\Language\LanguageInterface $language
    *   A language code to use when looking up the paths.
    */
-  public function getPathAlias($path, $language);
+  public function getPathAlias($path, LanguageInterface $language);
 
   /**
    * Perform operations before rebuilding the sitemap.
    */
-  public function regenerateBefore();
+  public static function regenerateBefore();
 
   /**
    * Get how much memory was used.
    *
    * @param bool $start
+   *   Set start.
    *
-   * @return integer
+   * @return int
    *   Used memory.
    */
-  public function getMemoryUsage($start = FALSE);
+  public static function getMemoryUsage($start = FALSE);
 
   /**
    * Calculate the optimal PHP memory limit for sitemap generation.
@@ -42,29 +45,29 @@ interface XmlSitemapGeneratorInterface {
    * This function just makes a guess. It does not take into account
    * the currently loaded modules.
    *
-   * @return integer
+   * @return int
    *   Optimal memory limit.
    */
-  public function getOptimalMemoryLimit();
+  public static function getOptimalMemoryLimit();
 
   /**
    * Calculate the optimal memory level for sitemap generation.
    *
-   * @param $new_limit
+   * @param int $new_limit
    *   An optional PHP memory limit in bytes. If not provided, the value of
    *   getOptimalMemoryLimit() will be used.
    */
-  public function setMemoryLimit($new_limit = NULL);
+  public static function setMemoryLimit($new_limit = NULL);
 
   /**
    * Generate one page (chunk) of the sitemap.
    *
-   * @param $sitemap
+   * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
    *   An unserialized data array for an XML sitemap.
-   * @param $page
+   * @param int $page
    *   An integer of the specific page of the sitemap to generate.
    */
-  public function generatePage(XmlSitemapInterface $sitemap, $page);
+  public static function generatePage(XmlSitemapInterface $sitemap, $page);
 
   /**
    * Generates one chunk of the sitemap.
@@ -73,15 +76,15 @@ interface XmlSitemapGeneratorInterface {
    *   An unserialized data array for an XML sitemap.
    * @param \Drupal\xmlsitemap\XmlSitemapWriter $writer
    *   XML writer object.
-   * @param int $pageAn integer of the specific page of the sitemap to generate.
-   *   An integer of the specific page of the sitemap to generate.
+   * @param int $chunk
+   *   Current chunk.
    */
   public function generateChunk(XmlSitemapInterface $sitemap, XmlSitemapWriter $writer, $chunk);
 
   /**
    * Generate the index sitemap.
    *
-   * @param $sitemap
+   * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
    *   An unserialized data array for an XML sitemap.
    */
   public function generateIndex(XmlSitemapInterface $sitemap);
@@ -94,7 +97,7 @@ interface XmlSitemapGeneratorInterface {
    * @param array $context
    *   Sitemap context.
    */
-  public function regenerateBatchGenerate($smid, array &$context);
+  public static function regenerateBatchGenerate($smid, array &$context);
 
   /**
    * Batch callback; generate the index page of a sitemap.
@@ -104,7 +107,7 @@ interface XmlSitemapGeneratorInterface {
    * @param array $context
    *   Sitemap context.
    */
-  public function regenerateBatchGenerateIndex($smid, array &$context);
+  public static function regenerateBatchGenerateIndex($smid, array &$context);
 
   /**
    * Batch callback; sitemap regeneration finished.
@@ -115,10 +118,10 @@ interface XmlSitemapGeneratorInterface {
    *   Results for the regeneration process.
    * @param array $operations
    *   Operations performed.
-   * @param int $elapsedTime elapsed.
+   * @param int $elapsed
    *   Time elapsed.
    */
-  public function regenerateBatchFinished($success, $results, $operations, $elapsed);
+  public static function regenerateBatchFinished($success, $results, $operations, $elapsed);
 
   /**
    * Batch callback; clear sitemap links for entites.
@@ -130,7 +133,7 @@ interface XmlSitemapGeneratorInterface {
    * @param array $context
    *   Context to be rebuilt.
    */
-  public function rebuildBatchClear(array $entity_type_ids, $save_custom, &$context);
+  public static function rebuildBatchClear(array $entity_type_ids, $save_custom, &$context);
 
   /**
    * Batch callback; fetch and add the sitemap links for a specific entity.
@@ -140,7 +143,7 @@ interface XmlSitemapGeneratorInterface {
    * @param array $context
    *   Context to be rebuilt.
    */
-  public function rebuildBatchFetch($entity_type_id, &$context);
+  public static function rebuildBatchFetch($entity_type_id, &$context);
 
   /**
    * Batch callback; sitemap rebuild finished.
@@ -151,10 +154,10 @@ interface XmlSitemapGeneratorInterface {
    *   Results for the regeneration process.
    * @param array $operations
    *   Operations performed.
-   * @param int $elapsedTime elapsed.
+   * @param int $elapsed
    *   Time elapsed.
    */
-  public function rebuildBatchFinished($success, $results, $operations, $elapsed);
+  public static function rebuildBatchFinished($success, $results, $operations, $elapsed);
 
   /**
    * Set variables during the batch process.
@@ -162,5 +165,31 @@ interface XmlSitemapGeneratorInterface {
    * @param array $variables
    *   Variables to be set.
    */
-  public function batchVariableSet(array $variables);
+  public static function batchVariableSet(array $variables);
+
+  /**
+   * Batch information callback for rebuilding the sitemap data.
+   *
+   * @param array $entity_type_ids
+   *   Entity types to rebuild.
+   * @param bool $save_custom
+   *   Save custom data.
+   *
+   * @return array
+   *   Batch array.
+   */
+  public function createRebuildBatch(array $entity_type_ids, $save_custom = FALSE);
+
+  /**
+   * Batch information callback for regenerating the sitemap files.
+   *
+   * @param int[] $smids
+   *   An optional array of XML sitemap IDs. If not provided, it will load all
+   *   existing XML sitemaps.
+   *
+   * @return array
+   *   Batch array.
+   */
+  public function createRegenerateBatch(array $smids = []);
+
 }
diff --git a/src/XmlSitemapIndexWriter.php b/src/XmlSitemapIndexWriter.php
index 170a333..449619d 100644
--- a/src/XmlSitemapIndexWriter.php
+++ b/src/XmlSitemapIndexWriter.php
@@ -41,7 +41,7 @@ class XmlSitemapIndexWriter extends XmlSitemapWriter {
   public function generateXML() {
     $lastmod_format = \Drupal::config('xmlsitemap.settings')->get('lastmod_format');
 
-    $url_options = $this->sitemap->uri['options'];
+    $url_options = $this->sitemap->getUri()['options'];
     $url_options += array(
       'absolute' => TRUE,
       'xmlsitemap_base_url' => \Drupal::state()->get('xmlsitemap_base_url'),
@@ -49,7 +49,7 @@ class XmlSitemapIndexWriter extends XmlSitemapWriter {
       'alias' => TRUE,
     );
 
-    for ($i = 1; $i <= $this->sitemap->chunks; $i++) {
+    for ($i = 1; $i <= $this->sitemap->getChunks(); $i++) {
       $url_options['query']['page'] = $i;
       $element = array(
         'loc' => Url::fromRoute('xmlsitemap.sitemap_xml', [], $url_options),
diff --git a/src/XmlSitemapInterface.php b/src/XmlSitemapInterface.php
index e6cea64..e2fd343 100644
--- a/src/XmlSitemapInterface.php
+++ b/src/XmlSitemapInterface.php
@@ -115,18 +115,18 @@ interface XmlSitemapInterface extends ConfigEntityInterface {
   /**
    * Sets the context for the sitemap.
    *
-   * @param string $context
+   * @param array $context
    *   The context.
    *
    * @return \Drupal\xmlsitemap\XmlSitemapInterface
    *   The class instance that this method is called on.
    */
-  public function setContext($context);
+  public function setContext($context = []);
 
   /**
    * Sets if the sitemap was updated.
    *
-   * @param updated
+   * @param bool $updated
    *   Check is sitemap was updated.
    *
    * @return \Drupal\xmlsitemap\XmlSitemapInterface
@@ -146,4 +146,12 @@ interface XmlSitemapInterface extends ConfigEntityInterface {
    */
   public static function loadByContext(array $context = NULL);
 
+  /**
+   * Return the sitemap URI data.
+   *
+   * @return array
+   *   Sitemap URI data.
+   */
+  public function getUri();
+
 }
diff --git a/src/XmlSitemapLinkStorage.php b/src/XmlSitemapLinkStorage.php
index db448de..581b9a5 100644
--- a/src/XmlSitemapLinkStorage.php
+++ b/src/XmlSitemapLinkStorage.php
@@ -2,12 +2,15 @@
 
 namespace Drupal\xmlsitemap;
 
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\Merge;
 use Drupal\Core\Language\LanguageInterface;
 use Drupal\Core\Extension\ModuleHandlerInterface;
 use Drupal\Core\State\StateInterface;
 use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Session\AnonymousUserSession;
+use Drupal\Core\Url;
+use Drupal\Core\Entity\Exception\UndefinedLinkTemplateException;
 
 /**
  * XmlSitemap link storage service class.
@@ -49,6 +52,15 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     $this->anonymousUser = new AnonymousUserSession();
   }
 
+  /**
+   * Create the link and respective meta data and attach to entity.
+   *
+   * @param EntityInterface $entity
+   *   Entity to process.
+   *
+   * @return EntityInterface
+   *   Entity with attached xmlsitemap data.
+   */
   public function create(EntityInterface $entity) {
     if (!isset($entity->xmlsitemap)) {
       $entity->xmlsitemap = array();
@@ -58,7 +70,14 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     }
 
     $settings = xmlsitemap_link_bundle_load($entity->getEntityTypeId(), $entity->bundle());
-    $uri = $entity->url();
+    try {
+      $url = $entity->toUrl()->toString();
+    }
+    catch (UndefinedLinkTemplateException $e) {
+      // This entity type has no "canonical" link.
+      // TODO: This should be handled on entity type level.
+      $url = Url::fromRoute('<front>')->toString();
+    }
     $entity->xmlsitemap += array(
       'type' => $entity->getEntityTypeId(),
       'id' => (string) $entity->id(),
@@ -76,9 +95,8 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
       $entity->xmlsitemap['lastmod'] = $entity->getChangedTime();
     }
 
-    $url = $entity->url();
     // The following values must always be checked because they are volatile.
-    $entity->xmlsitemap['loc'] = $uri;
+    $entity->xmlsitemap['loc'] = $url;
     $entity->xmlsitemap['access'] = isset($url) && $entity->access('view', $this->anonymousUser);
     $language = $entity->language();
     $entity->xmlsitemap['language'] = !empty($language) ? $language->getId() : LanguageInterface::LANGCODE_NOT_SPECIFIED;
@@ -108,10 +126,28 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     // Temporary validation checks.
     // @todo Remove in final?
     if ($link['priority'] < 0 || $link['priority'] > 1) {
-      trigger_error(t('Invalid sitemap link priority %priority.<br />@link', array('%priority' => $link['priority'], '@link' => var_export($link, TRUE))), E_USER_ERROR);
+      trigger_error(
+        t(
+          'Invalid sitemap link priority %priority.<br />:link',
+          [
+            '%priority' => $link['priority'],
+            ':link' => var_export($link, TRUE),
+          ]
+        ),
+        E_USER_ERROR
+      );
     }
     if ($link['changecount'] < 0) {
-      trigger_error(t('Negative changecount value. Please report this to <a href="@516928">@516928</a>.<br />@link', array('@516928' => 'http://drupal.org/node/516928', '@link' => var_export($link, TRUE))), E_USER_ERROR);
+      trigger_error(
+        t(
+          'Negative changecount value. Please report this to <a href=":516928">:516928</a>.<br />:link',
+          [
+            ':516928' => 'http://drupal.org/node/516928',
+            ':link' => var_export($link, TRUE),
+          ]
+        ),
+        E_USER_ERROR
+      );
       $link['changecount'] = 0;
     }
 
@@ -137,8 +173,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
       ))
       ->execute();
 
-    switch($queryStatus)
-    {
+    switch ($queryStatus) {
       case Merge::STATUS_INSERT:
         $this->moduleHandler->invokeAll('xmlsitemap_link_insert', array($link));
         break;
@@ -159,7 +194,9 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
 
     if ($original_link === NULL) {
       // Load only the fields necessary for data to be changed in the sitemap.
-      $original_link = db_query_range("SELECT loc, access, status, lastmod, priority, changefreq, changecount, language FROM {xmlsitemap} WHERE type = :type AND id = :id", 0, 1, array(':type' => $link['type'], ':id' => $link['id']))->fetchAssoc();
+      $original_link = Database::getConnection()
+        ->queryRange("SELECT loc, access, status, lastmod, priority, changefreq, changecount, language FROM {xmlsitemap} WHERE type = :type AND id = :id", 0, 1, [':type' => $link['type'], ':id' => $link['id']])
+        ->fetchAssoc();
     }
 
     if (!$original_link) {
@@ -174,7 +211,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
         $changed = TRUE;
       }
       elseif ($original_link['access'] && $original_link['status'] && array_diff_assoc($original_link, $link)) {
-        // Changing a visible link
+        // Changing a visible link.
         $changed = TRUE;
       }
     }
@@ -194,7 +231,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     $conditions['status'] = (!empty($updates['status']) && empty($conditions['status'])) ? 0 : 1;
     $conditions['access'] = (!empty($updates['access']) && empty($conditions['access'])) ? 0 : 1;
 
-    $query = db_select('xmlsitemap');
+    $query = Database::getConnection()->select('xmlsitemap');
     $query->addExpression('1');
     foreach ($conditions as $field => $value) {
       $query->condition($field, $value);
@@ -226,7 +263,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     }
 
     // @todo Add a hook_xmlsitemap_link_delete() hook invoked here.
-    $query = db_delete('xmlsitemap');
+    $query = Database::getConnection()->delete('xmlsitemap');
     foreach ($conditions as $field => $value) {
       $query->condition($field, $value);
     }
@@ -245,7 +282,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
     }
 
     // Process updates.
-    $query = db_update('xmlsitemap');
+    $query = Database::getConnection()->update('xmlsitemap');
     $query->fields($updates);
     foreach ($conditions as $field => $value) {
       $query->condition($field, $value);
@@ -266,7 +303,7 @@ class XmlSitemapLinkStorage implements XmlSitemapLinkStorageInterface {
    * {@inheritdoc}
    */
   public function loadMultiple(array $conditions = array()) {
-    $query = db_select('xmlsitemap');
+    $query = Database::getConnection()->select('xmlsitemap');
     $query->fields('xmlsitemap');
 
     foreach ($conditions as $field => $value) {
diff --git a/xmlsitemap.module b/xmlsitemap.module
index 6f031be..9bc6f26 100644
--- a/xmlsitemap.module
+++ b/xmlsitemap.module
@@ -1,24 +1,18 @@
 <?php
-
-/**
- * @defgroup xmlsitemap XML sitemap
- */
-
 /**
  * @file
  * Main file for the xmlsitemap module.
  */
 
 use Drupal\Component\Utility\Crypt;
-use Drupal\Component\Utility\SafeMarkup;
 use Drupal\Component\Utility\Unicode;
 use Drupal\Component\Utility\UrlHelper;
-use Drupal\Core\Render\Element;
 use Drupal\Core\Entity\EntityForm;
 use Drupal\Core\Entity\EntityInterface;
-use Drupal\Core\Session\AnonymousUserSession;
 use Drupal\Core\Routing\RouteMatchInterface;
+use Drupal\Core\Database\Database;
 use Drupal\Core\Database\Query\AlterableInterface;
+use Drupal\Core\Database\Query\Condition;
 use Drupal\Core\Entity\Query\QueryInterface;
 use Drupal\Core\Entity\Query\QueryException;
 use Drupal\Core\Cache\Cache;
@@ -30,7 +24,6 @@ use Drupal\xmlsitemap\XmlSitemapInterface;
 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 use Symfony\Component\HttpFoundation\Response;
 
-
 /**
  * The maximum number of links in one sitemap chunk file.
  */
@@ -45,15 +38,15 @@ const XMLSITEMAP_MAX_SITEMAP_FILESIZE = 10485760;
  * Xmlsitemap Frequencies.
  */
 const XMLSITEMAP_FREQUENCY_YEARLY = 31449600;
-// 60 * 60 * 24 * 7 * 52
+// 60 * 60 * 24 * 7 * 52.
 const XMLSITEMAP_FREQUENCY_MONTHLY = 2419200;
-// 60 * 60 * 24 * 7 * 4
+// 60 * 60 * 24 * 7 * 4.
 const XMLSITEMAP_FREQUENCY_WEEKLY = 604800;
-// 60 * 60 * 24 * 7
+// 60 * 60 * 24 * 7.
 const XMLSITEMAP_FREQUENCY_DAILY = 86400;
-// 60 * 60 * 24
+// 60 * 60 * 24.
 const XMLSITEMAP_FREQUENCY_HOURLY = 3600;
-// 60 * 60
+// 60 * 60.
 const XMLSITEMAP_FREQUENCY_ALWAYS = 60;
 
 /**
@@ -124,7 +117,7 @@ function xmlsitemap_help($route_name, RouteMatchInterface $route_match) {
     case 'xmlsitemap.entities_settings':
     case 'entity.xmlsitemap.edit_form':
     case 'entity.xmlsitemap.delete_form':
-      return;
+      return NULL;
 
     case 'xmlsitemap.admin_search':
       break;
@@ -219,6 +212,8 @@ function xmlsitemap_robotstxt() {
     $robotstxt[] = 'Sitemap: ' . Url::fromUri($path, $uri['options'])->toString();
     return $robotstxt;
   }
+
+  return NULL;
 }
 
 /**
@@ -273,7 +268,7 @@ function xmlsitemap_var($name, $default = NULL) {
 
   // @todo Remove when stable.
   if (!isset($defaults[$name])) {
-    trigger_error(strtr('Default variable for %variable not found.', array('%variable' => drupal_placeholder($name))));
+    trigger_error(strtr('Default variable for %variable not found.', ['%variable' => $name]));
   }
 
   if (\Drupal::state()->get($name, NULL) === NULL) {
@@ -292,10 +287,10 @@ function xmlsitemap_var($name, $default = NULL) {
 /**
  * Load an XML sitemap array from the database.
  *
- * @param $smid
+ * @param int $smid
  *   An XML sitemap ID.
  *
- * @return
+ * @return array
  *   The XML sitemap object.
  */
 function xmlsitemap_sitemap_load($smid) {
@@ -306,12 +301,12 @@ function xmlsitemap_sitemap_load($smid) {
 /**
  * Load multiple XML sitemaps from the database.
  *
- * @param $smids
+ * @param int[] $smids
  *   An array of XML sitemap IDs, or FALSE to load all XML sitemaps.
- * @param $conditions
+ * @param array $conditions
  *   An array of conditions in the form 'field' => $value.
  *
- * @return
+ * @return array
  *   An array of XML sitemap objects.
  */
 function xmlsitemap_sitemap_load_multiple($smids = array(), array $conditions = array()) {
@@ -321,6 +316,8 @@ function xmlsitemap_sitemap_load_multiple($smids = array(), array $conditions =
   else {
     $conditions['smid'] = NULL;
   }
+
+  /** @var \Drupal\xmlsitemap\XmlSitemapLinkStorageInterface $storage */
   $storage = Drupal::entityTypeManager()->getStorage('xmlsitemap');
 
   $sitemaps = $storage->loadMultiple($conditions['smid']);
@@ -338,25 +335,29 @@ function xmlsitemap_sitemap_load_multiple($smids = array(), array $conditions =
 /**
  * Save changes to an XML sitemap or add a new XML sitemap.
  *
- * @param $sitemap
+ * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
  *   The XML sitemap array to be saved. If $sitemap->smid is omitted, a new
  *   XML sitemap will be added.
  *
+ * @return \Drupal\xmlsitemap\XmlSitemapInterface
+ *   The saved sitemap.
+ *
  * @todo Save the sitemap's URL as a column?
  */
 function xmlsitemap_sitemap_save(XmlSitemapInterface $sitemap) {
-  $context = $sitemap->context;
+  $context = $sitemap->getContext();
   if (!isset($context) || !$context) {
-    $sitemap->context = array();
+    $sitemap->setContext([]);
   }
 
   // Make sure context is sorted before saving the hash.
   $sitemap->setOriginalId($sitemap->isNew() ? NULL : $sitemap->getId());
   $sitemap->setId(xmlsitemap_sitemap_get_context_hash($context));
+
   // If the context was changed, we need to perform additional actions.
   if (!$sitemap->isNew() && $sitemap->getId() != $sitemap->getOriginalId()) {
     // Rename the files directory so the sitemap does not break.
-    $old_sitemap = (object) array('smid' => $sitemap->old_smid);
+    $old_sitemap = (object) array('smid' => $sitemap->getOriginalId());
     $old_dir = xmlsitemap_get_directory($old_sitemap);
     $new_dir = xmlsitemap_get_directory($sitemap);
     xmlsitemap_directory_move($old_dir, $new_dir);
@@ -382,7 +383,7 @@ function xmlsitemap_sitemap_delete($smid) {
 /**
  * Delete multiple XML sitemaps.
  *
- * @param array $smids
+ * @param int[] $smids
  *   An array of XML sitemap IDs.
  */
 function xmlsitemap_sitemap_delete_multiple(array $smids) {
@@ -399,9 +400,9 @@ function xmlsitemap_sitemap_delete_multiple(array $smids) {
 /**
  * Return the expected file path for a specific sitemap chunk.
  *
- * @param $sitemap
+ * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
  *   An XmlSitemapInterface sitemap object.
- * @param $chunk
+ * @param int|string $chunk
  *   An optional specific chunk in the sitemap. Defaults to the index page.
  *
  * @return string
@@ -416,6 +417,9 @@ function xmlsitemap_sitemap_get_file(XmlSitemapInterface $sitemap, $chunk = 'ind
  *
  * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
  *   The XML sitemap object.
+ *
+ * @return int
+ *   Max file size.
  */
 function xmlsitemap_sitemap_get_max_filesize(XmlSitemapInterface $sitemap) {
   $dir = xmlsitemap_get_directory($sitemap);
@@ -431,6 +435,7 @@ function xmlsitemap_sitemap_get_max_filesize(XmlSitemapInterface $sitemap) {
  *
  * @param array $context
  *   Context to be hashed.
+ *
  * @return string
  *   Hash string for the context.
  */
@@ -444,14 +449,15 @@ function xmlsitemap_sitemap_get_context_hash(array &$context) {
  *
  * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
  *   The sitemap represented by and XmlSitemapInterface object.
- * @return
+ *
+ * @return array
  *   An array containing the 'path' and 'options' keys used to build the uri of
  *   the XML sitemap, and matching the signature of url().
  */
 function xmlsitemap_sitemap_uri(XmlSitemapInterface $sitemap) {
   $uri['path'] = 'sitemap.xml';
-  $uri['options'] = \Drupal::moduleHandler()->invokeAll('xmlsitemap_context_url_options', array($sitemap->context));
-  $context = $sitemap->context;
+  $uri['options'] = \Drupal::moduleHandler()->invokeAll('xmlsitemap_context_url_options', array($sitemap->getContext()));
+  $context = $sitemap->getContext();
   \Drupal::moduleHandler()->alter('xmlsitemap_context_url_options', $uri['options'], $context);
   $uri['options'] += array(
     'absolute' => TRUE,
@@ -461,7 +467,13 @@ function xmlsitemap_sitemap_uri(XmlSitemapInterface $sitemap) {
 }
 
 /**
- * @} End of "defgroup xmlsitemap_api"
+ * Get the directory URI for a sitemap.
+ *
+ * @param \Drupal\xmlsitemap\XmlSitemapInterface|NULL $sitemap
+ *   A sitemap.
+ *
+ * @return string
+ *   URI to directory of sitemap.
  */
 function xmlsitemap_get_directory(XmlSitemapInterface $sitemap = NULL) {
   $directory = &drupal_static(__FUNCTION__);
@@ -479,6 +491,12 @@ function xmlsitemap_get_directory(XmlSitemapInterface $sitemap = NULL) {
 
 /**
  * Check that the sitemap files directory exists and is writable.
+ *
+ * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
+ *   Sitemap to check.
+ *
+ * @return bool
+ *   Directory exists or not.
  */
 function xmlsitemap_check_directory(XmlSitemapInterface $sitemap = NULL) {
   $directory = xmlsitemap_get_directory($sitemap);
@@ -489,6 +507,12 @@ function xmlsitemap_check_directory(XmlSitemapInterface $sitemap = NULL) {
   return $result;
 }
 
+/**
+ * Recursively check directories for all Sitemaps.
+ *
+ * @return array
+ *   Results.
+ */
 function xmlsitemap_check_all_directories() {
   $directories = array();
 
@@ -534,17 +558,19 @@ function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete
  *   A string specifying the filepath or URI of the original directory.
  * @param string $new_dir
  *   A string specifying the filepath or URI of the new directory.
- * @param int $replaceReplace behavior when the destination file already exists.
+ * @param int $replace
  *   Replace behavior when the destination file already exists.
  *
  * @return bool
  *   TRUE if the directory was moved successfully. FALSE otherwise.
  */
 function xmlsitemap_directory_move($old_dir, $new_dir, $replace = FILE_EXISTS_REPLACE) {
+  /** @var \Drupal\Core\File\FileSystem $file_system_service */
+  $file_system_service = \Drupal::service('file_system');
   $success = file_prepare_directory($new_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
 
-  $old_path = drupal_realpath($old_dir);
-  $new_path = drupal_realpath($new_dir);
+  $old_path = $file_system_service->realpath($old_dir);
+  $new_path = $file_system_service->realpath($new_dir);
   if (!is_dir($old_path) || !is_dir($new_path) || !$success) {
     return FALSE;
   }
@@ -556,7 +582,7 @@ function xmlsitemap_directory_move($old_dir, $new_dir, $replace = FILE_EXISTS_RE
   }
 
   // The remove the directory.
-  $success &= drupal_rmdir($old_dir);
+  $success &= $file_system_service->rmdir($old_dir);
   return $success;
 }
 
@@ -576,8 +602,10 @@ function xmlsitemap_directory_move($old_dir, $new_dir, $replace = FILE_EXISTS_RE
  *   TRUE if operation was successful, FALSE otherwise.
  */
 function _xmlsitemap_delete_recursive($path, $delete_root = FALSE) {
+  /** @var \Drupal\Core\File\FileSystem $file_system_service */
+  $file_system_service = \Drupal::service('file_system');
   // Resolve streamwrapper URI to local path.
-  $path = drupal_realpath($path);
+  $path = $file_system_service->realpath($path);
   if (is_dir($path)) {
     $dir = dir($path);
     while (($entry = $dir->read()) !== FALSE) {
@@ -588,7 +616,7 @@ function _xmlsitemap_delete_recursive($path, $delete_root = FALSE) {
       file_unmanaged_delete_recursive($entry_path, NULL);
     }
     $dir->close();
-    return $delete_root ? drupal_rmdir($path) : TRUE;
+    return $delete_root ? $file_system_service->rmdir($path) : TRUE;
   }
   return file_unmanaged_delete($path);
 }
@@ -596,10 +624,10 @@ function _xmlsitemap_delete_recursive($path, $delete_root = FALSE) {
 /**
  * Returns information about supported sitemap link types.
  *
- * @param $type
+ * @param string $type
  *   (optional) The link type to return information for. If omitted,
  *   information for all link types is returned.
- * @param $reset
+ * @param bool $reset
  *   (optional) Boolean whether to reset the static cache and do nothing. Only
  *   used for tests.
  *
@@ -657,7 +685,7 @@ function xmlsitemap_get_link_info($type = NULL, $reset = FALSE) {
           ],
         );
         if (!isset($info['xmlsitemap']['rebuild callback']) && !empty($info['base table']) && $entity_types[$key]->getKey('id')) {
-          $info['xmlsitemap']['rebuild callback'] = 'xmlsitemap_rebuild_batch_fetch';
+          $info['xmlsitemap']['rebuild callback'] = ['\Drupal\xmlsitemap\XmlSitemapGenerator', 'rebuildBatchFetch'];
         }
         foreach ($info['bundles'] as $bundle => &$bundle_info) {
           $bundle_info += array(
@@ -716,8 +744,12 @@ function xmlsitemap_get_link_type_indexed_status($entity_type_id, $bundle = '')
   $info = xmlsitemap_get_link_info($entity_type_id);
   $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
 
-  $status['indexed'] = db_query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", array(':entity' => $entity_type_id, ':bundle' => $bundle))->fetchField();
-  $status['visible'] = db_query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle AND status = 1 AND access = 1", array(':entity' => $entity_type_id, ':bundle' => $bundle))->fetchField();
+  $status['indexed'] = Database::getConnection()
+    ->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", [':entity' => $entity_type_id, ':bundle' => $bundle])
+    ->fetchField();
+  $status['visible'] = Database::getConnection()
+    ->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle AND status = 1 AND access = 1", [':entity' => $entity_type_id, ':bundle' => $bundle])
+    ->fetchField();
 
   try {
     $query = \Drupal::entityQuery($entity_type_id);
@@ -752,18 +784,21 @@ function xmlsitemap_get_link_type_indexed_status($entity_type_id, $bundle = '')
  *   Settings to be saved.
  * @param bool $update_links
  *   Update bundle links after settings are saved.
- *
- * @return array
- *   Info about sitemap link.
  */
 function xmlsitemap_link_bundle_settings_save($entity, $bundle, array $settings, $update_links = TRUE) {
   if ($update_links) {
     $old_settings = xmlsitemap_link_bundle_load($entity, $bundle);
     if ($settings['status'] != $old_settings['status']) {
-      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('status' => $settings['status']), array('type' => $entity, 'subtype' => $bundle, 'status_override' => 0));
+      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(
+        ['status' => $settings['status']],
+        ['type' => $entity, 'subtype' => $bundle, 'status_override' => 0]
+      );
     }
     if ($settings['priority'] != $old_settings['priority']) {
-      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('priority' => $settings['priority']), array('type' => $entity, 'subtype' => $bundle, 'priority_override' => 0));
+      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(
+        ['priority' => $settings['priority']],
+        ['type' => $entity, 'subtype' => $bundle, 'priority_override' => 0]
+      );
     }
   }
 
@@ -803,7 +838,7 @@ function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  *
  * @param string $entity_old
  *   Old entity type id.
- * @param string or int or object... $entity_newNew entity type id.
+ * @param string|int|\stdClass $entity_new
  *   New entity type id.
  * @param array $bundles
  *   Bundles to be updated.
@@ -834,6 +869,7 @@ function xmlsitemap_link_type_rename($entity_old, $entity_new, $bundles = NULL)
  *   Bundle info.
  * @param bool $load_bundle_info
  *   If TRUE, loads bundle info.
+ *
  * @return array
  *   Info about a bundle.
  */
@@ -885,6 +921,7 @@ function xmlsitemap_link_bundle_delete($entity, $bundle, $delete_links = TRUE) {
  *   Entity type id.
  * @param string $bundle
  *   Bundle id.
+ *
  * @return bool
  *   If TRUE, access is allowed, FALSE otherwise.
  */
@@ -920,7 +957,7 @@ function xmlsitemap_link_bundle_access($entity, $bundle = NULL) {
  * @param string $bundle
  *   Bundle id.
  *
- * @return
+ * @return string|FALSE
  *   Path of bundle, or FALSE if it does not exist.
  */
 function xmlsitemap_get_bundle_path($entity, $bundle) {
@@ -954,9 +991,10 @@ function xmlsitemap_entity_bundle_delete($entity_type_id, $bundle) {
 /**
  * Determine the frequency of updates to a link.
  *
- * @param $interval
+ * @param int $interval
  *   An interval value in seconds.
- * @return
+ *
+ * @return string
  *   A string representing the update frequency according to the sitemaps.org
  *   protocol.
  */
@@ -977,12 +1015,13 @@ function xmlsitemap_get_changefreq($interval) {
 /**
  * Get the current number of sitemap chunks.
  *
+ * @param bool $reset
+ *   If TRUE, reset number of chunks.
+ *
  * @static int $chunks
  *   Number of chunks.
- * @param int $reset
- *   If TRUE, reset number of chunks.
  *
- * @return integer
+ * @return int
  *   Number of chunks.
  */
 function xmlsitemap_get_chunk_count($reset = FALSE) {
@@ -997,18 +1036,21 @@ function xmlsitemap_get_chunk_count($reset = FALSE) {
 /**
  * Get the current number of sitemap links.
  *
- * @static int $count
- *   Current number of sitemap links.
  * @param bool $reset
  *   If TRUE, update current number of sitemap links.
  *
- * @return integer
+ * @static int $count
+ *   Current number of sitemap links.
+ *
+ * @return int
  *   Returns current number of sitemap links.
  */
 function xmlsitemap_get_link_count($reset = FALSE) {
   static $count;
   if (!isset($count) || $reset) {
-    $count = db_query("SELECT COUNT(id) FROM {xmlsitemap} WHERE access = 1 AND status = 1")->fetchField();
+    $count = Database::getConnection()
+      ->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE access = 1 AND status = 1")
+      ->fetchField();
   }
   return $count;
 }
@@ -1020,9 +1062,10 @@ function xmlsitemap_get_link_count($reset = FALSE) {
  * calculate the appropriate value. Use this function instead of @code
  * xmlsitemap_var('chunk_size') @endcode when the actual value is needed.
  *
- * @param $reset
+ * @param bool $reset
  *   A boolean to reset the saved, static result. Defaults to FALSE.
- * @return
+ *
+ * @return int
  *   An integer with the number of links in each sitemap page.
  */
 function xmlsitemap_get_chunk_size($reset = FALSE) {
@@ -1041,21 +1084,22 @@ function xmlsitemap_get_chunk_size($reset = FALSE) {
 /**
  * Recalculate the changefreq of a sitemap link.
  *
- * @param $link
+ * @param array $link
  *   A sitemap link array.
  */
 function xmlsitemap_recalculate_changefreq(&$link) {
   $link['changefreq'] = round((($link['changefreq'] * $link['changecount']) + (REQUEST_TIME - $link['lastmod'])) / ($link['changecount'] + 1));
-  $link['changecount'] ++;
+  $link['changecount']++;
   $link['lastmod'] = REQUEST_TIME;
 }
 
 /**
  * Calculates the average interval between UNIX timestamps.
  *
- * @param $timestamps
+ * @param int[] $timestamps
  *   An array of UNIX timestamp integers.
- * @return
+ *
+ * @return array
  *   An integer of the average interval.
  */
 function xmlsitemap_calculate_changefreq($timestamps) {
@@ -1090,7 +1134,12 @@ function xmlsitemap_form_submit_flag_regenerate(array $form, FormStateInterface
     }
     if ($stored_value != 'not_a_variable' && $stored_value != $value) {
       \Drupal::state()->set('xmlsitemap_regenerate_needed', TRUE);
-      drupal_set_message(t('XML sitemap settings have been modified and the files should be regenerated. You can <a href="@run-cron">run cron manually</a> to regenerate the cached files.', array('@run-cron' => Url::fromRoute('system.run_cron', [], array('query' => drupal_get_destination()))->toString())), 'warning', FALSE);
+      $cron_url = Url::fromRoute('system.run_cron', [], array('query' => \Drupal::destination()->getAsArray()))->toString();
+      drupal_set_message(
+        t('XML sitemap settings have been modified and the files should be regenerated. You can <a href="@run-cron">run cron manually</a> to regenerate the cached files.', ['@run-cron' => $cron_url]),
+        'warning',
+        FALSE
+      );
       return;
     }
   }
@@ -1105,8 +1154,9 @@ function xmlsitemap_form_submit_flag_regenerate(array $form, FormStateInterface
  *   Entity type id.
  * @param string $bundle
  *   Bundle id.
- * @param $id
+ * @param int $id
  *   Entity id.
+ *
  * @todo Add changefreq overridability.
  */
 function xmlsitemap_add_form_link_options(array &$form, $entity, $bundle, $id) {
@@ -1143,7 +1193,13 @@ function xmlsitemap_add_form_link_options(array &$form, $entity, $bundle, $id) {
     $form['xmlsitemap']['description'] = array(
       '#prefix' => '<div class="description">',
       '#suffix' => '</div>',
-      '#markup' => t('The default XML sitemap settings for this @bundle can be changed <a href="@link-type">here</a>.', array('@bundle' => Unicode::strtolower($info['bundle label']), '@link-type' => Url::fromUri($path, array('query' => drupal_get_destination()))->toString())),
+      '#markup' => t(
+        'The default XML sitemap settings for this @bundle can be changed <a href="@link-type">here</a>.',
+        [
+          '@bundle' => Unicode::strtolower($info['bundle label']),
+          '@link-type' => Url::fromUri($path, ['query' => \Drupal::destination()->getAsArray()])->toString(),
+        ]
+      ),
     );
   }
 
@@ -1174,7 +1230,7 @@ function xmlsitemap_add_form_link_options(array &$form, $entity, $bundle, $id) {
     '#value' => $link['status_override'],
   );
 
-  // Priority field
+  // Priority field.
   $form['xmlsitemap']['priority'] = array(
     '#type' => 'select',
     '#title' => t('Priority'),
@@ -1223,6 +1279,11 @@ function xmlsitemap_add_form_link_options(array &$form, $entity, $bundle, $id) {
 
 /**
  * Submit callback for the entity form to save.
+ *
+ * @param array $form
+ *   The form the call back is coming from.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ *   The respective form state.
  */
 function xmlsitemap_process_form_link_options(array $form, FormStateInterface $form_state) {
   $link = $form_state->getValue('xmlsitemap');
@@ -1245,8 +1306,13 @@ function xmlsitemap_process_form_link_options(array $form, FormStateInterface $f
 
 /**
  * Submit callback for link bundle settings.
+ *
+ * @param array $form
+ *   The form the call back is coming from.
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
+ *   The respective form state.
  */
-function xmlsitemap_link_bundle_settings_form_submit($form, &$form_state) {
+function xmlsitemap_link_bundle_settings_form_submit($form, FormStateInterface &$form_state) {
   $entity = $form['xmlsitemap']['#entity'];
   $bundle = $form['xmlsitemap']['#bundle'];
 
@@ -1329,9 +1395,10 @@ function xmlsitemap_language_load($language = LanguageInterface::LANGCODE_NOT_SP
  * @param array $context
  *   Context to be updated.
  * @param bool $reset
- *  If TRUE, resets context info.
+ *   If TRUE, resets context info.
  *
  * @return array
+ *   The context info.
  */
 function xmlsitemap_get_context_info($context = NULL, $reset = FALSE) {
   $language = \Drupal::languageManager()->getCurrentLanguage();
@@ -1386,11 +1453,12 @@ function xmlsitemap_get_current_context() {
  *   Key for the context.
  * @param array $context_info
  *   Info about the context.
+ *
  * @return string
  *   Context summary.
  */
 function _xmlsitemap_sitemap_context_summary(XmlSitemapInterface $sitemap, $context_key, array $context_info) {
-  $context_value = isset($sitemap->context[$context_key]) ? $sitemap->context[$context_key] : NULL;
+  $context_value = isset($sitemap->getContext()[$context_key]) ? $sitemap->getContext()[$context_key] : NULL;
 
   if (!isset($context_value)) {
     return t('Default');
@@ -1447,13 +1515,14 @@ function xmlsitemap_run_unprogressive_batch() {
 /**
  * Gets a link from url.
  *
- * @static string $destination
- *   Destination option.
  * @param string $url
  *   Url of the link.
  * @param array $options
  *   Extra options of the url such as 'query'.
  *
+ * @static string $destination
+ *   Destination option.
+ *
  * @return array
  *   An array representing a link.
  */
@@ -1461,7 +1530,7 @@ function xmlsitemap_get_operation_link($url, $options = array()) {
   static $destination;
 
   if (!isset($destination)) {
-    $destination = drupal_get_destination();
+    $destination = \Drupal::destination()->getAsArray();
   }
 
   $link = array('href' => $url) + $options;
@@ -1490,7 +1559,7 @@ function theme_xmlsitemap_content_settings_table($variables) {
 /**
  * Returns the entity form for the given form.
  *
- * @param array $form_state
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state array holding the entity form.
  *
  * @return \Drupal\Core\Entity\EntityFormInterface;
@@ -1509,13 +1578,12 @@ function xmlsitemap_form_alter(array &$form, FormStateInterface $form_state, $fo
   $entity = $form_controller ? $form_controller->getEntity() : NULL;
   $entity_type = $entity ? $entity->getEntityTypeId() : NULL;
   $bundle = $entity ? $entity->bundle() : NULL;
-  $anonymous_user = new AnonymousUserSession();
 
   if (!$form_controller) {
     return;
   }
 
-  // If this entity/bundle can be included in sitemap alter the form
+  // If this entity/bundle can be included in sitemap alter the form.
   if (\Drupal::config("xmlsitemap.settings.{$entity_type}.{$bundle}")->isNew()) {
     return;
   }
@@ -1568,14 +1636,14 @@ function xmlsitemap_xmlsitemap_index_links($limit) {
 /**
  * Process sitemap links.
  *
- * @param array $entities
- *   An array of \Drupal\Core\Entity\EntityInterface objects.
- * @param array
+ * @param string $entity_type
+ *   The entity type.
+ * @param int[] $ids
  *   Entity ids to be processed.
  */
 function xmlsitemap_xmlsitemap_process_entity_links($entity_type, array $ids) {
-  $entities = entity_load_multiple($entity_type, $ids);
-  $anonymous_user = new AnonymousUserSession();
+  $entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadMultiple($ids);
+
   foreach ($entities as $entity) {
     $link_storage = \Drupal::service('xmlsitemap.link_storage');
     $link = $link_storage->create($entity);
@@ -1585,14 +1653,10 @@ function xmlsitemap_xmlsitemap_process_entity_links($entity_type, array $ids) {
 
 /**
  * Implements hook_entity_presave().
- *
- * @param \Drupal\Core\Entity\EntityInterface $entity
- *   The entity that will be presaved.
  */
 function xmlsitemap_entity_presave(EntityInterface $entity) {
   $entity_type = $entity->getEntityTypeId();
   $bundle = $entity->bundle();
-  $anonymous_user = new AnonymousUserSession();
 
   if (!xmlsitemap_link_bundle_check_enabled($entity_type, $bundle)) {
     return;
@@ -1608,14 +1672,10 @@ function xmlsitemap_entity_presave(EntityInterface $entity) {
 
 /**
  * Implements hook_entity_insert().
- *
- * @param \Drupal\Core\Entity\EntityInterface $entity
- *   The entity that will be inserted.
  */
 function xmlsitemap_entity_insert(EntityInterface $entity) {
   $entity_type = $entity->getEntityTypeId();
   $bundle = $entity->bundle();
-  $anonymous_user = new AnonymousUserSession();
 
   if (!xmlsitemap_link_bundle_check_enabled($entity_type, $bundle)) {
     return;
@@ -1628,14 +1688,10 @@ function xmlsitemap_entity_insert(EntityInterface $entity) {
 
 /**
  * Implements hook_entity_update().
- *
- * @param \Drupal\Core\Entity\EntityInterface $entity
- *   The entity that will be updated.
  */
 function xmlsitemap_entity_update(EntityInterface $entity) {
   $entity_type = $entity->getEntityTypeId();
   $bundle = $entity->bundle();
-  $anonymous_user = new AnonymousUserSession();
 
   if (!xmlsitemap_link_bundle_check_enabled($entity_type, $bundle)) {
     return;
@@ -1648,14 +1704,8 @@ function xmlsitemap_entity_update(EntityInterface $entity) {
 
 /**
  * Implements hook_entity_delete().
- *
- * @param \Drupal\Core\Entity\EntityInterface $entity
- *   The entity that will be deleted.
  */
 function xmlsitemap_entity_delete(EntityInterface $entity) {
-  $entity_type = $entity->getEntityTypeId();
-  $bundle = $entity->bundle();
-
   \Drupal::service('xmlsitemap.link_storage')->delete($entity->getEntityTypeId(), $entity->id());
 }
 
@@ -1744,6 +1794,11 @@ function xmlsitemap_query_xmlsitemap_generate_alter(AlterableInterface $query) {
     return;
   }
 
+  // Function exists in SQL-ish queries, not in all types of queries.
+  if (!method_exists($query, 'condition')) {
+    return;
+  }
+
   $mode = \Drupal::config('xmlsitemap.settings')->get('i18n_selection_mode');
   if (!$mode) {
     $mode = 'simple';
@@ -1768,28 +1823,33 @@ function xmlsitemap_query_xmlsitemap_generate_alter(AlterableInterface $query) {
   switch ($mode) {
     case 'simple':
       // Current language and language neutral.
-      $query->condition('language', array($current, LanguageInterface::LANGCODE_NOT_SPECIFIED), 'IN');
+      $query->condition('language', [$current, LanguageInterface::LANGCODE_NOT_SPECIFIED], 'IN');
       break;
 
     case 'mixed':
-      // Mixed current language (if available) or default language (if not) and language neutral.
-      $query->condition('language', array($current, $default, LanguageInterface::LANGCODE_NOT_SPECIFIED), 'IN');
+      // Mixed current language (if available)
+      // or default language (if not) and language neutral.
+      $query->condition(
+        'language',
+        [$current, $default, LanguageInterface::LANGCODE_NOT_SPECIFIED],
+        'IN'
+      );
       break;
 
     case 'default':
       // Only default language and language neutral.
-      $query->condition('language', array($default, LanguageInterface::LANGCODE_NOT_SPECIFIED), 'IN');
+      $query->condition('language', [$default, LanguageInterface::LANGCODE_NOT_SPECIFIED], 'IN');
       break;
 
     case 'strict':
       // Only current language (for nodes), simple for all other types.
-      $node_condition = db_and();
+      $node_condition = new Condition('AND');
       $node_condition->condition('type', 'node', '=');
       $node_condition->condition('language', $current, '=');
-      $normal_condition = db_and();
+      $normal_condition = new Condition('AND');
       $normal_condition->condition('type', 'node', '<>');
       $normal_condition->condition('language', array($current, LanguageInterface::LANGCODE_NOT_SPECIFIED), 'IN');
-      $condition = db_or();
+      $condition = new Condition('OR');
       $condition->condition($node_condition);
       $condition->condition($normal_condition);
       $query->condition($condition);
@@ -1900,13 +1960,13 @@ function xmlsitemap_link_frontpage_settings(&$form) {
 /**
  * XML sitemap operation callback; regenerate sitemap files using the batch API.
  *
- * @param $smids
+ * @param int[] $smids
  *   An array of XML sitemap IDs.
  *
  * @see xmlsitemap_regenerate_batch()
  */
 function xmlsitemap_sitemap_multiple_update(array $smids) {
-  $batch = xmlsitemap_regenerate_batch($smids);
+  $batch = \Drupal::service('xmlsitemap_generator')->createRegenerateBatch($smids);
   batch_set($batch);
 }
 
@@ -1923,7 +1983,6 @@ function xmlsitemap_sitemap_multiple_update(array $smids) {
 function xmlsitemap_add_form_entity_summary(&$form, $entity, array $entity_info) {
   $priorities = xmlsitemap_get_priority_options(NULL, FALSE);
   $statuses = xmlsitemap_get_status_options(NULL);
-  $destination = drupal_get_destination();
 
   $rows = array();
   $totals = array('total' => 0, 'indexed' => 0, 'visible' => 0);
@@ -1941,11 +2000,11 @@ function xmlsitemap_add_form_entity_summary(&$form, $entity, array $entity_info)
     if (\Drupal::service('path.validator')->isValid("admin/config/search/xmlsitemap/settings/$entity/$bundle")) {
       $edit_link = xmlsitemap_get_operation_link("internal://admin/config/search/xmlsitemap/settings/$entity/$bundle", array('title' => $bundle_info['label'], 'modal' => TRUE));
       $url = Url::fromUri($edit_link['href'], $edit_link);
-      $row[] = \Drupal::l($edit_link['title'], $url);
+      $row[] = \Drupal::service('link_generator')->generate($edit_link['title'], $url);
     }
     else {
       // Bundle labels are assumed to be un-escaped input.
-      $row[] = SafeMarkup::checkPlain($bundle_info['label']);
+      $row[] = $bundle_info['label'];
     }
     $row[] = $statuses[$bundle_info['xmlsitemap']['status'] ? 1 : 0];
     $row[] = $priorities[number_format($bundle_info['xmlsitemap']['priority'], 1)];
@@ -1999,7 +2058,7 @@ function xmlsitemap_add_form_entity_summary(&$form, $entity, array $entity_info)
  *
  * @param array $form
  *   Form array.
- * @param array $form_state
+ * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Form state array.
  * @param string $entity
  *   Entity type id.
@@ -2063,11 +2122,12 @@ function xmlsitemap_add_link_bundle_settings(array &$form, FormStateInterface $f
 /**
  * Get a list of priority options.
  *
- * @param $default
+ * @param string $default
  *   Include a 'default' option.
- * @param $guides
+ * @param bool $guides
  *   Add helpful indicators for the highest, middle and lowest values.
- * @return
+ *
+ * @return array
  *   An array of options.
  */
 function xmlsitemap_get_priority_options($default = NULL, $guides = TRUE) {
@@ -2106,9 +2166,10 @@ function xmlsitemap_get_priority_options($default = NULL, $guides = TRUE) {
 /**
  * Get a list of priority options.
  *
- * @param $default
+ * @param string $default
  *   Include a 'default' option.
- * @return
+ *
+ * @return array
  *   An array of options.
  *
  * @see _xmlsitemap_translation_strings()
@@ -2186,7 +2247,8 @@ function xmlsitemap_output_file(Response $response, $file, array $headers = arra
   $if_none_match = $request->server->has('HTTP_IF_NONE_MATCH') ? stripslashes($request->server->get('HTTP_IF_NONE_MATCH')) : FALSE;
   if ($if_modified_since && $if_none_match && $if_none_match == $etag && $if_modified_since == $last_modified) {
     $response->setNotModified();
-    // All 304 responses must send an etag if the 200 response for the same object contained an etag
+    // All 304 responses must send an etag,
+    // if the 200 response for the same object contained an etag.
     $response->headers->set('Etag', $etag);
     return $response;
   }
@@ -2234,7 +2296,7 @@ function xmlsitemap_file_transfer(Response $response, $uri, $headers) {
   drupal_set_time_limit(240);
   $scheme = file_default_scheme();
   // Transfer file in 16 KB chunks to save memory usage.
-  if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
+  if ($scheme && \Drupal::service('file_system')->validScheme($scheme) && $fd = fopen($uri, 'rb')) {
     while (!feof($fd)) {
       $content .= fread($fd, 1024 * 16);
     }
@@ -2249,13 +2311,15 @@ function xmlsitemap_file_transfer(Response $response, $uri, $headers) {
 
 /**
  * Fetch a short blurb string about module maintainership and sponsors.
- * This message will be FALSE in 'official' releases.
+ *
+ * @param mixed $check_version
+ *   Version to check.
  *
  * @static string $blurb
  *   Blurb message.
  *
- * @param string or int or object... $check_version
  * @return string
+ *   Message.
  */
 function _xmlsitemap_get_blurb($check_version = TRUE) {
   static $blurb;
@@ -2264,15 +2328,15 @@ function _xmlsitemap_get_blurb($check_version = TRUE) {
     $blurb = FALSE;
     if (!$check_version || (($version = _xmlsitemap_get_version()) && preg_match('/dev|unstable|alpha|beta|HEAD/i', $version))) {
       $sponsors = array(
-        \Drupal::l('Symantec', Url::fromUri('http://www.symantec.com/')),
-        \Drupal::l('WebWise Solutions', Url::fromUri('http://www.webwiseone.com/')),
-        \Drupal::l('Volacci', Url::fromUri('http://www.volacci.com/')),
-        \Drupal::l('lanetro', Url::fromUri('http://www.lanetro.com/')),
-        \Drupal::l('Coupons Dealuxe', Url::fromUri('http://couponsdealuxe.com/')),
+        \Drupal::service('link_generator')->generate('Symantec', Url::fromUri('http://www.symantec.com/')),
+        \Drupal::service('link_generator')->generate('WebWise Solutions', Url::fromUri('http://www.webwiseone.com/')),
+        \Drupal::service('link_generator')->generate('Volacci', Url::fromUri('http://www.volacci.com/')),
+        \Drupal::service('link_generator')->generate('lanetro', Url::fromUri('http://www.lanetro.com/')),
+        \Drupal::service('link_generator')->generate('Coupons Dealuxe', Url::fromUri('http://couponsdealuxe.com/')),
       );
       // Don't extract the following string for translation.
       $blurb = '<div class="description"><p>Thank you for helping test the XML sitemap module rewrite. Please consider helping offset developer free time by <a href="http://davereid.chipin.com/">donating</a> or if your company is interested in sponsoring the rewrite or a specific feature, please <a href="http://davereid.net/contact">contact the developer</a>. Thank you to the following current sponsors: ' . implode(', ', $sponsors) . ', and all the individuals that have donated. This message will not be seen in the stable versions.</p></div>';
-      //http://drupalmodules.com/module/xml-sitemap
+      // http://drupalmodules.com/module/xml-sitemap.
     }
   }
 
@@ -2349,231 +2413,7 @@ function xmlsitemap_check_status() {
   return !empty($messages);
 }
 
-// BATCH OPERATIONS ------------------------------------------------------------
-/**
- * Perform operations before rebuilding the sitemap.
- */
-function _xmlsitemap_regenerate_before() {
-  \Drupal::service('xmlsitemap_generator')->regenerateBefore();
-}
-
-/**
- * Batch information callback for regenerating the sitemap files.
- *
- * @param $smids
- *   An optional array of XML sitemap IDs. If not provided, it will load all
- *   existing XML sitemaps.
- */
-function xmlsitemap_regenerate_batch(array $smids = array()) {
-  if (empty($smids)) {
-    $sitemaps = \Drupal::entityTypeManager()->getStorage('xmlsitemap')->loadMultiple();
-    foreach ($sitemaps as $sitemap) {
-      $smids[] = $sitemap->id();
-    }
-  }
-
-  $t = 't';
-  $batch = array(
-    'operations' => array(),
-    'error_message' => $t('An error has occurred.'),
-    'finished' => 'xmlsitemap_regenerate_batch_finished',
-    'title' => t('Regenerating Sitemap'),
-  );
-
-  // Set the regenerate flag in case something fails during file generation.
-  $batch['operations'][] = array('xmlsitemap_batch_variable_set', array(array('xmlsitemap_regenerate_needed' => TRUE)));
-
-  // @todo Get rid of this batch operation.
-  $batch['operations'][] = array('_xmlsitemap_regenerate_before', array());
-
-  // Generate all the sitemap pages for each context.
-  foreach ($smids as $smid) {
-    $batch['operations'][] = array('xmlsitemap_regenerate_batch_generate', array($smid));
-    $batch['operations'][] = array('xmlsitemap_regenerate_batch_generate_index', array($smid));
-  }
-
-  // Clear the regeneration flag.
-  $batch['operations'][] = array('xmlsitemap_batch_variable_set', array(array('xmlsitemap_regenerate_needed' => FALSE)));
-
-  return $batch;
-}
-
-/**
- * Batch callback; generate all pages of a sitemap.
- *
- * @param string $smid
- *   Sitemap entity id.
- * @param array $context
- *   Sitemap context.
- */
-function xmlsitemap_regenerate_batch_generate($smid, array &$context = array()) {
-  \Drupal::service('xmlsitemap_generator')->regenerateBatchGenerate($smid, $context);
-}
-
-/**
- * Batch callback; generate the index page of a sitemap.
- *
- * @param string $smid
- *   Sitemap entity id.
- * @param array $context
- *   Sitemap context.
- */
-function xmlsitemap_regenerate_batch_generate_index($smid, array &$context = array()) {
-  \Drupal::service('xmlsitemap_generator')->regenerateBatchGenerateIndex($smid, $context);
-}
-
-/**
- * Batch callback; sitemap regeneration finished.
- *
- * @param bool $success
- *   Checks if regeneration batch process was successful.
- * @param array $results
- *   Results for the regeneration process.
- * @param array $operations
- *   Operations performed.
- * @param int $elapsedTime elapsed.
- *   Time elapsed.
- */
-function xmlsitemap_regenerate_batch_finished($success, $results, $operations, $elapsed) {
-  \Drupal::service('xmlsitemap_generator')->regenerateBatchFinished($success, $results, $operations, $elapsed);
-}
-
-/**
- * Batch information callback for rebuilding the sitemap data.
- *
- * @param array $entity_type_ids
- *   Entity types to rebuild.
- * @param bool $save_custom
- *   Save custom data.
- *
- * @return array
- *   Batch array.
- */
-function xmlsitemap_rebuild_batch(array $entity_type_ids, $save_custom = FALSE) {
-  $batch = array(
-    'operations' => array(),
-    'finished' => 'xmlsitemap_rebuild_batch_finished',
-    'title' => t('Rebuilding Sitemap'),
-    'file' => drupal_get_path('module', 'xmlsitemap') . '/xmlsitemap.generate.inc',
-  );
-
-  // Set the rebuild flag in case something fails during the rebuild.
-  $batch['operations'][] = array('xmlsitemap_batch_variable_set', array(array('xmlsitemap_rebuild_needed' => TRUE)));
-
-  // Purge any links first.
-  $batch['operations'][] = array('xmlsitemap_rebuild_batch_clear', array($entity_type_ids, (bool) $save_custom));
-
-  // Fetch all the sitemap links and save them to the {xmlsitemap} table.
-  foreach ($entity_type_ids as $entity_type_id) {
-    $info = xmlsitemap_get_link_info($entity_type_id);
-    $batch['operations'][] = array($info['xmlsitemap']['rebuild callback'], array($entity_type_id));
-  }
-
-  // Clear the rebuild flag.
-  $batch['operations'][] = array('xmlsitemap_batch_variable_set', array(array('xmlsitemap_rebuild_needed' => FALSE)));
-
-  // Add the regeneration batch.
-  $regenerate_batch = xmlsitemap_regenerate_batch();
-  $batch['operations'] = array_merge($batch['operations'], $regenerate_batch['operations']);
-
-  return $batch;
-}
-
-/**
- * Batch callback; set an array of variables and their values.
- *
- * @param array $variables
- *   Variables to be set during the batch process.
- */
-function xmlsitemap_batch_variable_set(array $variables) {
-  \Drupal::service('xmlsitemap_generator')->batchVariableSet($variables);
-}
-
-/**
- * Batch callback; clear sitemap links for entites.
- *
- * @param array $entity_type_ids
- *   Entity types to rebuild.
- * @param bool $save_custom
- *   Save custom data.
- * @param array $context
- *   Context to be rebuilt.
- */
-function xmlsitemap_rebuild_batch_clear(array $entity_type_ids, $save_custom, &$context = array()) {
-  \Drupal::service('xmlsitemap_generator')->rebuildBatchClear($entity_type_ids, $save_custom, $context);
-}
-
-/**
- * Batch callback; fetch and add the sitemap links for a specific entity type.
- *
- * @param string $entity_type_id
- *   Entity type ID.
- * @param array context
- *   Sitemap context.
- */
-function xmlsitemap_rebuild_batch_fetch($entity_type_id, &$context) {
-  if (!isset($context['sandbox']['info'])) {
-    $context['sandbox']['info'] = xmlsitemap_get_link_info($entity_type_id);
-    $context['sandbox']['progress'] = 0;
-    $context['sandbox']['last_id'] = 0;
-  }
-  $info = $context['sandbox']['info'];
-  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
-
-  $query = \Drupal::entityQuery($entity_type_id);
-  $query->condition($entity_type->getKey('id'), $context['sandbox']['last_id'], '>');
-  $query->addTag('xmlsitemap_link_bundle_access');
-  $query->addTag('xmlsitemap_rebuild');
-  $query->addMetaData('entity_type_id', $entity_type_id);
-  $query->addMetaData('entity_info', $info);
-
-  if (!isset($context['sandbox']['max'])) {
-    $count_query = clone $query;
-    $count_query->count();
-    $context['sandbox']['max'] = $count_query->execute();
-    if (!$context['sandbox']['max']) {
-      // If there are no items to process, skip everything else.
-      return;
-    }
-  }
-
-  // PostgreSQL cannot have the ORDERED BY in the count query.
-  $query->sort($entity_type->getKey('id'));
-
-  // get batch limit
-  $limit = \Drupal::config('xmlsitemap.settings')->get('batch_limit');
-  $query->range(0, $limit);
-
-  $result = $query->execute();
-
-  $info['xmlsitemap']['process callback']($entity_type_id, $result);
-  $context['sandbox']['last_id'] = end($result);
-  $context['sandbox']['progress'] += count($result);
-  $context['message'] = t('Now processing %entity_type_id @last_id (@progress of @count).', array('%entity_type_id' => $entity_type_id, '@last_id' => $context['sandbox']['last_id'], '@progress' => $context['sandbox']['progress'], '@count' => $context['sandbox']['max']));
-
-  if ($context['sandbox']['progress'] >= $context['sandbox']['max']) {
-    $context['finished'] = 1;
-  }
-  else {
-    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
-  }
-}
-
-/**
- * Batch callback; sitemap rebuild finished.
- *
- * @param bool $success
- *   Checks if regeneration batch process was successful.
- * @param array $results
- *   Results for the regeneration process.
- * @param array $operations
- *   Operations performed.
- * @param int $elapsedTime elapsed.
- *   Time elapsed.
- */
-function xmlsitemap_rebuild_batch_finished($success, $results, $operations, $elapsed) {
-  \Drupal::service('xmlsitemap_generator')->rebuildBatchFinished($success, $results, $operations, $elapsed);
-}
+/* ------------------ BATCH OPERATIONS -------------------- */
 
 /**
  * Get all rebuildable entity types.
@@ -2604,7 +2444,7 @@ function xmlsitemap_get_rebuildable_link_types() {
 }
 
 /**
- * Enable an entity bundle and create specific xmlsitemap settings config object.
+ * Enable an entity bundle and create specific xmlsitemap settings config.
  *
  * @param string $entity_type_id
  *   Entity type id.
@@ -2627,7 +2467,7 @@ function xmlsitemap_link_bundle_enable($entity_type_id, $bundle_id) {
 }
 
 /**
- * Check if a bundle is enabled and config object xmlsitemap.settings object exists.
+ * Check if a bundle is enabled and config object xmlsitemap.settings exists.
  *
  * @param string $entity_type_id
  *   Entity type id.
