You are here

public function XmlSitemapGenerator::regenerateBatchGenerate in XML sitemap 2.x

Same name and namespace in other branches
  1. 8 src/XmlSitemapGenerator.php \Drupal\xmlsitemap\XmlSitemapGenerator::regenerateBatchGenerate()

Batch callback; generate all pages of a sitemap.

Parameters

string $smid: Sitemap id.

array|\ArrayAccess $context: Sitemap context.

Overrides XmlSitemapGeneratorInterface::regenerateBatchGenerate

File

src/XmlSitemapGenerator.php, line 398

Class

XmlSitemapGenerator
XmlSitemap generator service class.

Namespace

Drupal\xmlsitemap

Code

public function regenerateBatchGenerate($smid, &$context) {
  if (!isset($context['sandbox']['sitemap'])) {
    $context['sandbox']['sitemap'] = $this->entityTypeManager
      ->getStorage('xmlsitemap')
      ->load($smid);
    $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.
    if (!xmlsitemap_check_directory($context['sandbox']['sitemap'])) {
      throw new DirectoryNotReadyException("The sitemap directory could not be created or is not writable.");
    }
    xmlsitemap_clear_directory($context['sandbox']['sitemap']);
  }

  /** @var \Drupal\xmlsitemap\XmlSitemapInterface $sitemap */
  $sitemap =& $context['sandbox']['sitemap'];
  try {
    $links = $this
      ->generatePage($sitemap, $sitemap
      ->getChunks());
  } catch (\Exception $e) {

    // @todo Should this use watchdog_exception()?
    $this->logger
      ->error($e);
  }
  if (!empty($links)) {
    $context['message'] = $this
      ->t('Generated %sitemap-url with @count links.', [
      '%sitemap-url' => Url::fromRoute('xmlsitemap.sitemap_xml', [], $sitemap->uri['options'] + [
        'query' => [
          'page' => $sitemap
            ->getChunks(),
        ],
      ])
        ->toString(),
      '@count' => $links,
    ]);
    $sitemap
      ->setLinks($sitemap
      ->getLinks() + $links);
    $sitemap
      ->setChunks($sitemap
      ->getChunks() + 1);
  }
  else {

    // Cleanup the 'extra' empty file.
    $file = xmlsitemap_sitemap_get_file($sitemap, $sitemap
      ->getChunks());
    if (file_exists($file) && $sitemap
      ->getChunks() > 1) {
      $this->fileSystem
        ->delete($file);
    }
    $sitemap
      ->setChunks($sitemap
      ->getChunks() - 1);

    // Save the updated chunks and links values.
    $context['sandbox']['max'] = $sitemap
      ->getChunks();
    $sitemap
      ->setUpdated($this->time
      ->getRequestTime());
    xmlsitemap_sitemap_get_max_filesize($sitemap);
    xmlsitemap_sitemap_save($sitemap);
    $context['finished'] = 1;
    return;
  }
  if ($sitemap
    ->getChunks() < $context['sandbox']['max']) {
    $context['finished'] = $sitemap
      ->getChunks() / $context['sandbox']['max'];
  }
}