<?php
declare(strict_types=1);
namespace Hitso\Bundle\SeoBundle\EventListener;
use Hitso\Bundle\CommonBundle\Helper\Router\RouterHelper;
use Hitso\Bundle\SeoBundle\Manager\SeoPageManager;
use Hitso\Bundle\SeoBundle\Repository\SeoPageRepository;
use Hitso\Bundle\SeoBundle\Service\SeoPresentation;
use Sonata\SeoBundle\Seo\SeoPage;
use Symfony\Cmf\Bundle\SeoBundle\SeoAwareInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class SeoAwareSubscriber
*
* @package Hitso\Bundle\SeoBundle\EventListener
*/
class SeoAwareSubscriber implements EventSubscriberInterface
{
/**
* @var SeoPresentation
*/
protected $seoPresentation;
/**
* @var SeoPage
*/
protected $seoPage;
/**
* @var SeoPageManager
*/
protected $seoPageRepository;
/**
* @var RouterHelper
*/
protected $routerHelper;
/**
* SeoAwareSubscriber constructor.
*
* @param SeoPresentation $seoPresentation
* @param SeoPage $seoPage
* @param SeoPageRepository $seoPageRepository
* @param RouterHelper $routerHelper
*/
public function __construct(
SeoPresentation $seoPresentation,
SeoPage $seoPage,
SeoPageRepository $seoPageRepository,
RouterHelper $routerHelper
) {
$this->seoPresentation = $seoPresentation;
$this->seoPage = $seoPage;
$this->seoPageRepository = $seoPageRepository;
$this->routerHelper = $routerHelper;
}
/**
* @param FilterControllerEvent $event
*/
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
$context = $request->attributes->get('_firewall_context');
if ('security.firewall.map.context.admin' === $context || 'security.firewall.map.context.api') {
return;
}
if ($request->attributes->has('_route')) {
$route = $request->attributes->get('_route');
$routeParams = $request->attributes->get('_route_params', []);
$url = $this->routerHelper->generateUrl($route, $routeParams, 0);
$seoAware = $this->seoPageRepository->getPageByRoute($route);
if ($seoAware instanceof SeoAwareInterface) {
if (strlen($seoAware->getSeoMetadata()->getOriginalUrl())) {
$url = $seoAware->getSeoMetadata()->getOriginalUrl();
}
$this->seoPresentation->updateSeoPage($seoAware);
}
$this->seoPage->setLinkCanonical($url);
}
}
/**
* @param FilterControllerArgumentsEvent $event
*/
public function onControllerArguments(FilterControllerArgumentsEvent $event)
{
$arguments = $event->getArguments();
foreach ($arguments as $argument) {
if ($argument instanceof SeoAwareInterface) {
$seoMetadata = $argument->getSeoMetadata();
if ($seoMetadata) {
$this->seoPresentation->updateSeoPage($seoMetadata);
}
}
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => [['onKernelController', 1]],
KernelEvents::CONTROLLER_ARGUMENTS => ['onControllerArguments'],
];
}
}