Commit b7aeda24 authored by gbyte.co's avatar gbyte.co Committed by gbyte.co

Issue #2961236 by gbyte.co: Allow assigning any bundle to any sitemap variant via UI

parent 8658b74e
......@@ -39,7 +39,7 @@ simple_sitemap.settings:
sequence:
type: string
simple_sitemap.bundle_settings.*.*:
simple_sitemap.bundle_settings.*.*.*:
label: 'Entity bundle settings'
type: config_object
mapping:
......
......@@ -12,6 +12,7 @@
var vals = [];
if ($(context).find('#edit-simple-sitemap-index-content-1').is(':checked')) {
vals.push(Drupal.t('Included in sitemap'));
vals.push(Drupal.t('Variant') + ': ' + $('#edit-simple-sitemap-variant option:selected', context).text());
vals.push(Drupal.t('Priority') + ': ' + $('#edit-simple-sitemap-priority option:selected', context).text());
vals.push(Drupal.t('Change frequency') + ': ' + $('#edit-simple-sitemap-changefreq option:selected', context).text());
vals.push(Drupal.t('Include images') + ': ' + $('#edit-simple-sitemap-include-images option:selected', context).text());
......
......@@ -12,36 +12,13 @@
// On load: Hide the 'Regenerate sitemap' field to only display it if settings have changed.
$('.form-item-simple-sitemap-regenerate-now').hide();
// On load: Show or hide settings dependant on 'enabled' setting.
if ($('#edit-simple-sitemap-index-content-1').is(':checked')) {
$('.form-item-simple-sitemap-priority').show();
$('.form-item-simple-sitemap-changefreq').show();
$('.form-item-simple-sitemap-include-images').show();
}
else {
$('.form-item-simple-sitemap-priority').hide();
$('.form-item-simple-sitemap-changefreq').hide();
$('.form-item-simple-sitemap-include-images').hide();
}
// On change: Show or hide settings dependant on 'enabled' setting.
$("#edit-simple-sitemap-index-content").change(function() {
if ($('#edit-simple-sitemap-index-content-1').is(':checked')) {
$('.form-item-simple-sitemap-priority').show();
$('.form-item-simple-sitemap-changefreq').show();
$('.form-item-simple-sitemap-include-images').show();
}
else {
$('.form-item-simple-sitemap-priority').hide();
$('.form-item-simple-sitemap-changefreq').hide();
$('.form-item-simple-sitemap-include-images').hide();
}
// Show 'Regenerate sitemap' field if 'enabled' setting has changed.
$('.form-item-simple-sitemap-regenerate-now').show();
});
// Show 'Regenerate sitemap' field if settings have changed.
$("#edit-simple-sitemap-priority, #edit-simple-sitemap-changefreq, #edit-simple-sitemap-include-images").change(function() {
$("#edit-simple-sitemap-index-content"
+ ", #edit-simple-sitemap-variant"
+ ", #edit-simple-sitemap-priority"
+ ", #edit-simple-sitemap-changefreq"
+ ", #edit-simple-sitemap-include-images"
).change(function() {
$('.form-item-simple-sitemap-regenerate-now').show();
});
}
......
......@@ -36,44 +36,18 @@
});
});
// Show settings if atomic entity enabled on form load.
$.each(atomicEntities, function(index, value) {
var enabledId = '#edit-' + value + '-enabled';
var priorityId = '.form-item-' + value + '-simple-sitemap-priority';
var changefreqId = '.form-item-' + value + '-simple-sitemap-changefreq';
var includeImagesId = '.form-item-' + value + '-simple-sitemap-include-images';
// On load: Show or hide settings dependent on 'enabled' checkbox.
if ($(enabledId).is(':checked')) {
$(priorityId).show();
$(changefreqId).show();
$(includeImagesId).show();
}
else {
$(priorityId).hide();
$(changefreqId).hide();
$(includeImagesId).hide();
}
// On change: Show or hide settings dependent on 'enabled' checkbox.
$(enabledId).change(function() {
if ($(enabledId).is(':checked')) {
$(priorityId).show();
$(changefreqId).show();
$(includeImagesId).show();
}
else {
$(priorityId).hide();
$(changefreqId).hide();
$(includeImagesId).hide();
}
});
// Show 'Regenerate sitemap' field if settings have changed.
$(priorityId, changefreqId, includeImagesId).change(function() {
$('.form-item-simple-sitemap-regenerate-now').show();
});
});
// todo
// Show 'Regenerate sitemap' field if settings have changed.
// $.each(atomicEntities, function(index, value) {
// var variant = '.form-item-' + value + '-simple-sitemap-variant';
// var priorityId = '.form-item-' + value + '-simple-sitemap-priority';
// var changefreqId = '.form-item-' + value + '-simple-sitemap-changefreq';
// var includeImagesId = '.form-item-' + value + '-simple-sitemap-include-images';
//
// $(variant, priorityId, changefreqId, includeImagesId).change(function() {
// $('.form-item-simple-sitemap-regenerate-now').show();
// });
// });
}
};
})(jQuery);
......@@ -27,39 +27,41 @@ function simple_sitemap_requirements($phase) {
case 'runtime':
$generator = \Drupal::service('simple_sitemap.generator');
$generated_ago = $generator->getGeneratedAgo(\Drupal\simple_sitemap\SimplesitemapManager::DEFAULT_SITEMAP_VARIANT); //todo
$cron_generation = $generator->getSetting('cron_generate');
if (!$generated_ago) {
$value = t('Not available');
$description = t($cron_generation
? 'Run cron, or <a href="@generate">generate</a> the sitemap manually.'
: 'Generation on cron run is disabled. <a href="@generate">Generate</a> the sitemap manually.', [
'@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'
]
);
$severity = REQUIREMENT_WARNING;
}
else {
$value = t('XML sitemaps are available');
$description = t('The last generation finished @ago ago.'
. ' ' . ($cron_generation
? 'Run cron, or <a href="@generate">regenerate</a> the sitemaps manually.'
: 'Generation on cron run is disabled. <a href="@generate">Regenerate</a> the sitemaps manually.'), [
'@ago' => $generated_ago,
'@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'
]
);
$severity = REQUIREMENT_INFO;
}
$requirements['simple_sitemap_generated'] = [
'title' => 'Simple XML sitemap',
'value' => $value,
'description' => $description,
'severity' => $severity,
];
// todo Implement for 3.x
// /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
// $generator = \Drupal::service('simple_sitemap.generator');
// $generated_ago = $generator->getGeneratedAgo();
// $cron_generation = $generator->getSetting('cron_generate');
//
// if (!$generated_ago) {
// $value = t('Not available');
// $description = t($cron_generation
// ? 'Run cron, or <a href="@generate">generate</a> the sitemap manually.'
// : 'Generation on cron run is disabled. <a href="@generate">Generate</a> the sitemap manually.', [
// '@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'
// ]
// );
// $severity = REQUIREMENT_WARNING;
// }
// else {
// $value = t('XML sitemaps are available');
// $description = t('The last generation finished @ago ago.'
// . ' ' . ($cron_generation
// ? 'Run cron, or <a href="@generate">regenerate</a> the sitemaps manually.'
// : 'Generation on cron run is disabled. <a href="@generate">Regenerate</a> the sitemaps manually.'), [
// '@ago' => $generated_ago,
// '@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'
// ]
// );
// $severity = REQUIREMENT_INFO;
// }
//
// $requirements['simple_sitemap_generated'] = [
// 'title' => 'Simple XML sitemap',
// 'value' => $value,
// 'description' => $description,
// 'severity' => $severity,
// ];
break;
}
return $requirements;
......@@ -142,6 +144,12 @@ function simple_sitemap_schema() {
'not null' => TRUE,
'unsigned' => TRUE,
],
'type' => [
'description' => 'Type of sitemap this override belongs to.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
],
'entity_type' => [
'description' => 'Entity type of the overriding entity.',
'type' => 'varchar',
......@@ -459,8 +467,6 @@ function simple_sitemap_update_8210() {
]
);
}
return t('The XML sitemap needs to be regenerated.');
}
/**
......@@ -607,7 +613,52 @@ function simple_sitemap_update_8215() {
}
$type->set('variants', $variants)->save();
}
}
/**
* Adding per-variant bundle and entity override configuration.
*/
function simple_sitemap_update_8216() {
$config_factory = \Drupal::service('config.factory');
$default_variant = $config_factory->get('simple_sitemap.settings')->get('default_variant');
if (empty($default_variant)) {
$default_variant = 'default';
$config_factory->getEditable('simple_sitemap.settings')
->set('default_variant', $default_variant)
->save();
}
/** @var \Drupal\simple_sitemap\SimplesitemapManager $manager */
$manager = \Drupal::service('simple_sitemap.manager');
$variants = $manager->getSitemapVariants();
if (!isset($variants[$default_variant])) {
$manager->addSitemapVariant($default_variant);
}
foreach ($config_factory->listAll('simple_sitemap.bundle_settings.') as $bundle_config_name) {
/** @var \Drupal\Core\Config\Config $config */
$config = $config_factory->getEditable($bundle_config_name);
$config_name_parts = explode('.', $bundle_config_name);
$config_factory->getEditable($config_name_parts[0] . '.' . $config_name_parts[1]
. '.' . $default_variant . '.' . $config_name_parts[2] . '.' . $config_name_parts[3])
->setData($config->get())->save();
$config->delete();
}
$database = \Drupal::database();
if (!$database->schema()->fieldExists('simple_sitemap_entity_overrides', 'type')) {
$database->schema()->addField(
'simple_sitemap_entity_overrides',
'type', [
'description' => 'Type of sitemap this override belongs to.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
'initial' => 'default',
]
);
}
return t('The XML sitemaps need to be regenerated.');
}
......@@ -49,8 +49,7 @@ function simple_sitemap_form_alter(&$form, FormStateInterface $form_state, $form
];
// Attach some js magic to forms.
// todo: JS not working on comment entity form, hence disabling.
if ($f->getEntityTypeId() !== 'comment' || $f->getEntityCategory() !== 'instance') {
if ($f->getEntityCategory() !== 'instance') {
$form['#attached']['library'][] = 'simple_sitemap/form';
}
......@@ -111,21 +110,31 @@ function simple_sitemap_entity_form_submit($form, FormStateInterface &$form_stat
'include_images' => (bool) $values['simple_sitemap_include_images'],
];
// Deleting bundle settings for old bundle.
// See SimplesitemapEntitiesForm::submitForm().
// todo: This will not be necessary if "multiple variants pro bundle" is implemented.
if (isset($form['simple_sitemap']['simple_sitemap_variant']['#default_value'])) {
$old_variant = $form['simple_sitemap']['simple_sitemap_variant']['#default_value'];
if ($old_variant !== $values['simple_sitemap_variant']) {
$generator->setVariants($old_variant)->removeBundleSettings($f->getEntityTypeId(), $f->getBundleName());
}
}
switch ($f->getEntityCategory()) {
case 'bundle':
$generator->setBundleSettings(
$f->getEntityTypeId(),
!empty($f->getBundleName()) ? $f->getBundleName() : $f->getFormEntityId(),
$generator->setVariants([$values['simple_sitemap_variant']])
->setBundleSettings($f->getEntityTypeId(),
!empty($f->getBundleName()) ? $f->getBundleName() : $f->getFormEntityId(),
$settings
);
break;
case 'instance':
$generator->setEntityInstanceSettings(
$f->getEntityTypeId(),
!empty($f->getInstanceId()) ? $f->getInstanceId() : $f->getFormEntityId(),
$settings
$generator->setVariants([$values['simple_sitemap_variant']])
->setEntityInstanceSettings($f->getEntityTypeId(),
!empty($f->getInstanceId()) ? $f->getInstanceId() : $f->getFormEntityId(),
$settings
);
break;
}
......@@ -192,7 +201,7 @@ function simple_sitemap_entity_delete(EntityInterface $entity) {
/** @var \Drupal\simple_sitemap\Simplesitemap $generator */
$generator = \Drupal::service('simple_sitemap.generator');
$generator->removeEntityInstanceSettings(
$generator->setVariants(TRUE)->removeEntityInstanceSettings(
$entity->getEntityTypeId(), $entity->id()
);
}
......@@ -206,7 +215,10 @@ function simple_sitemap_entity_delete(EntityInterface $entity) {
* @param string $bundle
*/
function simple_sitemap_entity_bundle_delete($entity_type_id, $bundle) {
simple_sitemap_delete_bundle_config($entity_type_id, $bundle);
/** @var \Drupal\simple_sitemap\Simplesitemap $generator */
$generator = \Drupal::service('simple_sitemap.generator');
$generator->setVariants(TRUE)->removeBundleSettings($entity_type_id, $bundle);
}
/**
......@@ -217,33 +229,10 @@ function simple_sitemap_entity_bundle_delete($entity_type_id, $bundle) {
* @param \Drupal\system\MenuInterface $menu
*/
function simple_sitemap_menu_delete(MenuInterface $menu) {
simple_sitemap_delete_bundle_config('menu_link_content', $menu->id());
}
/**
* Helper function used by simple_sitemap_entity_bundle_delete() and
* simple_sitemap_menu_delete() hooks. This is needed, as menus are technically
* not bundles.
*
* @param string $entity_type_id
* @param string $bundle
*/
function simple_sitemap_delete_bundle_config($entity_type_id, $bundle) {
/** @var \Drupal\simple_sitemap\Simplesitemap $generator */
$generator = \Drupal::service('simple_sitemap.generator');
if (!empty($deleted_bundle_settings = $generator->getBundleSettings($entity_type_id, $bundle))) {
\Drupal::service('config.factory')->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle")->delete();
if (!empty($deleted_bundle_settings['index'])) {
$message = 'You may want to <a href="@url">regenerate</a> your XML sitemaps now.';
if ($generator->getSetting('cron_generate')) {
$message .= ' Otherwise the sitemaps will be regenerated during a future cron run.';
}
\Drupal::messenger()->addMessage(t($message, ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']));
}
}
$generator->setVariants(TRUE)->removeBundleSettings('menu_link_content', $menu->id());
}
/**
......
......@@ -21,6 +21,7 @@ services:
public: false
arguments:
- '@config.factory'
- '@database'
- '@plugin.manager.simple_sitemap.sitemap_type'
- '@plugin.manager.simple_sitemap.url_generator'
- '@plugin.manager.simple_sitemap.sitemap_generator'
......
......@@ -59,6 +59,16 @@ class FormHelper {
*/
protected $instanceId;
/**
* @var string
*/
protected $variant;
/**
* @var array
*/
protected $bundleSettings;
protected static $allowedFormOperations = [
'default',
'edit',
......@@ -77,6 +87,7 @@ class FormHelper {
];
protected static $valuesToCheck = [
'simple_sitemap_variant',
'simple_sitemap_index_content',
'simple_sitemap_priority',
'simple_sitemap_changefreq',
......@@ -108,6 +119,7 @@ class FormHelper {
$this->formState = $form_state;
$this->cleanUpFormInfo();
$this->getEntityDataFromFormEntity();
$this->negotiateVariant();
return $this->supports();
}
......@@ -197,9 +209,12 @@ class FormHelper {
// Do not alter the form, if sitemap is disabled for the entity type of this
// entity instance.
elseif ($this->getEntityCategory() === 'instance'
&& !$this->generator->bundleIsIndexed($this->getEntityTypeId(), $this->getBundleName())) {
return FALSE;
elseif ($this->getEntityCategory() === 'instance') {
if (NULL === $this->variant || !$this->generator
->setVariants($this->variant)
->bundleIsIndexed($this->getEntityTypeId(), $this->getBundleName())) {
return FALSE;
}
}
return TRUE;
......@@ -220,6 +235,15 @@ class FormHelper {
}
}
protected function negotiateVariant() {
$all_bundle_settings = $this->generator->setVariants(TRUE)
->getBundleSettings($this->getEntityTypeId(), $this->getBundleName(), FALSE, TRUE);
$this->bundleSettings = NULL !== ($variant = key($all_bundle_settings))
? $all_bundle_settings[$variant]
: [];
$this->variant = $variant;
}
/**
* @param array $form_fragment
* @param bool $multiple
......@@ -228,15 +252,9 @@ class FormHelper {
public function displayEntitySettings(&$form_fragment, $multiple = FALSE) {
$prefix = $multiple ? $this->getEntityTypeId() . '_' : '';
if ($this->getEntityCategory() === 'instance') {
$bundle_settings = $this->generator->getBundleSettings($this->getEntityTypeId(), $this->getBundleName());
$settings = NULL !== $this->getInstanceId()
? $this->generator->getEntityInstanceSettings($this->getEntityTypeId(), $this->getInstanceId())
: $bundle_settings;
}
else {
$settings = $this->generator->getBundleSettings($this->getEntityTypeId(), $this->getBundleName());
}
$settings = $this->getEntityCategory() === 'instance' && NULL !== $this->variant && NULL !== $this->getInstanceId()
? $this->generator->setVariants($this->variant)->getEntityInstanceSettings($this->getEntityTypeId(), $this->getInstanceId())
: $this->bundleSettings;
Simplesitemap::supplementDefaultSettings('entity', $settings);
$bundle_name = !empty($this->getBundleName()) ? $this->getBundleName() : $this->t('undefined');
......@@ -256,11 +274,32 @@ class FormHelper {
],
];
if ($this->getEntityCategory() === 'instance' && isset($bundle_settings['index'])) {
$form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][(int) $bundle_settings['index']] .= ' <em>(' . $this->t('default') . ')</em>';
if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['index'])) {
$form_fragment[$prefix . 'simple_sitemap_index_content']['#options'][(int) $this->bundleSettings['index']] .= ' <em>(' . $this->t('default') . ')</em>';
}
}
// Variant
$variants = $this->generator->getSitemapManager()->getSitemapVariants(NULL, FALSE);
$variants = array_map(function($variant) { return $variant['label']; }, $variants);
$form_fragment[$prefix . 'simple_sitemap_variant'] = [
'#type' => 'select',
'#title' => $this->t('Sitemap variant'),
'#description' => $this->t('The sitemap variant entities of this type are to be indexed in.'),
'#options' => $variants,
'#default_value' => $this->variant,
'#states' => [
'visible' => !$multiple
? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
: [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
'required' => !$multiple // todo Should implement server side validation on top of this.
? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
: [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
],
'#disabled' => $this->getEntityCategory() === 'instance'
];
// Priority
$form_fragment[$prefix . 'simple_sitemap_priority'] = [
'#type' => 'select',
......@@ -270,10 +309,15 @@ class FormHelper {
: $this->t('The priority entities of this type will have in the eyes of search engine bots.'),
'#default_value' => $settings['priority'],
'#options' => $this->getPrioritySelectValues(),
'#states' => [
'visible' => !$multiple
? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
: [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
],
];
if ($this->getEntityCategory() === 'instance' && isset($bundle_settings['priority'])) {
$form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($bundle_settings['priority'])] .= ' (' . $this->t('default') . ')';
if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['priority'])) {
$form_fragment[$prefix . 'simple_sitemap_priority']['#options'][$this->formatPriority($this->bundleSettings['priority'])] .= ' (' . $this->t('default') . ')';
}
// Changefreq
......@@ -285,10 +329,15 @@ class FormHelper {
: $this->t('The frequency with which entities of this type change. Search engine bots may take this as an indication of how often to index them.'),
'#default_value' => $settings['changefreq'],
'#options' => $this->getChangefreqSelectValues(),
'#states' => [
'visible' => !$multiple
? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
: [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
],
];
if ($this->getEntityCategory() === 'instance' && isset($bundle_settings['changefreq'])) {
$form_fragment[$prefix . 'simple_sitemap_changefreq']['#options'][$bundle_settings['changefreq']] .= ' (' . $this->t('default') . ')';
if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['changefreq'])) {
$form_fragment[$prefix . 'simple_sitemap_changefreq']['#options'][$this->bundleSettings['changefreq']] .= ' (' . $this->t('default') . ')';
}
// Images
......@@ -300,10 +349,15 @@ class FormHelper {
: $this->t('Determines if images referenced by entities of this type should be included in the sitemap.'),
'#default_value' => (int) $settings['include_images'],
'#options' => [0 => $this->t('No'), 1 => $this->t('Yes')],
'#states' => [
'visible' => !$multiple
? [':input[name="' . $prefix . 'simple_sitemap_index_content"]' => ['value' => 1]]
: [':input[name="' . $prefix . 'enabled"]' => ['checked' => TRUE]],
],
];
if ($this->getEntityCategory() === 'instance' && isset($bundle_settings['include_images'])) {
$form_fragment[$prefix . 'simple_sitemap_include_images']['#options'][(int) $bundle_settings['include_images']] .= ' (' . $this->t('default') . ')';
if ($this->getEntityCategory() === 'instance' && isset($this->bundleSettings['include_images'])) {
$form_fragment[$prefix . 'simple_sitemap_include_images']['#options'][(int) $this->bundleSettings['include_images']] .= ' (' . $this->t('default') . ')';
}
return $this;
......@@ -327,9 +381,7 @@ class FormHelper {
$this->setEntityCategory('instance');
}
else {
/**
* @var \Drupal\Core\Entity\EntityType $sitemap_entity_type
*/
/** @var \Drupal\Core\Entity\EntityType $sitemap_entity_type */
foreach ($sitemap_entity_types as $sitemap_entity_type) {
if ($sitemap_entity_type->getBundleEntityType() === $entity_type_id) {
$this->setEntityCategory('bundle');
......@@ -390,6 +442,8 @@ class FormHelper {
$this->entityTypeId = NULL;
$this->bundleName = NULL;
$this->instanceId = NULL;
$this->variant = NULL;
$this->bundleSettings = NULL;
}
/**
......@@ -415,7 +469,8 @@ class FormHelper {
*/
public function valuesChanged($form, array $values) {
foreach (self::$valuesToCheck as $field_name) {
if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
if (!isset($form['simple_sitemap'][$field_name]['#default_value'])
|| (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value'])) {
return TRUE;
}
}
......
......@@ -118,11 +118,24 @@ class SimplesitemapEntitiesForm extends SimplesitemapFormBase {
if ($value) {
$this->generator->enableEntityType($entity_type_id);
if ($this->entityHelper->entityTypeIsAtomic($entity_type_id)) {
$this->generator->setBundleSettings($entity_type_id, $entity_type_id, [
'index' => TRUE,
'priority' => $values[$entity_type_id . '_simple_sitemap_priority'],
'changefreq' => $values[$entity_type_id . '_simple_sitemap_changefreq'],
'include_images' => (bool) $values[$entity_type_id . '_simple_sitemap_include_images'],
// Deleting bundle settings for old bundle.
// See simple_sitemap.module::simple_sitemap_entity_form_submit().
// todo: This will not be necessary if "multiple variants pro bundle" is implemented.
if (isset($form['simple_sitemap_entities']['entities'][$entity_type_id][$entity_type_id . '_settings'][$entity_type_id . '_simple_sitemap_variant']['#default_value'])) {
$old_variant = $form['simple_sitemap_entities']['entities'][$entity_type_id][$entity_type_id . '_settings'][$entity_type_id . '_simple_sitemap_variant']['#default_value'];
if ($old_variant !== $values[$entity_type_id . '_simple_sitemap_variant']) {
$this->generator->setVariants($old_variant)->removeBundleSettings($entity_type_id);
}
}
$this->generator
->setVariants($values[$entity_type_id . '_simple_sitemap_variant'])
->setBundleSettings($entity_type_id, $entity_type_id, [
'index' => TRUE,
'priority' => $values[$entity_type_id . '_simple_sitemap_priority'],
'changefreq' => $values[$entity_type_id . '_simple_sitemap_changefreq'],
'include_images' => (bool) $values[$entity_type_id . '_simple_sitemap_include_images'],
]);
}
}
......
......@@ -152,7 +152,7 @@ class SimplesitemapSettingsForm extends SimplesitemapFormBase {
foreach ($this->generator->getSitemapManager()->getSitemapVariants(NULL, FALSE) as $name => $info) {
$variants[$name] = $this->t($info['label']);
}
$default_variant = $this->generator->getSetting('default_variant', SimplesitemapManager::DEFAULT_SITEMAP_VARIANT);
$default_variant = $this->generator->getSetting('default_variant');
$form['simple_sitemap_settings']['advanced']['default_variant'] = [
'#type' => 'select',
......
......@@ -49,7 +49,8 @@ class SimplesitemapVariantsForm extends SimplesitemapFormBase {
/**
* {@inheritdoc}
*
* @todo show multiple errors at once
* @todo Show multiple errors at once.
* @todo Allow numeric variant names, but bear in mind that they are stored as integer array keys due to how php arrays work.
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$line = 0;
......@@ -70,6 +71,10 @@ class SimplesitemapVariantsForm extends SimplesitemapFormBase {
$form_state->setErrorByName('', $this->t("<strong>Line @line</strong>: The variant name <em>@name</em> can only include alphanumeric characters, dashes and underscores.", $placeholders));
}
if (is_numeric($variant_name)) {
$form_state->setErrorByName('', $this->t("<strong>Line @line</strong>: The variant name cannot be numeric.", $placeholders));
}
if (!isset($sitemap_types[$variant_definition['type']])) {
$form_state->setErrorByName('', $this->t("<strong>Line @line</strong>: The variant <em>@name</em> is of a sitemap type <em>@type</em> that does not exist.", $placeholders));
}
......@@ -80,26 +85,19 @@ class SimplesitemapVariantsForm extends SimplesitemapFormBase {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Removing all variants will clear the default variant setting, may need to
// restore this setting later.
$default_variant = $this->generator->getSetting('default_variant');
$this->generator->getSitemapManager()->removeSitemapVariants();
$manager = $this->generator->getSitemapManager();
$new_variants = $this->stringToVariants($form_state->getValue('variants'));
$remove_variants = array_values(array_diff(
array_keys($manager->getSitemapVariants(NULL, FALSE)),
array_keys($new_variants)
));
$manager->removeSitemapVariants($remove_variants);
$weight = 0;
foreach ($new_variants as $variant_name => $variant_definition) {
$this->generator->getSitemapManager()->addSitemapVariant($variant_name, $variant_definition + ['weight' => $weight]);
$manager->addSitemapVariant($variant_name, $variant_definition + ['weight' => $weight]);
$weight++;
}
// Restoring the default variant setting in case the default variant has
// not been deleted.
if (isset($new_variants[$default_variant])) {
$this->generator->saveSetting('default_variant', $default_variant);
}
parent::submitForm($form, $form_state);
// Regenerate sitemaps according to user setting.
......
......@@ -189,30 +189,31 @@ abstract class SitemapGeneratorBase extends SimplesitemapPluginBase implements S
}
public static function removeSitemapVariants($variants = NULL, $mode = 'all') {
$variants = is_array($variants) || NULL === $variants ? $variants : [$variants];
$delete_query = \Drupal::database()->delete('simple_sitemap');
if (NULL === $variants || !empty((array) $variants)) {
$delete_query = \Drupal::database()->delete('simple_sitemap');
switch($mode) {
case 'published':
$delete_query->condition('status', 1);
break;
switch($mode) {
case 'published':
$delete_query->condition('status', 1);
break;
case 'unpublished':
$delete_query->condition('status', 0);
break;
case 'unpublished':
$delete_query->condition('status', 0);
break;
case 'all':
break;
case 'all':
break;
default:
//todo: throw error
}
default:
//todo: throw error
}
if (NULL !== $variants) {
$delete_query->condition('type', $variants, 'IN');