Commit 9873b7e2 authored by gbyte.co's avatar gbyte.co

Change convention array() to []

parent 52412360
......@@ -8,11 +8,11 @@
* Implements hook_drush_command().
*/
function simple_sitemap_drush_command() {
$items['simple_sitemap-generate'] = array(
$items['simple_sitemap-generate'] = [
'description' => 'Regenerate XML sitemaps for all languages according to the module settings.',
'callback' => 'drush_simple_sitemap_generate',
'drupal dependencies' => array('simple_sitemap'),
);
'drupal dependencies' => ['simple_sitemap'],
];
return $items;
}
......
......@@ -8,15 +8,15 @@
* Implements hook_requirements().
*/
function simple_sitemap_requirements($phase) {
$requirements = array();
$requirements = [];
if (!extension_loaded('xmlwriter')) {
$requirements['simple_sitemap_php_extensions'] = array(
$requirements['simple_sitemap_php_extensions'] = [
'title' => t('Simple XML sitemap PHP extensions'),
'value' => t('Missing PHP xmlwriter extension'),
'description' => t("In order to be able to generate sitemaps, the Simple XML sitemap module requires the <em>xmlwriter</em> PHP extension to be enabled."),
'severity' => REQUIREMENT_ERROR,
);
];
}
switch($phase) {
......@@ -25,20 +25,20 @@ function simple_sitemap_requirements($phase) {
$generated_ago = $sitemap->getGeneratedAgo();
if (!$generated_ago) {
$value = t('Not available');
$description = t("The sitemap has not been generated yet. Run cron, or <a href='@generate'>generate</a> the sitemap manually.", array('@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'));
$description = t("The sitemap has not been generated yet. Run cron, or <a href='@generate'>generate</a> the sitemap manually.", ['@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']);
$severity = REQUIREMENT_WARNING;
}
else {
$value = t('XML sitemap is available');
$description = t("The <a href='@sitemap'>XML sitemap</a> was generated @ago ago. <a href='@generate'>Regenerate</a>.", array('@ago' => $generated_ago, '@sitemap' => $GLOBALS['base_url'] . '/sitemap.xml', '@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'));
$description = t("The <a href='@sitemap'>XML sitemap</a> was generated @ago ago. <a href='@generate'>Regenerate</a>.", ['@ago' => $generated_ago, '@sitemap' => $GLOBALS['base_url'] . '/sitemap.xml', '@generate' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']);
$severity = REQUIREMENT_INFO;
}
$requirements['simple_sitemap_generated'] = array(
$requirements['simple_sitemap_generated'] = [
'title' => 'Simple XML sitemap',
'value' => $value,
'description' => $description,
'severity' => $severity,
);
];
break;
}
return $requirements;
......@@ -48,30 +48,30 @@ function simple_sitemap_requirements($phase) {
* Implements hook_schema().
*/
function simple_sitemap_schema() {
$schema['simple_sitemap'] = array(
$schema['simple_sitemap'] = [
'description' => 'Holds XML sitemaps as strings for quick retrieval.',
'fields' => array(
'id' => array(
'fields' => [
'id' => [
'description' => 'Sitemap chunk unique identifier.',
'type' => 'int',
'size' => 'small',
'not null' => TRUE,
),
'sitemap_string' => array(
],
'sitemap_string' => [
'description' => 'XML sitemap chunk string.',
'type' => 'text',
'size' => 'big',
'not null' => TRUE,
),
'sitemap_created' => array(
],
'sitemap_created' => [
'description' => 'Timestamp of sitemap chunk generation.',
'type' => 'int',
'default' => 0,
'not null' => TRUE,
),
),
'primary key' => array('id'),
);
],
],
'primary key' => ['id'],
];
return $schema;
}
......@@ -82,7 +82,7 @@ function simple_sitemap_install() {
$sitemap = \Drupal::service('simple_sitemap.generator');
$sitemap->generateSitemap('nobatch');
$base_url = $GLOBALS['base_url'];
drupal_set_message(t("You can now include content into the <a href='@sitemap_url' target='_blank'>XML sitemap</a> by visiting the corresponding entity type edit pages (e.g. <a href='@content_type_url' target='_blank'>node type edit pages</a>) These settings can then be overridden for single entities.<br/> Support for additional entity types and custom links can be added on <a href='@config_url' target='_blank'>the module's configuration pages</a>.", array('@sitemap_url' => "$base_url/sitemap.xml", '@content_type_url' => "$base_url/admin/structure/types", '@config_url' => "$base_url/admin/config/search/simplesitemap")));
drupal_set_message(t("You can now include content into the <a href='@sitemap_url' target='_blank'>XML sitemap</a> by visiting the corresponding entity type edit pages (e.g. <a href='@content_type_url' target='_blank'>node type edit pages</a>) These settings can then be overridden for single entities.<br/> Support for additional entity types and custom links can be added on <a href='@config_url' target='_blank'>the module's configuration pages</a>.", ['@sitemap_url' => "$base_url/sitemap.xml", '@content_type_url' => "$base_url/admin/structure/types", '@config_url' => "$base_url/admin/config/search/simplesitemap"]));
}
/**
......@@ -90,7 +90,7 @@ function simple_sitemap_install() {
*/
function simple_sitemap_update_8201() {
$entity_types = \Drupal::config('simple_sitemap.settings')->get('entity_types');
$entity_types = is_array($entity_types) ? $entity_types : array();
$entity_types = is_array($entity_types) ? $entity_types : [];
$naming_changes = [
'node_type' => 'node',
'taxonomy_vocabulary' => 'taxonomy_term',
......
......@@ -73,12 +73,12 @@ function simple_sitemap_entity_form_submit($form, &$form_state) {
switch ($f->entityCategory) {
case 'bundle':
$f->bundleName = !empty($f->bundleName) ? $f->bundleName : Form::getNewEntityId($form_state);
$f->bundleName = !empty($f->bundleName) ? $f->bundleName : $f->getFormEntityId();
$sitemap->setBundleSettings($f->entityTypeId, $f->bundleName, ['index' => $values['simple_sitemap_index_content'], 'priority' => $values['simple_sitemap_priority']]);
break;
case 'instance':
$f->instanceId = !empty($f->instanceId) ? $f->instanceId : Form::getNewEntityId($form_state);
$f->instanceId = !empty($f->instanceId) ? $f->instanceId : $f->getFormEntityId();
$sitemap->setEntityInstanceSettings($f->entityTypeId, $f->instanceId, ['index' => $values['simple_sitemap_index_content'], 'priority' => $values['simple_sitemap_priority']]);
break;
}
......@@ -113,7 +113,7 @@ function simple_sitemap_entity_bundle_delete($entity_type_id, $bundle) {
if (isset($entity_types[$entity_type_id][$bundle])) {
unset($entity_types[$entity_type_id][$bundle]);
$sitemap->saveConfig('entity_types', $entity_types);
$message = t("You may want to <a href='@url'>regenerate</a> your XML sitemap now.", array('@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap'));
$message = t("You may want to <a href='@url'>regenerate</a> your XML sitemap now.", ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']);
if ($sitemap->getSetting('cron_generate')) {
$message .= '</br>' . t('Otherwise the sitemap will be regenerated on the next cron run.');
}
......
......@@ -26,14 +26,14 @@ class Batch {
const ANONYMOUS_USER_ID = 0;
function __construct() {
$this->batch = array(
$this->batch = [
'title' => t('Generating XML sitemap'),
'init_message' => t(self::BATCH_INIT_MESSAGE),
'error_message' => t(self::BATCH_ERROR_MESSAGE),
'progress_message' => t(self::BATCH_PROGRESS_MESSAGE),
'operations' => array(),
'finished' => [__CLASS__ , 'finishGeneration'], // __CLASS__ . '::finishGeneration' not working possibly due to a drush error.
);
'operations' => [],
'finished' => [__CLASS__, 'finishGeneration'], // __CLASS__ . '::finishGeneration' not working possibly due to a drush error.
];
}
public function setBatchInfo($batch_info) {
......@@ -67,12 +67,12 @@ class Batch {
break;
case 'nobatch':
$context = array();
$context = [];
foreach($this->batch['operations'] as $i => $operation) {
$operation[1][] = &$context;
call_user_func_array($operation[0], $operation[1]);
}
self::finishGeneration(TRUE, $context['results'], array());
self::finishGeneration(TRUE, $context['results'], []);
break;
}
}
......@@ -87,17 +87,17 @@ class Batch {
switch ($type) {
case 'entity_types':
foreach ($operations as $operation) {
$this->batch['operations'][] = array(
$this->batch['operations'][] = [
__CLASS__ . '::generateBundleUrls',
array($operation['entity_info'], $this->batchInfo)
);
[$operation['entity_info'], $this->batchInfo]
];
};
break;
case 'custom_paths':
$this->batch['operations'][] = array(
$this->batch['operations'][] = [
__CLASS__ . '::generateCustomUrls',
array($operations, $this->batchInfo)
);
[$operations, $this->batchInfo]
];
break;
}
}
......@@ -113,9 +113,9 @@ class Batch {
if (!empty($results['generate']) || $remove_sitemap) {
SitemapGenerator::generateSitemap($results['generate'], $remove_sitemap);
}
Cache::invalidateTags(array('simple_sitemap'));
Cache::invalidateTags(['simple_sitemap']);
drupal_set_message(t("The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.",
array('@url' => $GLOBALS['base_url'] . '/sitemap.xml')));
['@url' => $GLOBALS['base_url'] . '/sitemap.xml']));
}
else {
//todo: register error
......@@ -194,7 +194,7 @@ class Batch {
// Loading url object for other entities.
else {
$route_name = 'entity.' . $entity_info['entity_type_name'] . '.canonical';
$route_parameters = array($entity_info['entity_type_name'] => $entity_id);
$route_parameters = [$entity_info['entity_type_name'] => $entity_id];
$url_object = Url::fromRoute($route_name, $route_parameters);
}
$url_object->setOption('absolute', TRUE);
......@@ -208,7 +208,7 @@ class Batch {
if ($batch_info['remove_duplicates'] && self::pathProcessed($path, $context))
continue;
$urls = array();
$urls = [];
foreach ($languages as $language) {
if ($language->getId() === $default_language_id) {
$urls[$default_language_id] = $url_object->toString();
......@@ -221,13 +221,13 @@ class Batch {
}
}
$context['results']['generate'][] = array(
$context['results']['generate'][] = [
'path' => $path,
'urls' => $urls,
'options' => $url_object->getOptions(),
'lastmod' => method_exists($entity, 'getChangedTime') ? date_iso8601($entity->getChangedTime()) : NULL,
'priority' => isset($priority) ? $priority : (isset($entity_info['bundle_settings']['priority']) ? $entity_info['bundle_settings']['priority'] : NULL),
);
];
$priority = NULL;
}
}
......@@ -264,10 +264,10 @@ class Batch {
$user_input = $custom_path['path'][0] === '/' ? $custom_path['path'] : '/' . $custom_path['path'];
if (!\Drupal::service('path.validator')->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.
self::registerError(self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS, array('@faulty_path' => $custom_path['path']), 'warning');
self::registerError(self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS, ['@faulty_path' => $custom_path['path']], 'warning');
continue;
}
$options = array('absolute' => TRUE, 'language' => $languages[$default_language_id]);
$options = ['absolute' => TRUE, 'language' => $languages[$default_language_id]];
$url_object = Url::fromUserInput($user_input, $options);
if (!$url_object->access($batch_info['anonymous_user_account']))
......@@ -277,7 +277,7 @@ class Batch {
if ($batch_info['remove_duplicates'] && self::pathProcessed($path, $context))
continue;
$urls = array();
$urls = [];
foreach($languages as $language) {
if ($language->getId() === $default_language_id) {
$urls[$default_language_id] = $url_object->toString();
......@@ -288,12 +288,12 @@ class Batch {
}
}
$context['results']['generate'][] = array(
$context['results']['generate'][] = [
'path' => $path,
'urls' => $urls,
'options' => $url_object->getOptions(),
'priority' => isset($custom_path['priority']) ? $custom_path['priority'] : NULL,
);
];
}
if (self::isBatch($batch_info)) {
self::setProgressInfo($context);
......@@ -302,7 +302,7 @@ class Batch {
}
private static function pathProcessed($path, &$context) {
$path_pool = isset($context['results']['processed_paths']) ? $context['results']['processed_paths'] : array();
$path_pool = isset($context['results']['processed_paths']) ? $context['results']['processed_paths'] : [];
if (in_array($path, $path_pool)) {
return TRUE;
}
......@@ -311,12 +311,12 @@ class Batch {
}
private static function InitializeBatch($batch_info, $max, &$context) {
$context['results']['generate'] = !empty($context['results']['generate']) ? $context['results']['generate'] : array();
$context['results']['generate'] = !empty($context['results']['generate']) ? $context['results']['generate'] : [];
if (self::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'] : array();
$context['results']['processed_paths'] = !empty($context['results']['processed_paths']) ? $context['results']['processed_paths'] : [];
}
}
......@@ -334,11 +334,11 @@ class Batch {
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", array(
$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']),
));
]);
}
}
}
......@@ -368,7 +368,7 @@ class Batch {
* @param string $type (optional)
* Message type (status/warning/error).
*/
private static function registerError($message, $substitutions = array(), $type = 'error') {
private static function registerError($message, $substitutions = [], $type = 'error') {
$message = strtr(t($message), $substitutions);
\Drupal::logger('simple_sitemap')->notice($message);
drupal_set_message($message, $type);
......
......@@ -48,7 +48,7 @@ class SimplesitemapController extends ControllerBase {
$output = !$output ? '' : $output;
// Display sitemap with correct xml header.
$response = new CacheableResponse($output, Response::HTTP_OK, array('content-type' => 'application/xml'));
$response = new CacheableResponse($output, Response::HTTP_OK, ['content-type' => 'application/xml']);
$meta_data = $response->getCacheableMetadata();
$meta_data->addCacheTags(['simple_sitemap']);
return $response;
......
......@@ -22,7 +22,7 @@ class CustomLinkGenerator {
*
*/
public function getCustomPaths($custom_paths) {
$paths = array();
$paths = [];
foreach($custom_paths as $i => $custom_path) {
$paths[$i]['path'] = $custom_path['path'];
$paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
......
......@@ -24,22 +24,24 @@ class Form {
private $formState;
private $sitemap;
private static $allowed_operations = ['default', 'edit', 'add'];
private static $allowedFormOperations = ['default', 'edit', 'add'];
private static $valuesToCheck = ['simple_sitemap_index_content', 'simple_sitemap_priority', 'simple_sitemap_regenerate_now'];
/**
* Form constructor.
*/
function __construct($form_state = NULL) {
$this->formState = $form_state;
$this->entityCategory = NULL;
$this->alteringForm = TRUE;
$this->sitemap = \Drupal::service('simple_sitemap.generator');
// Do not alter the form if user lacks certain permissions.
if (!\Drupal::currentUser()->hasPermission('administer sitemap settings')) {
$this->alteringForm = FALSE;
return;
}
$this->formState = $form_state;
$this->entityCategory = NULL;
$this->alteringForm = TRUE;
$this->sitemap = \Drupal::service('simple_sitemap.generator');
$this->getEntityData();
}
......@@ -78,12 +80,12 @@ class Form {
}
public function displaySitemapRegenerationSetting(&$form_fragment) {
$form_fragment['simple_sitemap_regenerate_now'] = array(
$form_fragment['simple_sitemap_regenerate_now'] = [
'#type' => 'checkbox',
'#title' => t('Regenerate sitemap after hitting <em>Save</em>'),
'#description' => t('This setting will regenerate the whole sitemap including the above changes.'),
'#default_value' => FALSE,
);
];
if ($this->sitemap->getSetting('cron_generate')) {
$form_fragment['simple_sitemap_regenerate_now']['#description'] .= '</br>' . t('Otherwise the sitemap will be regenerated on the next cron run.');
}
......@@ -153,7 +155,7 @@ class Form {
$this->entityCategory = 'instance';
}
else {
foreach ($sitemap_entity_types as $sitemap_entity) {
foreach($sitemap_entity_types as $sitemap_entity) {
if ($sitemap_entity->getBundleEntityType() == $entity_type_id) {
$this->entityCategory = 'bundle';
break;
......@@ -195,7 +197,7 @@ class Form {
$form_object = $this->formState->getFormObject();
if (!is_null($form_object)
&& method_exists($form_object, 'getEntity')
&& in_array($form_object->getOperation(), self::$allowed_operations)) {
&& in_array($form_object->getOperation(), self::$allowedFormOperations)) {
return $form_object->getEntity();
}
return FALSE;
......@@ -207,8 +209,8 @@ class Form {
*
* @return int entity ID.
*/
public static function getNewEntityId($form_state) {
return $form_state->getFormObject()->getEntity()->id();
public function getFormEntityId() {
return $this->formState->getFormObject()->getEntity()->id();
}
/**
......@@ -219,7 +221,7 @@ class Form {
* TRUE if simple_sitemap form values have been altered by the user.
*/
public static function valuesChanged($form, $values) {
foreach (array('simple_sitemap_index_content', 'simple_sitemap_priority', 'simple_sitemap_regenerate_now') as $field_name) {
foreach (self::$valuesToCheck as $field_name) {
if (isset($values[$field_name]) && $values[$field_name] != $form['simple_sitemap'][$field_name]['#default_value']) {
return TRUE;
}
......@@ -233,7 +235,7 @@ class Form {
* @return array $options
*/
public static function getPrioritySelectValues() {
$options = array();
$options = [];
foreach(range(0, self::PRIORITY_HIGHEST) as $value) {
$value = self::formatPriority($value / self::PRIORITY_DIVIDER);
$options[$value] = $value;
......
......@@ -44,18 +44,18 @@ class SimplesitemapCustomLinksForm extends ConfigFormBase {
$setting_string .= "\r\n";
}
$form['simple_sitemap_custom'] = array(
$form['simple_sitemap_custom'] = [
'#title' => t('Custom links'),
'#type' => 'fieldset',
'#markup' => '<p>' . t('Add custom internal drupal paths to the XML sitemap.') . '</p>',
);
];
$form['simple_sitemap_custom']['custom_links'] = array(
$form['simple_sitemap_custom']['custom_links'] = [
'#type' => 'textarea',
'#title' => t('Relative Drupal paths'),
'#default_value' => $setting_string,
'#description' => 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>."),
);
];
$f = new Form();
$f->displaySitemapRegenerationSetting($form['simple_sitemap_custom']);
......@@ -73,14 +73,14 @@ class SimplesitemapCustomLinksForm extends ConfigFormBase {
foreach($custom_link_config as $link_config) {
if (!\Drupal::service('path.validator')->isValid($link_config['path'])) {
$form_state->setErrorByName('', t("The path <em>@path</em> does not exist.", array('@path' => $link_config['path'])));
$form_state->setErrorByName('', t("The path <em>@path</em> does not exist.", ['@path' => $link_config['path']]));
}
if ($link_config['path'][0] != '/') {
$form_state->setErrorByName('', t("The path <em>@path</em> needs to start with a '/'.", array('@path' => $link_config['path'])));
$form_state->setErrorByName('', t("The path <em>@path</em> needs to start with a '/'.", ['@path' => $link_config['path']]));
}
if (isset($link_config['priority'])) {
if (!Form::isValidPriority($link_config['priority'])) {
$form_state->setErrorByName('', t("The priority setting <em>@priority</em> for path <em>@path</em> is incorrect. Set the priority from 0.0 to 1.0.", array('@priority' => $link_config['priority'], '@path' => $link_config['path'])));
$form_state->setErrorByName('', t("The priority setting <em>@priority</em> for path <em>@path</em> is incorrect. Set the priority from 0.0 to 1.0.", ['@priority' => $link_config['priority'], '@path' => $link_config['path']]));
}
}
}
......@@ -109,7 +109,7 @@ class SimplesitemapCustomLinksForm extends ConfigFormBase {
$custom_links_string_lines = explode("\n", str_replace("\r\n", "\n", $custom_links_string));
// Remove whitespace from array values.
$custom_links_string_lines = array_filter(array_map('trim', $custom_links_string_lines));
$custom_link_config = array();
$custom_link_config = [];
foreach($custom_links_string_lines as $i => &$line) {
$link_settings = explode(' ', $line, 2);
$custom_link_config[$i]['path'] = $link_settings[0];
......
......@@ -38,11 +38,11 @@ class SimplesitemapEntitiesForm extends ConfigFormBase {
$sitemap = \Drupal::service('simple_sitemap.generator');
$form['simple_sitemap_entities']['entities'] = array(
$form['simple_sitemap_entities']['entities'] = [
'#title' => t('Sitemap entities'),
'#type' => 'fieldset',
'#markup' => '<p>' . t("Simple XML sitemap settings will be added only to entity forms of entity types enabled here. For all entity types featuring bundles (e.g. <em>node</em>) sitemap settings have to be set on their bundle pages (e.g. <em>page</em>).") . '</p>',
);
];
$form['#attached']['library'][] = 'simple_sitemap/sitemapEntities';
$form['#attached']['drupalSettings']['simple_sitemap'] = ['all_entities' => [], 'atomic_entities' => []];
......@@ -63,7 +63,7 @@ class SimplesitemapEntitiesForm extends ConfigFormBase {
];
$form['simple_sitemap_entities']['entities'][$entity_type_id][$entity_type_id . '_enabled'] = [
'#type' => 'checkbox',
'#title' => t('Enable @entity_type_label <em>(@entity_type_id)</em> support', array('@entity_type_label' => strtolower($entity_type_label), '@entity_type_id' => $entity_type_id)),
'#title' => t('Enable @entity_type_label <em>(@entity_type_id)</em> support', ['@entity_type_label' => strtolower($entity_type_label), '@entity_type_id' => $entity_type_id]),
'#description' => t('Sitemap settings for this entity type can be set on its bundle pages and overridden on its entity pages.'),
'#default_value' => $sitemap->entityTypeIsEnabled($entity_type_id),
];
......
......@@ -36,62 +36,62 @@ class SimplesitemapSettingsForm extends ConfigFormBase {
$sitemap = \Drupal::service('simple_sitemap.generator');
$form['simple_sitemap_settings']['#prefix'] = "<div class='description'>" .t("If you would like to say thanks and support the development of this module, a <a target='_blank' href='@url'>donation</a> is always appreciated.", array('@url' => 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5AFYRSBLGSC3W')) . "</div>";
$form['simple_sitemap_settings']['#prefix'] = "<div class='description'>" .t("If you would like to say thanks and support the development of this module, a <a target='_blank' href='@url'>donation</a> is always appreciated.", ['@url' => 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5AFYRSBLGSC3W']) . "</div>";
$form['simple_sitemap_settings']['regenerate'] = array(
$form['simple_sitemap_settings']['regenerate'] = [
'#title' => t('Regenerate sitemap'),
'#type' => 'fieldset',
'#markup' => '<p>' . t('This will regenerate the XML sitemap for all languages.') . '</p>',
);
];
$form['simple_sitemap_settings']['regenerate']['regenerate_submit'] = array(
$form['simple_sitemap_settings']['regenerate']['regenerate_submit'] = [
'#type' => 'submit',
'#value' => t('Regenerate sitemap'),
'#submit' => array('::generateSitemap'),
'#validate' => array(), // Skip form-level validator.
);
'#submit' => ['::generateSitemap'],
'#validate' => [], // Skip form-level validator.
];
$form['simple_sitemap_settings']['settings'] = array(
$form['simple_sitemap_settings']['settings'] = [
'#title' => t('Settings'),
'#type' => 'fieldset',
);
];
$form['simple_sitemap_settings']['settings']['cron_generate'] = array(
$form['simple_sitemap_settings']['settings']['cron_generate'] = [
'#type' => 'checkbox',
'#title' => t('Regenerate the sitemap on every cron run'),
'#description' => t('Uncheck this if you intend to only regenerate the sitemap manually or via drush.'),
'#default_value' => $sitemap->getSetting('cron_generate'),
);
];
$form['simple_sitemap_settings']['advanced'] = array(
$form['simple_sitemap_settings']['advanced'] = [
'#title' => t('Advanced settings'),
'#type' => 'details',
);
];
$form['simple_sitemap_settings']['advanced']['remove_duplicates'] = array(
$form['simple_sitemap_settings']['advanced']['remove_duplicates'] = [
'#type' => 'checkbox',
'#title' => t('Exclude duplicate links'),
'#description' => t('Uncheck this to significantly speed up the sitemap generation process on a huge site (more than 20 000 indexed entities).'),
'#default_value' => $sitemap->getSetting('remove_duplicates'),
);
];
$form['simple_sitemap_settings']['advanced']['max_links'] = array(
$form['simple_sitemap_settings']['advanced']['max_links'] = [
'#title' => t('Maximum links in a sitemap'),
'#description' => t("The maximum number of links one sitemap can hold. If more links are generated than set here, a sitemap index will be created and the links split into several sub-sitemaps.<br/>50 000 links is the maximum Google will parse per sitemap, however it is advisable to set this to a lower number. If left blank, all links will be shown on a single sitemap."),
'#type' => 'textfield',
'#maxlength' => 5,
'#size' => 5,
'#default_value' => $sitemap->getSetting('max_links'),
);
];
$form['simple_sitemap_settings']['advanced']['batch_process_limit'] = array(
$form['simple_sitemap_settings']['advanced']['batch_process_limit'] = [
'#title' => t('Refresh batch every n links'),
'#description' => t("During sitemap generation, the batch process will issue a page refresh after n links processed to prevent PHP timeouts and memory exhaustion. Increasing this number will reduce the number of times Drupal has to bootstrap (thus speeding up the generation process), but will require more memory and less strict PHP timeout settings."),
'#type' => 'textfield',
'#maxlength' => 5,
'#size' => 5,
'#default_value' => $sitemap->getSetting('batch_process_limit'),
);
];
return parent::buildForm($form, $form_state);
}
......
......@@ -46,7 +46,7 @@ class Simplesitemap {
return $this->config->get($key);
}
private function fetchSitemap() {
private function fetchSitemapChunks() {
return \Drupal::service('database')
->query("SELECT * FROM {simple_sitemap}")
->fetchAllAssoc('id');
......@@ -265,31 +265,30 @@ class Simplesitemap {
* Returns the whole sitemap, a requested sitemap chunk,
* or the sitemap index file.
*
* @param int $sitemap_id
* @param int $chunk_id
*
* @return string $sitemap
* If no sitemap id provided, either a sitemap index is returned, or the
* whole sitemap, if the amount of links does not exceed the max links setting.
* If a sitemap id is provided, a sitemap chunk is returned.
*/
public function getSitemap($sitemap_id = NULL) {
$sitemap = $this->fetchSitemap();
if (is_null($sitemap_id) || !isset($sitemap[$sitemap_id])) {
public function getSitemap($chunk_id = NULL) {
$chunks = $this->fetchSitemapChunks();
if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
// Return sitemap index, if there are multiple sitemap chunks.
if (count($sitemap) > 1) {
return $this->getSitemapIndex($sitemap);
if (count($chunks) > 1) {
return $this->getSitemapIndex($chunks);
}
else { // Return sitemap if there is only one chunk.
if (isset($sitemap[1])) {
return $sitemap[1]->sitemap_string;
if (isset($chunks[1])) {
return $chunks[1]->sitemap_string;
}
return FALSE;
}
}
else { // Return specific sitemap chunk.
return $sitemap[$sitemap_id]->sitemap_string;
return $chunks[$chunk_id]->sitemap_string;
}
}
......
......@@ -22,15 +22,16 @@ class SitemapGenerator {
private $sitemap;
private $links;
private $generatingFrom;
private $generateFrom;
function __construct($sitemap) {
$this->sitemap = $sitemap;
$this->links = array();
$this->links = [];
$this->generateFrom = 'form';
}
public function setGenerateFrom($from = 'form') {
$this->generatingFrom = $from;
public function setGenerateFrom($from) {
$this->generateFrom = $from;
}
/**
......@@ -39,7 +40,7 @@ class SitemapGenerator {
public function startGeneration() {
$batch = new Batch();
$batch->setBatchInfo([
'from' => $this->generatingFrom,
'from' => $this->generateFrom,
'batch_process_limit' => !empty($this->sitemap->getSetting('batch_process_limit'))
? $this->sitemap->getSetting('batch_process_limit') : NULL,
'max_links' => $this->sitemap->getSetting('max_links'),
......@@ -104,11 +105,11 @@ class SitemapGenerator {
public static function generateSitemap($links, $remove_sitemap = FALSE) {
// Invoke alter hook.
\Drupal::moduleHandler()->alter('simple_sitemap_links', $links);
$values = array(
$values = [
'id' => $remove_sitemap ? 1 : \Drupal::service('database')->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
'sitemap_string' => self::generateSitemapChunk($links),
'sitemap_created' => REQUEST_TIME,
);
];
if ($remove_sitemap) {
\Drupal::service('database')->truncate('simple_sitemap')->execute();
}
......
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