QueueWorker.php 11.1 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;

  /**
gbyte.co's avatar
gbyte.co committed
46
   * @var \Drupal\simple_sitemap\Queue\SimplesitemapQueue
47
   */
gbyte.co's avatar
gbyte.co 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
gbyte.co's avatar
gbyte.co 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,
gbyte.co's avatar
gbyte.co 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;
gbyte.co's avatar
gbyte.co committed
109
    $this->queue = $element_queue;
110 111 112
    $this->lock = $lock;
  }

gbyte.co's avatar
gbyte.co committed
113 114 115
  /**
   * @return $this
   */
116
  public function deleteQueue() {
gbyte.co's avatar
gbyte.co 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
    $sitemap_variants = $this->manager->getSitemapVariants();

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

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

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

      $type = $variant_definition['type'];

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

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        $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 = [];
            }
175 176 177 178 179
          }
        }
      }
    }

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

185
    // todo: May not be clean to remove sitemap variants data when queuing elements.
186
    // todo: Add test.
187 188 189
    // 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']); })));

190 191 192 193
    return $this;
  }

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

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

    $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),
212
      'remove_duplicates' => $this->settings->getSetting('remove_duplicates', TRUE),
213 214 215 216 217 218 219 220
      '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();

221
    if (!$this->generationInProgress()) {
gbyte.co's avatar
gbyte.co committed
222
      $this->rebuildQueue();
223 224
    }

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

      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'];
241
          $this->processedPaths = [];
242 243 244 245 246 247 248 249 250 251 252 253
        }

        $this->generateResultsFromElement($element);

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

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

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

    return $this;
  }

  protected function generateResultsFromElement($element) {
270 271 272 273 274 275 276 277 278 279 280
    $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']
281
      && !empty($results)
282 283 284 285 286 287 288 289
      && !empty($path = $results[key($results)]['meta']['path'])) {
      if (in_array($path, $this->processedPaths)) {
        $results = [];
      }
      else {
        $this->processedPaths[] = $path;
      }
    }
290 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
  }

  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,
327 328
      'results' => $this->results,
      'processed_paths' => $this->processedPaths,
329 330
    ]);
    $this->results = [];
331
    $this->processedPaths = [];
332 333 334 335 336
    $this->generatorProcessedNow = NULL;
    $this->variantProcessedNow = NULL;
  }

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

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

    return $this->elementsTotal;
  }

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

    return $this->elementsRemaining;
  }

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

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

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

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