vendor/contao/core-bundle/src/EventListener/RobotsTxtListener.php line 38

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of Contao.
  5.  *
  6.  * (c) Leo Feyer
  7.  *
  8.  * @license LGPL-3.0-or-later
  9.  */
  10. namespace Contao\CoreBundle\EventListener;
  11. use Contao\CoreBundle\Event\RobotsTxtEvent;
  12. use Contao\CoreBundle\Framework\ContaoFramework;
  13. use Contao\PageModel;
  14. use webignition\RobotsTxt\Directive\Directive;
  15. use webignition\RobotsTxt\Directive\UserAgentDirective;
  16. use webignition\RobotsTxt\Inspector\Inspector;
  17. use webignition\RobotsTxt\Record\Record;
  18. /**
  19.  * @internal
  20.  */
  21. class RobotsTxtListener
  22. {
  23.     /**
  24.      * @var ContaoFramework
  25.      */
  26.     private $contaoFramework;
  27.     public function __construct(ContaoFramework $contaoFramework)
  28.     {
  29.         $this->contaoFramework $contaoFramework;
  30.     }
  31.     public function __invoke(RobotsTxtEvent $event): void
  32.     {
  33.         $this->contaoFramework->initialize();
  34.         $file $event->getFile();
  35.         $inspector = new Inspector($file'*');
  36.         // Get all directives for user-agent: *
  37.         $directiveList $inspector->getDirectives();
  38.         // If no directive for user-agent: * exists, we add the record
  39.         if (=== $directiveList->getLength()) {
  40.             $record = new Record();
  41.             $userAgentDirectiveList $record->getUserAgentDirectiveList();
  42.             $userAgentDirectiveList->add(new UserAgentDirective('*'));
  43.             $file->addRecord($record);
  44.         }
  45.         $records $file->getRecords();
  46.         foreach ($records as $record) {
  47.             $directiveList $record->getDirectiveList();
  48.             $directiveList->add(new Directive('Disallow''/contao/'));
  49.         }
  50.         /** @var PageModel $pageModel */
  51.         $pageModel $this->contaoFramework->getAdapter(PageModel::class);
  52.         // Only fetch the fallback page because there can only be one sitemap per host
  53.         $rootPage $pageModel->findPublishedFallbackByHostname($event->getRootPage()->dns);
  54.         if (null === $rootPage) {
  55.             return;
  56.         }
  57.         $sitemap sprintf(
  58.             '%s%s/sitemap.xml',
  59.             $rootPage->useSSL 'https://' 'http://',
  60.             $rootPage->dns ?: $event->getRequest()->server->get('HTTP_HOST')
  61.         );
  62.         $event->getFile()->getNonGroupDirectives()->add(new Directive('Sitemap'$sitemap));
  63.     }
  64. }