Created
September 19, 2024 08:44
-
-
Save benr77/5821d1b8be82d75410afc4c0db2e2a2e to your computer and use it in GitHub Desktop.
SuluCMS exclude specified webspaces from sitemap.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace App\Infra; | |
| use Sulu\Bundle\PageBundle\Document\HomeDocument; | |
| use Sulu\Bundle\PageBundle\Document\PageDocument; | |
| use Sulu\Component\Content\Document\Extension\ExtensionContainer; | |
| use Sulu\Component\DocumentManager\Event\PersistEvent; | |
| use Sulu\Component\DocumentManager\Events; | |
| use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag; | |
| use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
| /** | |
| * For some webspaces, we never want their contents to be shown in the sitemap.xml. | |
| * This is because these webspaces contain e.g. member only content that is privileged. | |
| * | |
| * Here we detect changes to documents inside specific webspaces and then force the | |
| * "hideInSitemap" setting to be enabled. This means even if a user unsets the setting | |
| * this listener will simply override it. | |
| */ | |
| #[AutoconfigureTag(name: 'sulu_document_manager.event_subscriber')] | |
| readonly class HideInSitemapListener implements EventSubscriberInterface | |
| { | |
| private const array PRIVATE_WEBSPACES = [ | |
| 'some-private-webspace-key', | |
| 'another-member-only-webspace-key', | |
| ]; | |
| public static function getSubscribedEvents(): array | |
| { | |
| return [ | |
| Events::PERSIST => 'hideInSitemap', | |
| ]; | |
| } | |
| public function hideInSitemap(PersistEvent $event): void | |
| { | |
| $document = $event->getDocument(); | |
| if (!$document instanceof PageDocument && !$document instanceof HomeDocument) | |
| { | |
| return; | |
| } | |
| if (in_array($document->getWebspaceName(), self::PRIVATE_WEBSPACES)) | |
| { | |
| /** @var ExtensionContainer $extensionsData */ | |
| $extensionsData = $document->getExtensionsData(); | |
| /** @var array<string, string> $seoConfig */ | |
| $seoConfig = $extensionsData->offsetGet('seo'); | |
| $seoConfig['hideInSitemap'] = true; | |
| $document->setExtension('seo', $seoConfig); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment