QueueWorker.php 11.2 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\simple_sitemap\Queue;

use Drupal\Component\Utility\Timer;
6
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase;
7 8 9 10
use Drupal\simple_sitemap\SimplesitemapSettings;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\simple_sitemap\SimplesitemapManager;
use Drupal\Core\State\State;
11
use Drupal\Core\Lock\LockBackendInterface;
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45


class QueueWorker {

  use BatchTrait;

  const REBUILD_QUEUE_CHUNK_ITEM_SIZE = 5000;

  /**
   * @var \Drupal\simple_sitemap\SimplesitemapSettings
   */
  protected $settings;

  /**
   * @var \Drupal\simple_sitemap\SimplesitemapManager
   */
  protected $manager;

  /**
   * @var \Drupal\Core\State\State
   */
  protected $state;

  /**
   * @var \Drupal\Core\Extension\ModuleHandler
   */
  protected $moduleHandler;

  /**
   * @var \Drupal\Core\ProxyClass\Lock\DatabaseLockBackend
   */
  protected $lock;

  /**
Pawel G's avatar
Pawel G committed
46
   * @var \Drupal\simple_sitemap\Queue\SimplesitemapQueue
47
   */
Pawel G's avatar
Pawel G committed
48
  protected $queue;
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

  /**
   * @var string|null
   */
  protected $variantProcessedNow;

  /**
   * @var string|null
   */
  protected $generatorProcessedNow;

  /**
   * @var array
   */
  protected $results = [];

65 66 67 68 69
  /**
   * @var array
   */
  protected $processedPaths = [];

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
  /**
   * @var array
   */
  protected $generatorSettings;

  /**
   * @var int|null
   */
  protected $maxLinks;

  /**
   * @var int|null
   */
  protected $elementsRemaining;

  /**
   * @var int|null
   */
  protected $elementsTotal;

  /**
   * QueueWorker constructor.
   * @param \Drupal\simple_sitemap\SimplesitemapSettings $settings
   * @param \Drupal\simple_sitemap\SimplesitemapManager $manager
   * @param \Drupal\Core\State\State $state
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
Pawel G's avatar
Pawel G committed
96
   * @param \Drupal\simple_sitemap\Queue\SimplesitemapQueue $element_queue
97
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
98 99 100 101 102
   */
  public function __construct(SimplesitemapSettings $settings,
                              SimplesitemapManager $manager,
                              State $state,
                              ModuleHandler $module_handler,
Pawel G's avatar
Pawel G committed
103
                              SimplesitemapQueue $element_queue,
104
                              LockBackendInterface $lock) {
105 106 107 108
    $this->settings = $settings;
    $this->manager = $manager;
    $this->state = $state;
    $this->moduleHandler = $module_handler;
Pawel G's avatar
Pawel G committed
109
    $this->queue = $element_queue;
110 111 112
    $this->lock = $lock;
  }

Pawel G's avatar
Pawel G committed
113 114 115
  /**
   * @return $this
   */
116
  public function deleteQueue() {
Pawel G's avatar
Pawel G committed
117
    $this->queue->deleteQueue();
118
    SitemapGeneratorBase::purgeSitemapVariants(NULL, 'unpublished');
119 120 121
    $this->variantProcessedNow = NULL;
    $this->generatorProcessedNow = NULL;
    $this->results = [];
122
    $this->processedPaths = [];
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    $this->state->set('simple_sitemap.queue_items_initial_amount', 0);
    $this->state->delete('simple_sitemap.queue_stashed_results');
    $this->elementsTotal = NULL;
    $this->elementsRemaining = NULL;

    return $this;
  }

  /**
   * @param null $variants
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *
   * @todo Lock functionality
   */
  public function rebuildQueue($variants = NULL) {
139
    $all_data_sets = [];
140 141 142 143 144 145 146 147 148
    $sitemap_variants = $this->manager->getSitemapVariants();
    $this->moduleHandler->alter('simple_sitemap_variants', $sitemap_variants);

    $type_definitions = $this->manager->getSitemapTypes();
    $this->deleteQueue();

    foreach ($sitemap_variants as $variant_name => $variant_definition) {

      // Skipping unwanted sitemap variants.
Pawel G's avatar
Pawel G committed
149
      if (NULL !== $variants && !in_array($variant_name, (array) $variants)) {
150 151 152 153 154 155 156 157
        continue;
      }

      $type = $variant_definition['type'];

      // Adding generate_sitemap operations for all data sets.
      foreach ($type_definitions[$type]['urlGenerators'] as $url_generator_id) {

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        $data_sets = $this->manager->getUrlGenerator($url_generator_id)
          ->setSitemapVariant($variant_name)
          ->getDataSets();

        if (!empty($data_sets)) {
          $sitemap_variants[$variant_name]['data'] = TRUE;
          foreach ($data_sets as $data_set) {
            $all_data_sets[] = [
              'data' => $data_set,
              'sitemap_variant' => $variant_name,
              'url_generator' => $url_generator_id,
              'sitemap_generator' => $type_definitions[$type]['sitemapGenerator'],
            ];

            if (count($all_data_sets) === self::REBUILD_QUEUE_CHUNK_ITEM_SIZE) {
              $this->queueElements($all_data_sets);
              $all_data_sets = [];
            }
176 177 178 179 180
          }
        }
      }
    }

181 182
    if (!empty($all_data_sets)) {
      $this->queueElements($all_data_sets);
183
    }
184
    $this->getQueuedElementCount(TRUE);
185

186
    // todo: May not be clean to remove sitemap variants data when queuing elements.
187
    // todo: Add test.
188 189 190
    // Remove all sitemap variant instances where no results have been queued.
    $this->manager->removeSitemap(array_keys(array_filter($sitemap_variants, function($e) { return empty($e['data']); })));

191 192 193 194
    return $this;
  }

  protected function queueElements($elements) {
Pawel G's avatar
Pawel G committed
195
    $this->queue->createItems($elements);
196 197 198 199
    $this->state->set('simple_sitemap.queue_items_initial_amount', ($this->state->get('simple_sitemap.queue_items_initial_amount') + count($elements)));
  }

  /**
Pawel G's avatar
Pawel G committed
200
   * @param string $from
201 202 203 204
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *
   * @todo Lock functionality
205
   * @todo Does not unpublish sitemaps were variant does not have links anymore.
206
   */
Pawel G's avatar
Pawel G committed
207
  public function generateSitemap($from = 'form') {
208 209 210 211 212

    $this->generatorSettings = [
      'base_url' => $this->settings->getSetting('base_url', ''),
      'default_variant' => $this->settings->getSetting('default_variant', NULL),
      'skip_untranslated' => $this->settings->getSetting('skip_untranslated', FALSE),
213
      'remove_duplicates' => $this->settings->getSetting('remove_duplicates', TRUE),
214 215 216 217 218 219 220 221
      'excluded_languages' => $this->settings->getSetting('excluded_languages', []),
    ];
    $this->maxLinks = $this->settings->getSetting('max_links');
    $max_execution_time = $this->settings->getSetting('generate_duration', 10000);
    Timer::start('simple_sitemap_generator');

    $this->unstashResults();

222
    if (!$this->generationInProgress()) {
Pawel G's avatar
Pawel G committed
223
      $this->rebuildQueue();
224 225
    }

Pawel G's avatar
Pawel G committed
226
    while ($element = $this->queue->claimItem()) {
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

      if (!empty($max_execution_time) && Timer::read('simple_sitemap_generator') >= $max_execution_time) {
        break;
      }

      try {
        if ($element->data['sitemap_variant'] !== $this->variantProcessedNow) {

          if (NULL !== $this->variantProcessedNow) {
            $this->generateVariantChunksFromResults(TRUE);
            $this->publishCurrentVariant();
          }

          $this->variantProcessedNow = $element->data['sitemap_variant'];
          $this->generatorProcessedNow = $element->data['sitemap_generator'];
242
          $this->processedPaths = [];
243 244 245 246 247 248 249 250 251 252 253 254
        }

        $this->generateResultsFromElement($element);

        if (!empty($this->maxLinks) && count($this->results) >= $this->maxLinks) {
          $this->generateVariantChunksFromResults();
        }
      }
      catch (\Exception $e) {
        watchdog_exception('simple_sitemap', $e);
      }

Pawel G's avatar
Pawel G committed
255
      $this->queue->deleteItem($element); //todo May want to use deleteItems() instead.
256 257 258
      $this->elementsRemaining--;
    }

259
    if ($this->getQueuedElementCount() === 0) {
260 261 262 263 264 265 266 267 268 269 270
      $this->generateVariantChunksFromResults(TRUE);
      $this->publishCurrentVariant();
    }
    else {
      $this->stashResults();
    }

    return $this;
  }

  protected function generateResultsFromElement($element) {
271 272 273 274 275 276 277 278 279 280 281
    $results = $this->manager->getUrlGenerator($element->data['url_generator'])
      ->setSitemapVariant($this->variantProcessedNow)
      ->setSettings($this->generatorSettings)
      ->generate($element->data['data']);

    $this->removeDuplicates($results);
    $this->results = array_merge($this->results, $results);
  }

  protected function removeDuplicates(&$results) {
    if ($this->generatorSettings['remove_duplicates']
282
      && !empty($results)
283 284 285 286 287 288 289 290
      && !empty($path = $results[key($results)]['meta']['path'])) {
      if (in_array($path, $this->processedPaths)) {
        $results = [];
      }
      else {
        $this->processedPaths[] = $path;
      }
    }
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  }

  protected function generateVariantChunksFromResults($complete = FALSE) {
    if (!empty($this->results)) {
      $generator = $this->manager->getSitemapGenerator($this->generatorProcessedNow)
        ->setSitemapVariant($this->variantProcessedNow)
        ->setSettings($this->generatorSettings);

      if (empty($this->maxLinks) || $complete) {
        $generator->generate($this->results);
        $this->results = [];
      }
      else {
        foreach (array_chunk($this->results, $this->maxLinks, TRUE) as $chunk_links) {
          if (count($chunk_links) === $this->maxLinks || $complete) {
            $generator->generate($chunk_links);
            $this->results = array_diff_key($this->results, $chunk_links);
          }
        }
      }
    };
  }

  protected function publishCurrentVariant() {
    if ($this->variantProcessedNow !== NULL) {
      $this->manager->getSitemapGenerator($this->generatorProcessedNow)
        ->setSitemapVariant($this->variantProcessedNow)
        ->setSettings($this->generatorSettings)
        ->generateIndex()
        ->publish();
    }
  }

  protected function stashResults() {
    $this->state->set('simple_sitemap.queue_stashed_results', [
      'variant' => $this->variantProcessedNow,
      'generator' => $this->generatorProcessedNow,
328 329
      'results' => $this->results,
      'processed_paths' => $this->processedPaths,
330 331
    ]);
    $this->results = [];
332
    $this->processedPaths = [];
333 334 335 336 337
    $this->generatorProcessedNow = NULL;
    $this->variantProcessedNow = NULL;
  }

  protected function unstashResults() {
338
    if (NULL !== $results = $this->state->get('simple_sitemap.queue_stashed_results')) {
339
      $this->state->delete('simple_sitemap.queue_stashed_results');
Pawel G's avatar
Pawel G committed
340
      $this->results = !empty($results['results']) ? $results['results'] : [];
341
      $this->processedPaths = !empty($results['processed_paths']) ? $results['processed_paths'] : [];
342 343 344 345 346
      $this->variantProcessedNow = $results['variant'];
      $this->generatorProcessedNow = $results['generator'];
    }
  }

Pawel G's avatar
Pawel G committed
347
  public function getInitialElementCount() {
348
    if (NULL === $this->elementsTotal) {
349
      $this->elementsTotal = (int) $this->state->get('simple_sitemap.queue_items_initial_amount', 0);
350 351 352 353 354
    }

    return $this->elementsTotal;
  }

355
  public function getQueuedElementCount($force_recount = FALSE) {
356
    if ($force_recount || NULL === $this->elementsRemaining) {
Pawel G's avatar
Pawel G committed
357
      $this->elementsRemaining = $this->queue->numberOfItems();
358 359 360 361 362
    }

    return $this->elementsRemaining;
  }

363
  public function getStashedResultCount() {
364
    return count($this->state->get('simple_sitemap.queue_stashed_results', ['results' => []])['results']);
365 366
  }

367
  public function getProcessedElementCount() {
368
    $initial = $this->getInitialElementCount();
369
    $remaining = $this->getQueuedElementCount();
370

371
    return $initial > $remaining ? ($initial - $remaining) : 0;
372
  }
373 374 375 376

  public function generationInProgress() {
    return 0 < ($this->getQueuedElementCount() + $this->getStashedResultCount());
  }
377 378
}