QueueWorker.php 10.7 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::removeSitemapVariants(NULL, 'unpublished'); //todo should call the remove() method of every plugin instead?
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 139 140 141 142 143 144 145 146 147 148
    $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) {
    $data_sets = [];
    $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.
gbyte.co's avatar
gbyte.co committed
149
      if (NULL !== $variants && !in_array($variant_name, (array) $variants)) {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        continue;
      }

      $type = $variant_definition['type'];

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

        foreach ($this->manager->getUrlGenerator($url_generator_id)
                   ->setSitemapVariant($variant_name)
                   ->getDataSets() as $data_set) {

          $data_sets[] = [
            'data' => $data_set,
            'sitemap_variant' => $variant_name,
            'url_generator' => $url_generator_id,
            'sitemap_generator' => $type_definitions[$type]['sitemapGenerator'],
          ];

          if (count($data_sets) === self::REBUILD_QUEUE_CHUNK_ITEM_SIZE) {
            $this->queueElements($data_sets);
            $data_sets = [];
          }
        }
      }
    }

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

    return $this;
  }

  protected function queueElements($elements) {
gbyte.co's avatar
gbyte.co committed
186
    $this->queue->createItems($elements);
187 188 189 190
    $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
191
   * @param string $from
192 193 194 195 196
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *
   * @todo Lock functionality
   */
gbyte.co's avatar
gbyte.co committed
197
  public function generateSitemap($from = 'form') {
198 199 200 201 202

    $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),
203
      'remove_duplicates' => $this->settings->getSetting('remove_duplicates', TRUE),
204 205 206 207 208 209 210 211
      '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();

212
    if (!$this->generationInProgress()) {
gbyte.co's avatar
gbyte.co committed
213
      $this->rebuildQueue();
214 215
    }

gbyte.co's avatar
gbyte.co committed
216
    while ($element = $this->queue->claimItem()) {
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

      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'];
232
          $this->processedPaths = [];
233 234 235 236 237 238 239 240 241 242 243 244
        }

        $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
245
      $this->queue->deleteItem($element); //todo May want to use deleteItems() instead.
246 247 248
      $this->elementsRemaining--;
    }

249
    if ($this->getQueuedElementCount() === 0) {
250 251 252 253 254 255 256 257 258 259 260
      $this->generateVariantChunksFromResults(TRUE);
      $this->publishCurrentVariant();
    }
    else {
      $this->stashResults();
    }

    return $this;
  }

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

  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,
318 319
      'results' => $this->results,
      'processed_paths' => $this->processedPaths,
320 321
    ]);
    $this->results = [];
322
    $this->processedPaths = [];
323 324 325 326 327
    $this->generatorProcessedNow = NULL;
    $this->variantProcessedNow = NULL;
  }

  protected function unstashResults() {
328
    if (NULL !== $results = $this->state->get('simple_sitemap.queue_stashed_results')) {
329
      $this->state->delete('simple_sitemap.queue_stashed_results');
gbyte.co's avatar
gbyte.co committed
330
      $this->results = !empty($results['results']) ? $results['results'] : [];
331
      $this->processedPaths = !empty($results['processed_paths']) ? $results['processed_paths'] : [];
332 333 334 335 336
      $this->variantProcessedNow = $results['variant'];
      $this->generatorProcessedNow = $results['generator'];
    }
  }

337
  public function getInitialElementCount() {
338
    if (NULL === $this->elementsTotal) {
339
      $this->elementsTotal = (int) $this->state->get('simple_sitemap.queue_items_initial_amount', 0);
340 341 342 343 344
    }

    return $this->elementsTotal;
  }

345
  public function getQueuedElementCount($force_recount = FALSE) {
346
    if ($force_recount || NULL === $this->elementsRemaining) {
gbyte.co's avatar
gbyte.co committed
347
      $this->elementsRemaining = $this->queue->numberOfItems();
348 349 350 351 352
    }

    return $this->elementsRemaining;
  }

353
  public function getStashedResultCount() {
354
    return count($this->state->get('simple_sitemap.queue_stashed_results', ['results' => []])['results']);
355 356
  }

357
  public function getProcessedElementCount() {
358
    $initial = $this->getInitialElementCount();
359
    $remaining = $this->getQueuedElementCount();
360

361
    return $initial > $remaining ? ($initial - $remaining) : 0;
362
  }
363 364 365 366

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