custom/plugins/SasBlogModule/src/Storefront/Framework/Seo/SeoUrlRoute/SeoUrlUpdateListener.php line 50

  1. <?php declare(strict_types=1);
  2. namespace Sas\BlogModule\Storefront\Framework\Seo\SeoUrlRoute;
  3. use Sas\BlogModule\Content\Blog\BlogSeoUrlRoute;
  4. use Sas\BlogModule\Content\Blog\Events\BlogIndexerEvent;
  5. use Shopware\Core\Content\Seo\SeoUrlUpdater;
  6. use Shopware\Core\Framework\Context;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. class SeoUrlUpdateListener implements EventSubscriberInterface
  14. {
  15.     private SeoUrlUpdater $seoUrlUpdater;
  16.     private EntityRepository $blogRepository;
  17.     /**
  18.      * @internal
  19.      */
  20.     public function __construct(
  21.         SeoUrlUpdater $seoUrlUpdater,
  22.         EntityRepository $blogRepository
  23.     ) {
  24.         $this->seoUrlUpdater $seoUrlUpdater;
  25.         $this->blogRepository $blogRepository;
  26.     }
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             BlogIndexerEvent::class => 'updateBlogUrls',
  31.             'sales_channel.written' => 'onCreateNewSalesChannel',
  32.         ];
  33.     }
  34.     public function updateBlogUrls(BlogIndexerEvent $event): void
  35.     {
  36.         if (\count($event->getIds()) === 0) {
  37.             return;
  38.         }
  39.         $this->seoUrlUpdater->update(BlogSeoUrlRoute::ROUTE_NAME$event->getIds());
  40.     }
  41.     public function onCreateNewSalesChannel(EntityWrittenEvent $event): void
  42.     {
  43.         if (\count($event->getIds()) === 0) {
  44.             return;
  45.         }
  46.         $blogArticlesIds $this->getBlogArticlesIds($event->getContext());
  47.         if (\count($blogArticlesIds) === 0) {
  48.             return;
  49.         }
  50.         $this->seoUrlUpdater->update(BlogSeoUrlRoute::ROUTE_NAME$blogArticlesIds);
  51.     }
  52.     private function getBlogArticlesIds(Context $context): array
  53.     {
  54.         $criteria = new Criteria();
  55.         $dateTime = new \DateTime();
  56.         $criteria->addFilter(
  57.             new EqualsFilter('active'true),
  58.             new RangeFilter('publishedAt', [RangeFilter::LTE => $dateTime->format(\DATE_ATOM)])
  59.         );
  60.         return $this->blogRepository->searchIds($criteria$context)->getIds();
  61.     }
  62. }