QueueWorker.php 10 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

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

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

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

  /**
   * @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
91
   * @param \Drupal\simple_sitemap\Queue\SimplesitemapQueue $element_queue
92
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
93 94 95 96 97
   */
  public function __construct(SimplesitemapSettings $settings,
                              SimplesitemapManager $manager,
                              State $state,
                              ModuleHandler $module_handler,
gbyte.co's avatar
gbyte.co committed
98
                              SimplesitemapQueue $element_queue,
99
                              LockBackendInterface $lock) {
100 101 102 103
    $this->settings = $settings;
    $this->manager = $manager;
    $this->state = $state;
    $this->moduleHandler = $module_handler;
gbyte.co's avatar
gbyte.co committed
104
    $this->queue = $element_queue;
105 106 107
    $this->lock = $lock;
  }

gbyte.co's avatar
gbyte.co committed
108 109 110
  /**
   * @return $this
   */
111
  public function deleteQueue() {
gbyte.co's avatar
gbyte.co committed
112
    $this->queue->deleteQueue();
113
    SitemapGeneratorBase::removeSitemapVariant(NULL, 'unpublished');
114 115 116 117 118 119 120 121 122 123 124
    $this->variantProcessedNow = NULL;
    $this->generatorProcessedNow = NULL;
    $this->results = [];
    $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;
  }

gbyte.co's avatar
gbyte.co committed
125 126
  public function getQueue() {
    return $this->queue;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 180 181 182 183 184 185 186
  }

  /**
   * @param null $variants
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *
   * @todo Lock functionality
   */
  public function rebuildQueue($variants = NULL) {
    $variants = NULL === $variants ? NULL : (array) $variants;

    $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.
      if (NULL !== $variants && !in_array($variant_name, $variants)) {
        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);
    }
    $this->getRemainingElementCount(TRUE);

    return $this;
  }

  protected function queueElements($elements) {
gbyte.co's avatar
gbyte.co committed
187
    $this->queue->createItems($elements);
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    $this->state->set('simple_sitemap.queue_items_initial_amount', ($this->state->get('simple_sitemap.queue_items_initial_amount') + count($elements)));
  }

  /**
   * @param null $variants
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   *
   * @todo Lock functionality
   */
  public function generateSitemap($variants = NULL) {
    $variants = NULL === $variants ? NULL : (array) $variants;

    $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),
      'remove_duplicates' => $this->settings->getSetting('remove_duplicates', TRUE), //todo
      'excluded_languages' => $this->settings->getSetting('excluded_languages', []),
    ];
    $this->maxLinks = $this->settings->getSetting('max_links');
    $max_execution_time = $this->settings->getSetting('generate_duration', 10000);
    $elements_processed = 0;
    Timer::start('simple_sitemap_generator');

    $this->unstashResults();

    if ($this->getRemainingElementCount() === 0 && empty($this->results)) {
      $this->rebuildQueue($variants);
    }

gbyte.co's avatar
gbyte.co committed
219
    while ($element = $this->queue->claimItem()) {
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

      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'];
        }

        $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
247
      $this->queue->deleteItem($element); //todo May want to use deleteItems() instead.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 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 318 319 320 321 322 323
      $elements_processed++;
      $this->elementsRemaining--;
    }

    if ($this->getRemainingElementCount() === 0) {
      $this->generateVariantChunksFromResults(TRUE);
      $this->publishCurrentVariant();
    }
    else {
      $this->stashResults();
    }

    return $this;
  }

  protected function generateResultsFromElement($element) {
    $this->results = array_merge(
      $this->results,
      $this->manager->getUrlGenerator($element->data['url_generator'])
        ->setSitemapVariant($this->variantProcessedNow)
        ->setSettings($this->generatorSettings)
        ->generate($element->data['data']));
  }

  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,
      'results' => $this->results
    ]);
    $this->results = [];
    $this->generatorProcessedNow = NULL;
    $this->variantProcessedNow = NULL;
  }

  protected function unstashResults() {
    if ($this->state->has('simple_sitemap.queue_stashed_results')) {
      $results = $this->state->get('simple_sitemap.queue_stashed_results');
      $this->state->delete('simple_sitemap.queue_stashed_results');
      $this->results = is_array($results['results']) ? $results['results'] : [];
      $this->variantProcessedNow = $results['variant'];
      $this->generatorProcessedNow = $results['generator'];
    }
  }

324
  public function getInitialElementCount() {
325 326 327 328 329 330 331 332 333 334 335
    if (NULL === $this->elementsTotal) {
      $this->elementsTotal = !empty($original = $this->state->get('simple_sitemap.queue_items_initial_amount'))
        ? (int) $original
        : 0;
    }

    return $this->elementsTotal;
  }

  public function getRemainingElementCount($force_recount = FALSE) {
    if ($force_recount || NULL === $this->elementsRemaining) {
gbyte.co's avatar
gbyte.co committed
336
      $this->elementsRemaining = $this->queue->numberOfItems();
337 338 339 340 341 342
    }

    return $this->elementsRemaining;
  }

  public function getProcessedElementCount() {
343
    $original = $this->getInitialElementCount();
344 345 346 347 348 349
    $remaining = $this->getRemainingElementCount();

    return $remaining <= $original ? ($original - $remaining) : 0;
  }
}