<?php
namespace Platform\MarketingBundle\Listeners;
use Cms\CoreBundle\Service\ContextManager;
use Platform\MarketingBundle\Model\ProductControllerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
/**
* Class UpsellListener
* @package Platform\MarketingBundle\EventListener
*/
final class UpsellListener implements EventSubscriberInterface
{
/**
* @var ContextManager
*/
protected ContextManager $cm;
/**
* @var RouterInterface
*/
protected RouterInterface $router;
/**
* @param ContextManager $cm
* @param RouterInterface $router
*/
public function __construct(ContextManager $cm, RouterInterface $router)
{
$this->cm = $cm;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => ['productCheck'],
];
}
/**
* @param ControllerEvent $event
*/
public function productCheck(ControllerEvent $event): void
{
// get the controller
$controller = $event->getController();
// should be an array of object then method call
if (is_array($controller) && $controller[0] instanceof ProductControllerInterface) {
// must have a tenant
$tenant = $this->cm->getGlobalContext()->getTenant();
if (empty($tenant)) {
return;
}
// we know that we can call the interface method, which is static, on the controller
try {
$result = $controller[0]->productCheck(
$tenant->getProducts()
);
if ( ! empty($result) && ! $result instanceof Response) {
throw new \Exception();
}
} catch (\Exception $e) {
$result = $e;
}
// if we have a non-empty result, need to reset the controller
// also need to stop propagation
if ( ! empty($result)) {
$event->stopPropagation();
$event->setController(
function () use ($result) {
if ($result instanceof \Exception) {
throw $result;
}
return $result;
}
);
}
}
}
}