UrlGeneratorBase.php 9.86 KB
Newer Older
1
2
<?php

Pawel G's avatar
Pawel G committed
3
namespace Drupal\simple_sitemap\Batch\Generator;
4
5

use Drupal\Component\Utility\Html;
Pawel G's avatar
Pawel G committed
6
use Drupal\Core\Entity\ContentEntityBase;
7
use Drupal\Core\Entity\Entity;
8
use Drupal\Core\StringTranslation\StringTranslationTrait;
Pawel G's avatar
Pawel G committed
9
use Drupal\Core\Url;
10
use Drupal\simple_sitemap\EntityHelper;
Pawel G's avatar
Pawel G committed
11
use Drupal\simple_sitemap\Logger;
Pawel G's avatar
Pawel G committed
12
use Drupal\simple_sitemap\Simplesitemap;
Pawel G's avatar
Pawel G committed
13
14
15
16
use Drupal\simple_sitemap\SitemapGenerator;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\PathValidator;
17
18

/**
Pawel G's avatar
Pawel G committed
19
20
 * Class UrlGeneratorBase
 * @package Drupal\simple_sitemap\Batch\Generator
21
 */
Pawel G's avatar
Pawel G committed
22
class UrlGeneratorBase {
23
24
25
26

  use StringTranslationTrait;

  const ANONYMOUS_USER_ID = 0;
27
  const PROCESSING_PATH_MESSAGE = 'Processing path #@current out of @max: @path';
28

Pawel G's avatar
Pawel G committed
29
30
31
  /**
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
Pawel G's avatar
Pawel G committed
32
  protected $generator;
Pawel G's avatar
Pawel G committed
33
34
35
36

  /**
   * @var \Drupal\simple_sitemap\SitemapGenerator
   */
37
  protected $sitemapGenerator;
Pawel G's avatar
Pawel G committed
38
39
40
41

  /**
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
42
  protected $languageManager;
Pawel G's avatar
Pawel G committed
43
44
45
46

  /**
   * @var \Drupal\Core\Language\LanguageInterface[]
   */
47
  protected $languages;
Pawel G's avatar
Pawel G committed
48
49
50
51

  /**
   * @var string
   */
52
  protected $defaultLanguageId;
Pawel G's avatar
Pawel G committed
53
54
55
56

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
57
  protected $entityTypeManager;
Pawel G's avatar
Pawel G committed
58
59
60

  /**
   * @var \Drupal\Core\Path\PathValidator
Pawel G's avatar
Pawel G committed
61
62
   *
   * @todo Move to CustomUrlGenerator
Pawel G's avatar
Pawel G committed
63
   */
64
  protected $pathValidator;
Pawel G's avatar
Pawel G committed
65
66
67
68

  /**
   * @var \Drupal\simple_sitemap\Logger
   */
Pawel G's avatar
Pawel G committed
69
  protected $logger;
Pawel G's avatar
Pawel G committed
70
71
72
73

  /**
   * @var \Drupal\Core\Entity\EntityInterface|null
   */
74
75
  protected $anonUser;

Pawel G's avatar
Pawel G committed
76
77
78
  /**
   * @var array
   */
79
  protected $context;
Pawel G's avatar
Pawel G committed
80
81
82
83

  /**
   * @var array
   */
84
85
  protected $batchInfo;

86
  /**
87
88
89
90
91
92
   * @var \Drupal\simple_sitemap\EntityHelper
   */
  protected $entityHelper;

  /**
   * UrlGeneratorBase constructor.
Pawel G's avatar
Pawel G committed
93
94
95
96
97
98
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
   * @param \Drupal\simple_sitemap\SitemapGenerator $sitemap_generator
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\Core\Path\PathValidator $path_validator
   * @param \Drupal\simple_sitemap\Logger $logger
99
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
100
   */
101
  public function __construct(
Pawel G's avatar
Pawel G committed
102
103
    Simplesitemap $generator,
    SitemapGenerator $sitemap_generator, //todo: use $this->generator->sitemapGenerator instead?
Pawel G's avatar
Pawel G committed
104
105
106
    LanguageManagerInterface $language_manager,
    EntityTypeManagerInterface $entity_type_manager,
    PathValidator $path_validator,
107
108
    Logger $logger,
    EntityHelper $entityHelper
109
  ) {
Pawel G's avatar
Pawel G committed
110
    $this->generator = $generator;
Pawel G's avatar
Pawel G committed
111
    $this->sitemapGenerator = $sitemap_generator; // todo: using only one method, maybe make method static instead?
112
    $this->languageManager = $language_manager;
113
    $this->languages = $language_manager->getLanguages();
114
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
115
116
    $this->entityTypeManager = $entity_type_manager;
    $this->pathValidator = $path_validator;
Pawel G's avatar
Pawel G committed
117
    $this->logger = $logger;
118
    $this->entityHelper = $entityHelper;
Pawel G's avatar
Pawel G committed
119
120
    $this->anonUser = $this->entityTypeManager->getStorage('user')
      ->load(self::ANONYMOUS_USER_ID);
121
122
  }

123
124
125
126
127
128
129
130
131
  /**
   * @param $context
   * @return $this
   */
  public function setContext(&$context) {
    $this->context = &$context;
    return $this;
  }

132
  /**
Pawel G's avatar
Pawel G committed
133
   * @param array $batch_info
134
   * @return $this
135
   */
Pawel G's avatar
Pawel G committed
136
  public function setBatchInfo(array $batch_info) {
137
138
    $this->batchInfo = $batch_info;
    return $this;
139
140
  }

141
142
143
144
145
146
147
148
  /**
   * @return bool
   */
  protected function isBatch() {
    return $this->batchInfo['from'] != 'nobatch';
  }

  /**
Pawel G's avatar
Pawel G committed
149
   * @param string $path
150
151
152
153
154
155
156
157
158
159
160
   * @return bool
   */
  protected function pathProcessed($path) {
    $path_pool = isset($this->context['results']['processed_paths']) ? $this->context['results']['processed_paths'] : [];
    if (in_array($path, $path_pool)) {
      return TRUE;
    }
    $this->context['results']['processed_paths'][] = $path;
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
161
162
163
164
165
166
167
168
169
170
171
172
173
  /**
   * @param array $path_data
   * @param \Drupal\Core\Url|NULL $url_object
   */
  protected function addUrl(array $path_data, Url $url_object = NULL) {
    if ($url_object !== NULL) {
      $this->addUrlVariants($path_data, $url_object);
    }
    else {
      $this->context['results']['generate'][] = $path_data;
    }
  }

174
  /**
175
   * @param Url $url_object
Pawel G's avatar
Pawel G committed
176
   * @param array $path_data
177
   */
Pawel G's avatar
Pawel G committed
178
  protected function addUrlVariants(array $path_data, Url $url_object) {
179
    $alternate_urls = [];
Pawel G's avatar
Pawel G committed
180
    $entity = $this->entityHelper->getEntityFromUrlObject($url_object);
181
    $translation_languages = $entity instanceof ContentEntityBase && $this->batchInfo['skip_untranslated']
Pawel G's avatar
Pawel G committed
182
183
      ? $entity->getTranslationLanguages()
      : $this->languages;
184

185
    // Entity is not translated.
186
    if ($entity instanceof ContentEntityBase && isset($translation_languages['und'])) {
187
188
      if ($url_object->access($this->anonUser)) {
        $url_object->setOption('language', $this->languages[$this->defaultLanguageId]);
189
        $alternate_urls[$this->defaultLanguageId] = $this->replaceBaseUrlWithCustom($url_object->toString());
190
      }
191
192
    }
    else {
193
194
      // Including only translated variants of content entity.
      if ($entity instanceof ContentEntityBase && $this->batchInfo['skip_untranslated']) {
195
        foreach ($translation_languages as $language) {
196
          $translation = $entity->getTranslation($language->getId());
197
198
          if ($translation->access('view', $this->anonUser)) {
            $url_object->setOption('language', $language);
199
            $alternate_urls[$language->getId()] = $this->replaceBaseUrlWithCustom($url_object->toString());
200
          }
201
        }
202
203
      }

204
      // Not a content entity or including all untranslated variants.
205
206
207
      elseif ($url_object->access($this->anonUser)) {
        foreach ($translation_languages as $language) {
          $url_object->setOption('language', $language);
208
          $alternate_urls[$language->getId()] = $this->replaceBaseUrlWithCustom($url_object->toString());
209
        }
210
211
      }
    }
212

Pawel G's avatar
Pawel G committed
213
    foreach ($alternate_urls as $langcode => $url) {
Pawel G's avatar
Pawel G committed
214
215
      $this->context['results']['generate'][] = $path_data + [
        'langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
216
    }
217
218
  }

219
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
247
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
  /**
   * @return bool
   */
  protected function needsInitialization() {
    return empty($this->context['sandbox']);
  }

  /**
   * @param $max
   */
  protected function initializeBatch($max) {
    $this->context['results']['generate'] = !empty($this->context['results']['generate']) ? $this->context['results']['generate'] : [];
    if ($this->isBatch()) {
      $this->context['sandbox']['progress'] = 0;
      $this->context['sandbox']['current_id'] = 0;
      $this->context['sandbox']['max'] = $max;
      $this->context['results']['processed_paths'] = !empty($this->context['results']['processed_paths'])
        ? $this->context['results']['processed_paths'] : [];
    }
  }

  /**
   * @param $id
   */
  protected function setCurrentId($id) {
    if ($this->isBatch()) {
      $this->context['sandbox']['progress']++;
      $this->context['sandbox']['current_id'] = $id;
    }
  }

  /**
   *
   */
  protected function processSegment() {
    if ($this->isBatch()) {
      $this->setProgressInfo();
    }
    if (!empty($this->batchInfo['max_links']) && count($this->context['results']['generate']) >= $this->batchInfo['max_links']) {
      $chunks = array_chunk($this->context['results']['generate'], $this->batchInfo['max_links']);
      foreach ($chunks as $i => $chunk_links) {
        if (count($chunk_links) == $this->batchInfo['max_links']) {
          $remove_sitemap = empty($this->context['results']['chunk_count']);
          $this->sitemapGenerator->generateSitemap($chunk_links, $remove_sitemap);
          $this->context['results']['chunk_count'] = !isset($this->context['results']['chunk_count'])
            ? 1 : $this->context['results']['chunk_count'] + 1;
          $this->context['results']['generate'] = array_slice($this->context['results']['generate'], count($chunk_links));
        }
      }
    }
  }

  /**
   *
   */
  protected function setProgressInfo() {
    if ($this->context['sandbox']['progress'] != $this->context['sandbox']['max']) {
      // Providing progress info to the batch API.
      $this->context['finished'] = $this->context['sandbox']['progress'] / $this->context['sandbox']['max'];
      // Adding processing message after finishing every batch segment.
      end($this->context['results']['generate']);
      $last_key = key($this->context['results']['generate']);
      if (!empty($this->context['results']['generate'][$last_key]['path'])) {
        $this->context['message'] = $this->t(self::PROCESSING_PATH_MESSAGE, [
          '@current' => $this->context['sandbox']['progress'],
          '@max' => $this->context['sandbox']['max'],
          '@path' => HTML::escape($this->context['results']['generate'][$last_key]['path']),
        ]);
      }
    }
  }

291
292
293
294
295
  /**
   * @param string $url
   * @return string
   */
  protected function replaceBaseUrlWithCustom($url) {
296
297
298
299
    return !empty($this->batchInfo['base_url'])
      ? str_replace($GLOBALS['base_url'], $this->batchInfo['base_url'], $url)
      : $url;
  }
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

  /**
   * @param array $elements
   * @return array
   */
  protected function getBatchIterationElements(array $elements) {
    if ($this->needsInitialization()) {
      $this->initializeBatch(count($elements));
    }

    if ($this->isBatch()) {
      $elements = array_slice($elements, $this->context['sandbox']['progress'], $this->batchInfo['batch_process_limit']);
    }

    return $elements;
  }
Pawel G's avatar
Pawel G committed
316
317
318
319
320
321
322
323
324

  /**
   * @param $entity_type_name
   * @param $entity_id
   * @return array
   */
  protected function getImages($entity_type_name, $entity_id) {
    $images = [];
    foreach ($this->entityHelper->getEntityImageUrls($entity_type_name, $entity_id) as $Url) {
325
      $images[]['path'] = $this->replaceBaseUrlWithCustom($Url);
Pawel G's avatar
Pawel G committed
326
327
328
    }
    return $images;
  }
329
}