Commit 22f0e398 authored by gbyte.co's avatar gbyte.co

Refactor BatchUrlGenerator class, rename simple_sitemap.batch service to...

Refactor BatchUrlGenerator class, rename simple_sitemap.batch service to simple_sitemap.batch_helper
parent 267033ce
......@@ -4,8 +4,6 @@
* Main module file containing hooks.
*/
use Drupal\simple_sitemap\Form\Form;
/**
* Implements hook_help.
*/
......@@ -20,7 +18,7 @@ function simple_sitemap_help($route_name, \Drupal\Core\Routing\RouteMatchInterfa
* Adds sitemap settings to entity types that are supported via plugins.
*/
function simple_sitemap_form_alter(&$form, $form_state, $form_id) {
$f = \Drupal::service('simple_sitemap.form')->processForm($form_state);
$f = \Drupal::service('simple_sitemap.form_helper')->processForm($form_state);
if (!$f->alteringForm)
return;
......@@ -58,7 +56,7 @@ function simple_sitemap_form_alter(&$form, $form_state, $form_id) {
*/
function simple_sitemap_entity_form_submit($form, &$form_state) {
$f = \Drupal::service('simple_sitemap.form')->processForm($form_state);
$f = \Drupal::service('simple_sitemap.form_helper')->processForm($form_state);
$values = $form_state->getValues();
......
......@@ -19,8 +19,8 @@ services:
- @module_handler
- @language_manager
simple_sitemap.form:
class: Drupal\simple_sitemap\Form\Form
simple_sitemap.form_helper:
class: Drupal\simple_sitemap\Form\FormHelper
public: true
arguments:
- @simple_sitemap.generator
......
......@@ -99,7 +99,9 @@ class Batch {
*/
public static function generateBundleUrls($entity_info, $batch_info, &$context) {
BatchUrlGenerator::service()
->generateBundleUrls($entity_info, $batch_info, $context);
->setContext($context)
->setBatchInfo($batch_info)
->generateBundleUrls($entity_info);
}
/**
......@@ -108,10 +110,14 @@ class Batch {
* @param array $custom_paths
* @param array $batch_info
* @param array &$context
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public static function generateCustomUrls($custom_paths, $batch_info, &$context) {
BatchUrlGenerator::service()
->generateCustomUrls($custom_paths, $batch_info, $context);
->setContext($context)
->setBatchInfo($batch_info)
->generateCustomUrls($custom_paths);
}
/**
......@@ -120,9 +126,11 @@ class Batch {
* @param $success
* @param $results
* @param $operations
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public static function finishGeneration($success, $results, $operations) {
BatchUrlGenerator::service()
->finishGeneration($success, $results, $operations);
->finishGeneration($success, $results, $operations);
}
}
......@@ -16,7 +16,9 @@ class BatchUrlGenerator {
use StringTranslationTrait;
const ANONYMOUS_USER_ID = 0;
const PATH_DOES_NOT_EXIST_OR_NO_ACCESS = "The path @path has been omitted from the XML sitemap as it either does not exist, or it is not accessible to anonymous users.";
const PATH_DOES_NOT_EXIST_OR_NO_ACCESS_MESSAGE = "The path @path has been omitted from the XML sitemap as it either does not exist, or it is not accessible to anonymous users.";
const PROCESSING_PATH_MESSAGE = 'Processing path #@current out of @max: @path';
const REGENERATION_FINISHED_MESSAGE= "The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.";
protected $sitemapGenerator;
protected $languages;
......@@ -26,6 +28,9 @@ class BatchUrlGenerator {
protected $logger;
protected $anonUser;
protected $context;
protected $batchInfo;
/**
* BatchUrlGenerator constructor.
* @param $sitemap_generator
......@@ -68,98 +73,107 @@ class BatchUrlGenerator {
return \Drupal::service('simple_sitemap.batch_url_generator');
}
/**
* @param $context
* @return $this
*/
public function setContext(&$context) {
$this->context = &$context;
return $this;
}
/**
* @param $batch_info
* @return bool
* @return $this
*/
protected function isBatch($batch_info) {
return $batch_info['from'] != 'nobatch';
public function setBatchInfo($batch_info) {
$this->batchInfo = $batch_info;
return $this;
}
/**
* @param $context
* @return bool
*/
protected function needsInitialization($context) {
return empty($context['sandbox']);
protected function isBatch() {
return $this->batchInfo['from'] != 'nobatch';
}
/**
* @param $path
* @param $context
* @return bool
*/
protected function pathProcessed($path, &$context) {
$path_pool = isset($context['results']['processed_paths']) ? $context['results']['processed_paths'] : [];
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;
}
$context['results']['processed_paths'][] = $path;
$this->context['results']['processed_paths'][] = $path;
return FALSE;
}
/**
* @param $batch_info
* @param $max
* @param $context
*/
protected function initializeBatch($batch_info, $max, &$context) {
$context['results']['generate'] = !empty($context['results']['generate']) ? $context['results']['generate'] : [];
if ( $this->isBatch($batch_info)) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_id'] = 0;
$context['sandbox']['max'] = $max;
$context['results']['processed_paths'] = !empty($context['results']['processed_paths'])
? $context['results']['processed_paths'] : [];
protected function initializeBatch($max) {
if ($this->needsInitialization()) {
$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
* @param $context
* @return bool
*/
protected function setCurrentId($id, &$context) {
$context['sandbox']['progress']++;
$context['sandbox']['current_id'] = $id;
protected function needsInitialization() {
return empty($this->context['sandbox']);
}
/**
* @param $context
* @param $batch_info
* @param $id
*/
protected function processSegment(&$context, $batch_info) {
if ($this->isBatch($batch_info)) {
$this->setProgressInfo($context);
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($batch_info['max_links']) && count($context['results']['generate']) >= $batch_info['max_links']) {
$chunks = array_chunk($context['results']['generate'], $batch_info['max_links']);
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) == $batch_info['max_links']) {
$remove_sitemap = empty($context['results']['chunk_count']);
if (count($chunk_links) == $this->batchInfo['max_links']) {
$remove_sitemap = empty($this->context['results']['chunk_count']);
$this->sitemapGenerator->generateSitemap($chunk_links, $remove_sitemap);
$context['results']['chunk_count'] = !isset($context['results']['chunk_count'])
? 1 : $context['results']['chunk_count'] + 1;
$context['results']['generate'] = array_slice($context['results']['generate'], count($chunk_links));
$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));
}
}
}
}
/**
* @param $context
*/
protected function setProgressInfo(&$context) {
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
protected function setProgressInfo() {
if ($this->context['sandbox']['progress'] != $this->context['sandbox']['max']) {
// Providing progress info to the batch API.
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
$this->context['finished'] = $this->context['sandbox']['progress'] / $this->context['sandbox']['max'];
// Adding processing message after finishing every batch segment.
end($context['results']['generate']);
$last_key = key($context['results']['generate']);
if (!empty($context['results']['generate'][$last_key]['path'])) {
$context['message'] = t("Processing path @current out of @max: @path", [
'@current' => $context['sandbox']['progress'],
'@max' => $context['sandbox']['max'],
'@path' => HTML::escape($context['results']['generate'][$last_key]['path']),
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']),
]);
}
}
......@@ -169,14 +183,10 @@ class BatchUrlGenerator {
* Batch callback function which generates urls to entity paths.
*
* @param array $entity_info
* @param array $batch_info
* @param array &$context
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public function generateBundleUrls($entity_info, $batch_info, &$context) {
public function generateBundleUrls($entity_info) {
$query = $this->entityQuery->get($entity_info['entity_type_name']);//todo
$query = $this->entityQuery->get($entity_info['entity_type_name']);
if (!empty($entity_info['keys']['id']))
$query->sort($entity_info['keys']['id'], 'ASC');
if (!empty($entity_info['keys']['bundle']))
......@@ -184,15 +194,12 @@ class BatchUrlGenerator {
if (!empty($entity_info['keys']['status']))
$query->condition($entity_info['keys']['status'], 1);
// Initialize batch if not done yet.
if ($this->needsInitialization($context)) {
$count_query = clone $query;
$this->initializeBatch($batch_info, $count_query->count()->execute(), $context);
}
$count_query = clone $query;
$this->initializeBatch($count_query->count()->execute());
// Creating a query limited to n=batch_process_limit entries.
if ($this->isBatch($batch_info)) {
$query->range($context['sandbox']['progress'], $batch_info['batch_process_limit']);
if ($this->isBatch()) {
$query->range($this->context['sandbox']['progress'], $this->batchInfo['batch_process_limit']);
}
$results = $query->execute();
......@@ -200,19 +207,17 @@ class BatchUrlGenerator {
$entities = $this->entityTypeManager->getStorage($entity_info['entity_type_name'])->loadMultiple($results);
foreach ($entities as $entity_id => $entity) {
if ($this->isBatch($batch_info)) {
$this->setCurrentId($entity_id, $context);
}
$this->setCurrentId($entity_id);
// Overriding entity settings if it has been overridden on entity edit page...
if (isset($batch_info['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index'])) {
if (isset($this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index'])) {
// Skipping entity if it has been excluded on entity edit page.
if (!$batch_info['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index']) {
if (!$this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index']) {
continue;
}
// Otherwise overriding priority settings for this entity.
$priority = $batch_info['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['priority'];
$priority = $this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['priority'];
}
switch ($entity_info['entity_type_name']) {
......@@ -235,7 +240,7 @@ class BatchUrlGenerator {
// Do not include paths that have been already indexed.
$path = $url_object->getInternalPath();
if ($batch_info['remove_duplicates'] && $this->pathProcessed($path, $context))
if ($this->batchInfo['remove_duplicates'] && $this->pathProcessed($path))
continue;
$url_object->setOption('absolute', TRUE);
......@@ -251,42 +256,33 @@ class BatchUrlGenerator {
$alternate_urls = [];
foreach ($this->languages as $language) {
$langcode = $language->getId();
if (!$batch_info['skip_untranslated'] || $language->isDefault() || $entity->hasTranslation($langcode)) {
if (!$this->batchInfo['skip_untranslated'] || $language->isDefault() || $entity->hasTranslation($langcode)) {
$url_object->setOption('language', $language);
$alternate_urls[$langcode] = $url_object->toString();
}
}
foreach($alternate_urls as $langcode => $url) {
$context['results']['generate'][] = $path_data + ['langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
$this->context['results']['generate'][] = $path_data + ['langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
}
}
}
$this->processSegment($context, $batch_info);
$this->processSegment();
}
/**
* Batch function which generates urls to custom paths.
*
* @param array $custom_paths
* @param array $batch_info
* @param array &$context
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public function generateCustomUrls($custom_paths, $batch_info, &$context) {
public function generateCustomUrls($custom_paths) {
// Initialize batch if not done yet.
if ($this->needsInitialization($context)) {
$this->initializeBatch($batch_info, count($custom_paths), $context);
}
$this->initializeBatch(count($custom_paths));
foreach($custom_paths as $i => $custom_path) {
if ($this->isBatch($batch_info)) {
$this->setCurrentId($i, $context);
}
$this->setCurrentId($i);
if (!$this->pathValidator->isValid($custom_path['path'])) { //todo: Change to different function, as this also checks if current user has access. The user however varies depending if process was started from the web interface or via cron/drush. Use getUrlIfValidWithoutAccessCheck()?
$this->logger->registerError([self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS, ['@path' => $custom_path['path']]], 'warning');
$this->logger->registerError([self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS_MESSAGE, ['@path' => $custom_path['path']]], 'warning');
continue;
}
$url_object = Url::fromUserInput($custom_path['path'], ['absolute' => TRUE]);
......@@ -295,7 +291,7 @@ class BatchUrlGenerator {
continue;
$path = $url_object->getInternalPath();
if ($batch_info['remove_duplicates'] && $this->pathProcessed($path, $context))
if ($this->batchInfo['remove_duplicates'] && $this->pathProcessed($path))
continue;
// Load entity object if this is an entity route.
......@@ -315,16 +311,16 @@ class BatchUrlGenerator {
$alternate_urls = [];
foreach ($this->languages as $language) {
$langcode = $language->getId();
if (!$batch_info['skip_untranslated'] || is_null($entity) || $entity->hasTranslation($langcode) || $language->isDefault()) {
if (!$this->batchInfo['skip_untranslated'] || is_null($entity) || $entity->hasTranslation($langcode) || $language->isDefault()) {
$url_object->setOption('language', $language);
$alternate_urls[$langcode] = $url_object->toString();
}
}
foreach($alternate_urls as $langcode => $url) {
$context['results']['generate'][] = $path_data + ['langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
$this->context['results']['generate'][] = $path_data + ['langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
}
}
$this->processSegment($context, $batch_info);
$this->processSegment();
}
/**
......@@ -339,7 +335,7 @@ class BatchUrlGenerator {
$this->sitemapGenerator->generateSitemap($results['generate'], $remove_sitemap);
}
Cache::invalidateTags(['simple_sitemap']);
drupal_set_message($this->t("The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.",
drupal_set_message($this->t(self::REGENERATION_FINISHED_MESSAGE,
['@url' => $GLOBALS['base_url'] . '/sitemap.xml']));
}
else {
......
......@@ -5,10 +5,10 @@ namespace Drupal\simple_sitemap\Form;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Class Form
* Class FormHelper
* @package Drupal\simple_sitemap\Form
*/
class Form {
class FormHelper {
use StringTranslationTrait;
const PRIORITY_DEFAULT = 0.5;
......@@ -269,7 +269,7 @@ class Form {
* @return bool
* TRUE if simple_sitemap form values have been altered by the user.
*/
public function valuesChanged($form, $values) { //todo make non-static
public function valuesChanged($form, $values) {
foreach (self::$valuesToCheck as $field_name) {
if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
return TRUE;
......
......@@ -25,7 +25,7 @@ class SimplesitemapCustomLinksForm extends SimplesitemapFormBase {
$setting_string = '';
foreach ($this->generator->getConfig('custom') as $custom_link) {
$setting_string .= isset($custom_link['priority'])
? $custom_link['path'] . ' ' . $this->form->formatPriority($custom_link['priority'])
? $custom_link['path'] . ' ' . $this->formHelper->formatPriority($custom_link['priority'])
: $custom_link['path'];
$setting_string .= "\r\n";
}
......@@ -44,7 +44,7 @@ class SimplesitemapCustomLinksForm extends SimplesitemapFormBase {
'#description' => $this->t("Please specify drupal internal (relative) paths, one per line. Do not forget to prepend the paths with a '/'. You can optionally add a priority (0.0 - 1.0) by appending it to the path after a space. The home page with the highest priority would be <em>/ 1.0</em>, the contact page with the default priority would be <em>/contact 0.5</em>."),
];
$this->form->displayRegenerateNow($form['simple_sitemap_custom']);
$this->formHelper->displayRegenerateNow($form['simple_sitemap_custom']);
return parent::buildForm($form, $form_state);
}
......@@ -68,7 +68,7 @@ class SimplesitemapCustomLinksForm extends SimplesitemapFormBase {
}
// Making sure the priority is formatted correctly.
if (isset($link_config['priority']) && !Form::isValidPriority($link_config['priority'])) {
if (isset($link_config['priority']) && !FormHelper::isValidPriority($link_config['priority'])) {
$form_state->setErrorByName('', $this->t("<strong>Line @line</strong>: The priority setting <em>@priority</em> for path <em>@path</em> is incorrect. Set the priority from 0.0 to 1.0.", $placeholders));
}
}
......
......@@ -39,7 +39,7 @@ class SimplesitemapEntitiesForm extends SimplesitemapFormBase {
}
asort($entity_type_labels);
$this->form->processForm($form_state);
$this->formHelper->processForm($form_state);
foreach ($entity_type_labels as $entity_type_id => $entity_type_label) {
$form['simple_sitemap_entities']['entities'][$entity_type_id] = [
......@@ -56,14 +56,14 @@ class SimplesitemapEntitiesForm extends SimplesitemapFormBase {
$form['#attached']['drupalSettings']['simple_sitemap']['all_entities'][] = str_replace('_', '-', $entity_type_id);
if ($this->generator->entityTypeIsAtomic($entity_type_id)) {
$form['simple_sitemap_entities']['entities'][$entity_type_id][$entity_type_id . '_enabled']['#description'] = $this->t('Sitemap settings for this entity type can be set below and overridden on its entity pages.');
$this->form->setEntityCategory('bundle')
$this->formHelper->setEntityCategory('bundle')
->setEntityTypeId($entity_type_id)
->setBundleName($entity_type_id)
->displayEntitySettings($form['simple_sitemap_entities']['entities'][$entity_type_id][$entity_type_id . '_settings'], TRUE);
$form['#attached']['drupalSettings']['simple_sitemap']['atomic_entities'][] = str_replace('_', '-', $entity_type_id);
}
}
$this->form->displayRegenerateNow($form['simple_sitemap_entities']['entities']);
$this->formHelper->displayRegenerateNow($form['simple_sitemap_entities']['entities']);
return parent::buildForm($form, $form_state);
}
......
......@@ -12,19 +12,19 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class SimplesitemapFormBase extends ConfigFormBase {
protected $generator;
protected $form;
protected $formHelper;
protected $pathValidator;
/**
* SimplesitemapFormBase constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $generator
* @param $form
* @param $form_helper
* @param $path_validator
*/
public function __construct($generator, $form, $path_validator) {
public function __construct($generator, $form_helper, $path_validator) {
$this->generator = $generator;
$this->form = $form;
$this->formHelper = $form_helper;
$this->pathValidator = $path_validator;
}
......@@ -34,7 +34,7 @@ abstract class SimplesitemapFormBase extends ConfigFormBase {
public static function create(ContainerInterface $container) {
return new static(
$container->get('simple_sitemap.generator'),
$container->get('simple_sitemap.form'),
$container->get('simple_sitemap.form_helper'),
$container->get('path.validator')
);
}
......
......@@ -10,7 +10,7 @@ use Drupal\Core\Form\FormStateInterface;
*/
class SimplesitemapSettingsForm extends SimplesitemapFormBase {
private $form_settings = [
private $formSettings = [
'max_links',
'cron_generate',
'remove_duplicates',
......@@ -94,7 +94,7 @@ class SimplesitemapSettingsForm extends SimplesitemapFormBase {
'#required' => TRUE,
];
$this->form->displayRegenerateNow($form['simple_sitemap_settings']);
$this->formHelper->displayRegenerateNow($form['simple_sitemap_settings']);
return parent::buildForm($form, $form_state);
}
......@@ -108,7 +108,7 @@ class SimplesitemapSettingsForm extends SimplesitemapFormBase {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach($this->form_settings as $setting_name) {
foreach($this->formSettings as $setting_name) {
$this->generator->saveSetting($setting_name, $form_state->getValue($setting_name));
}
parent::submitForm($form, $form_state);
......
......@@ -3,7 +3,7 @@
namespace Drupal\simple_sitemap;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\simple_sitemap\Form\Form;
use Drupal\simple_sitemap\Form\FormHelper;
/**
* Class Simplesitemap
......@@ -24,17 +24,17 @@ class Simplesitemap {
/**
* Simplesitemap constructor.
* @param $sitemapGenerator
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface
* @param $configFactoryInterface
* @param $database
* @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
* @param $entityTypeManager
* @param $pathValidator
* @param $dateFormatter
*/
public function __construct(
$sitemapGenerator,
\Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface,
$configFactoryInterface,
$database,
\Drupal\Core\Entity\EntityTypeManager $entityTypeManager,
$entityTypeManager,
$pathValidator,
$dateFormatter
) {
......@@ -313,7 +313,7 @@ class Simplesitemap {
if (in_array($setting_key, self::$allowed_link_settings[$type])) {
switch($setting_key) {
case 'priority':
if (!Form::isValidPriority($setting)) {
if (!FormHelper::isValidPriority($setting)) {
// todo: register error
continue;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment