src/Seo/EventSubscriber/UrlSeoControllerSubscriber.php line 35

  1. <?php declare(strict_types=1);
  2. namespace App\Seo\EventSubscriber;
  3. use App\Seo\Entity\UrlSeo;
  4. use App\Seo\Repository\SeoSettingsRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Sonata\SeoBundle\Seo\SeoPageInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. /**
  11.  * Цепляем нужную метаинформацию по URL
  12.  *
  13.  * Class UrlSeoControllerSubscriber
  14.  * @package App\EventSubscriber\Seo
  15.  */
  16. class UrlSeoControllerSubscriber implements EventSubscriberInterface
  17. {
  18.     public function __construct(
  19.         private EntityManagerInterface $entityManager,
  20.         private SeoPageInterface $seoPage,
  21.         private SeoSettingsRepository $seoSettingsRepository,
  22.     ) {
  23.     }
  24.     public static function getSubscribedEvents()
  25.     {
  26.         return [
  27.             KernelEvents::CONTROLLER => 'onKernelController',
  28.         ];
  29.     }
  30.     public function onKernelController(ControllerEvent $event): void
  31.     {
  32.         $request $event->getRequest();
  33.         $decoded urldecode($request->getPathInfo());
  34.         $seoSettings $this->seoSettingsRepository->getOrCreate();
  35.         $metaSuffix $seoSettings->getMetaSuffix();
  36.         $separator {$seoSettings->getMetaSuffixSeparator()} " ?: ' ';
  37.         $this->seoPage->setSeparator($separator);
  38.         /** @var UrlSeo|null $item */
  39.         $item $this->entityManager
  40.             ->getRepository(UrlSeo::class)
  41.             ->findOneBy([
  42.                 'url' => $decoded
  43.             ]);
  44.         if (!$item) {
  45.             return;
  46.         }
  47.         if ($item->getTitle()) {
  48.             $this->seoPage->setTitle($item->getTitle());
  49.         }
  50.         if ($item->getKeywords()) {
  51.             $this->seoPage->addMeta('name''keywords'$item->getKeywords());
  52.         }
  53.         if ($item->getDescription()) {
  54.             $this->seoPage->addMeta('name''description'$item->getDescription());
  55.         }
  56.         if ($metaSuffix) {
  57.             $this->seoPage->addTitleSuffix($metaSuffix);
  58.         }
  59.     }
  60. }