Skip to content
Snippets Groups Projects
Commit a26700d7 authored by Pawel G's avatar Pawel G
Browse files

Add 3 hooks: hook_simple_sitemap_arbitrary_links_alter,...

Add 3 hooks: hook_simple_sitemap_arbitrary_links_alter, hook_simple_sitemap_attributes_alter, hook_simple_sitemap_index_attributes_alter
parent 1157cd71
No related branches found
No related tags found
No related merge requests found
......@@ -21,9 +21,9 @@ function hook_simple_sitemap_links_alter(&$links) {
// Remove German URL for a certain path in the hreflang sitemap.
foreach ($links as $key => $link) {
if ($link['path'] == 'node/1') {
if ($link['path'] === 'node/1') {
// Remove 'loc' URL if it points to a german site.
if ($link['langcode'] == 'de') {
if ($link['langcode'] === 'de') {
unset($links[$key]);
}
// If this 'loc' URL points to a non-german site, make sure to remove
......@@ -37,6 +37,47 @@ function hook_simple_sitemap_links_alter(&$links) {
}
}
/**
* Use this hook to add arbitrary links to the sitemap.
*
* @param array &$arbitrary_links
*/
function hook_simple_sitemap_arbitrary_links_alter(&$arbitrary_links) {
// Add an arbitrary link.
$arbitrary_links[] = [
'url' => 'http://example.com',
'priority' => '0.5',
'lastmod' => '2012-10-12T17:40:30+02:00',
'changefreq' => 'weekly',
'images' => ['http://path-to-image.png']
];
}
/**
* Alters the sitemap attributes shortly before XML document generation.
* Attributes can be added, changed and removed.
*
* @param array &$attributes
*/
function hook_simple_sitemap_attributes_alter(&$attributes) {
// Remove the xhtml attribute e.g. if no xhtml sitemap elements are present.
unset($attributes['xmlns:xhtml']);
}
/**
* Alters attributes of the sitemap index. shortly before XML document generation.
* Attributes can be added, changed and removed.
*
* @param array &$index_attributes
*/
function hook_simple_sitemap_index_attributes_alter(&$index_attributes) {
// Add some attribute to the sitemap index.
$index_attributes['name'] = 'value';
}
/**
* @} End of "addtogroup hooks".
*/
......@@ -64,6 +64,18 @@ services:
- '@simple_sitemap.logger'
- '@simple_sitemap.entity_helper'
simple_sitemap.arbitrary_url_generator:
class: Drupal\simple_sitemap\Batch\ArbitraryUrlGenerator
public: true
arguments:
- '@simple_sitemap.generator'
- '@simple_sitemap.sitemap_generator'
- '@language_manager'
- '@entity_type.manager'
- '@path.validator'
- '@simple_sitemap.logger'
- '@simple_sitemap.entity_helper'
simple_sitemap.logger:
class: Drupal\simple_sitemap\Logger
public: true
......
<?php
namespace Drupal\simple_sitemap\Batch;
/**
* Class ArbitraryUrlGenerator
* @package Drupal\simple_sitemap\Batch
*/
class ArbitraryUrlGenerator extends UrlGeneratorBase implements UrlGeneratorInterface {
/**
* Batch function that adds arbitrary URLs to the sitemap.
*
* @param mixed $arbitrary_paths
*/
public function generate($arbitrary_paths) {
foreach ($this->getBatchIterationElements($arbitrary_paths) as $i => $path_data) {
$this->setCurrentId($i);
$this->context['results']['generate'][] = $path_data;
}
$this->processSegment();
}
}
......@@ -43,7 +43,6 @@ class Batch {
'error_message' => $this->t(self::BATCH_ERROR_MESSAGE),
'progress_message' => $this->t(self::BATCH_PROGRESS_MESSAGE),
'operations' => [],
// __CLASS__ . '::finishGeneration' not working possibly due to a drush error.
'finished' => [__CLASS__, 'finishGeneration'],
];
}
......@@ -107,12 +106,12 @@ class Batch {
/**
* Adds an operation to the batch.
*
* @param string $processing_method
* @param string $processing_service
* @param array $data
*/
public function addOperation($processing_method, array $data) {
public function addOperation($processing_service, array $data) {
$this->batch['operations'][] = [
__CLASS__ . '::' . $processing_method, [$data, $this->batchInfo],
__CLASS__ . '::generate', [$processing_service, $data, $this->batchInfo],
];
}
......@@ -125,27 +124,22 @@ class Batch {
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public static function generateBundleUrls(array $entity_info, array $batch_info, &$context) {
\Drupal::service('simple_sitemap.entity_url_generator')
->setContext($context)
->setBatchInfo($batch_info)
->generate($entity_info);
}
/**
* Batch callback function which generates urls to custom paths.
* Batch callback function which generates URLs.
*
* @param array $custom_paths
* @param $processing_service
* @param array $data
* @param array $batch_info
* @param array &$context
* @param $context
*
* @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
*/
public static function generateCustomUrls(array $custom_paths, array $batch_info, &$context) {
\Drupal::service('simple_sitemap.custom_url_generator')
public static function generate($processing_service, array $data, array $batch_info, &$context) {
\Drupal::service($processing_service)
->setContext($context)
->setBatchInfo($batch_info)
->generate($custom_paths);
->generate($data);
}
/**
......
......@@ -19,7 +19,7 @@ class CustomUrlGenerator extends UrlGeneratorBase implements UrlGeneratorInterfa
*/
public function generate($custom_paths) {
foreach ($this->getBatchIterationCustomPaths($custom_paths) as $i => $custom_path) {
foreach ($this->getBatchIterationElements($custom_paths) as $i => $custom_path) {
$this->setCurrentId($i);
......@@ -58,21 +58,4 @@ class CustomUrlGenerator extends UrlGeneratorBase implements UrlGeneratorInterfa
}
$this->processSegment();
}
/**
* @param array $custom_paths
* @return array
*/
protected function getBatchIterationCustomPaths(array $custom_paths) {
if ($this->needsInitialization()) {
$this->initializeBatch(count($custom_paths));
}
if ($this->isBatch()) {
$custom_paths = array_slice($custom_paths, $this->context['sandbox']['progress'], $this->batchInfo['batch_process_limit']);
}
return $custom_paths;
}
}
......@@ -15,7 +15,7 @@ class EntityUrlGenerator extends UrlGeneratorBase implements UrlGeneratorInterfa
*/
public function generate($entity_info) {
foreach ($this->getBatchIterationEntities($entity_info) as $entity_id => $entity) {
foreach ($this->getBatchIterationElements($entity_info) as $entity_id => $entity) {
$this->setCurrentId($entity_id);
......@@ -77,7 +77,7 @@ class EntityUrlGenerator extends UrlGeneratorBase implements UrlGeneratorInterfa
* @param array $entity_info
* @return \Drupal\Core\Entity\EntityInterface[]
*/
protected function getBatchIterationEntities(array $entity_info) {
protected function getBatchIterationElements(array $entity_info) {
$query = $this->entityTypeManager->getStorage($entity_info['entity_type_name'])->getQuery();
if (!empty($entity_info['keys']['id'])) {
......
......@@ -284,4 +284,21 @@ class UrlGeneratorBase {
? str_replace($GLOBALS['base_url'], $this->batchInfo['base_url'], $url)
: $url;
}
/**
* @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;
}
}
......@@ -63,6 +63,16 @@ class SitemapGenerator {
*/
protected $generator;
protected static $attributes = [
'xmlns' => self::XMLNS,
'xmlns:xhtml' => self::XMLNS_XHTML,
'xmlns:image' => self::XMLNS_IMAGE,
];
protected static $indexAttributes = [
'xmlns' => self::XMLNS,
];
/**
* SitemapGenerator constructor.
* @param \Drupal\simple_sitemap\Batch\Batch $batch
......@@ -129,13 +139,22 @@ class SitemapGenerator {
'entity_types' => $this->generator->getBundleSettings(),
'base_url' => $this->generator->getSetting('base_url', ''),
]);
// Add custom link generating operation.
$this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
$this->batch->addOperation('simple_sitemap.custom_url_generator', $this->getCustomUrlsData());
// Add entity link generating operations.
foreach ($this->getEntityTypeData() as $data) {
$this->batch->addOperation('generateBundleUrls', $data);
$this->batch->addOperation('simple_sitemap.entity_url_generator', $data);
}
// Add arbitrary links generating operation.
$arbitrary_links = [];
$this->moduleHandler->alter('simple_sitemap_arbitrary_links', $arbitrary_links);
if (!empty($arbitrary_links)) {
$this->batch->addOperation('simple_sitemap.arbitrary_url_generator', $arbitrary_links);
}
$this->batch->start();
}
......@@ -151,8 +170,6 @@ class SitemapGenerator {
$paths[$i]['path'] = $custom_path['path'];
$paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
$paths[$i]['changefreq'] = isset($custom_path['changefreq']) ? $custom_path['changefreq'] : NULL;
// todo: implement lastmod.
$paths[$i]['lastmod'] = NULL;
}
return $paths;
}
......@@ -190,8 +207,8 @@ class SitemapGenerator {
}
/**
* Wrapper method which takes links along with their options, lets other
* modules alter the links and then generates and saves the sitemap.
* Wrapper method which takes links along with their options and then
* generates and saves the sitemap.
*
* @param array $links
* All links with their multilingual versions and settings.
......@@ -199,9 +216,6 @@ class SitemapGenerator {
* Remove old sitemap from database before inserting the new one.
*/
public function generateSitemap(array $links, $remove_sitemap = FALSE) {
// Invoke alter hook.
$this->moduleHandler->alter('simple_sitemap_links', $links);
$values = [
'id' => $remove_sitemap ? self::FIRST_CHUNK_INDEX
: $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')
......@@ -230,20 +244,29 @@ class SitemapGenerator {
$writer->startDocument(self::XML_VERSION, self::ENCODING);
$writer->writeComment(self::GENERATED_BY);
$writer->startElement('sitemapindex');
$writer->writeAttribute('xmlns', self::XMLNS);
$writer->writeAttribute('xmlns:image', self::XMLNS_IMAGE);
// Add attributes to document.
$this->moduleHandler->alter('simple_sitemap_index_attributes', self::$indexAttributes);
foreach (self::$indexAttributes as $name => $value) {
$writer->writeAttribute($name, $value);
}
// Add sitemap locations to document.
foreach ($chunk_info as $chunk_id => $chunk_data) {
$writer->startElement('sitemap');
$writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
$writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
$writer->endElement();
}
$writer->endElement();
$writer->endDocument();
return $writer->outputMemory();
}
/**
* @return string
*/
public function getCustomBaseUrl() {
$customBaseUrl = $this->generator->getSetting('base_url', '');
return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
......@@ -265,13 +288,18 @@ class SitemapGenerator {
$writer->startDocument(self::XML_VERSION, self::ENCODING);
$writer->writeComment(self::GENERATED_BY);
$writer->startElement('urlset');
$writer->writeAttribute('xmlns', self::XMLNS);
$writer->writeAttribute('xmlns:image', self::XMLNS_IMAGE);
if ($this->isHreflangSitemap()) {
$writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
// Add attributes to document.
if (!$this->isHreflangSitemap()) {
unset(self::$attributes['xmlns:xhtml']);
}
$this->moduleHandler->alter('simple_sitemap_attributes', self::$attributes);
foreach (self::$attributes as $name => $value) {
$writer->writeAttribute($name, $value);
}
// Add URLs to document.
$this->moduleHandler->alter('simple_sitemap_links', $links);
foreach ($links as $link) {
// Add each translation variant URL as location to the sitemap.
......@@ -281,7 +309,7 @@ class SitemapGenerator {
// If more than one language is enabled, add all translation variant URLs
// as alternate links to this location turning the sitemap into a hreflang
// sitemap.
if ($this->isHreflangSitemap()) {
if (isset($link['alternate_urls']) && $this->isHreflangSitemap()) {
foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
$writer->startElement('xhtml:link');
$writer->writeAttribute('rel', 'alternate');
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment