<?php declare(strict_types=1);
namespace App\Seo\EventSubscriber;
use App\Seo\Entity\UrlSeo;
use Doctrine\ORM\EntityManagerInterface;
use Sonata\SeoBundle\Seo\SeoPageInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Цепляем нужную метаинформацию по URL
*
* Class UrlSeoControllerSubscriber
* @package App\EventSubscriber\Seo
*/
class UrlSeoControllerSubscriber implements EventSubscriberInterface
{
public function __construct(private EntityManagerInterface $entityManager, private SeoPageInterface $seoPage)
{
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event): void
{
$request = $event->getRequest();
$decoded = urldecode($request->getPathInfo());
/** @var UrlSeo|null $item */
$item = $this->entityManager
->getRepository(UrlSeo::class)
->findOneBy([
'url' => $decoded
]);
if (!$item) {
return;
}
if ($item->getTitle()) {
$this->seoPage->setTitle($item->getTitle());
}
if ($item->getKeywords()) {
$this->seoPage->addMeta('name', 'keywords', $item->getKeywords());
}
if ($item->getDescription()) {
$this->seoPage->addMeta('name', 'description', $item->getDescription());
}
}
}