<?php
namespace Customize\EventListener;
use Customize\Entity\Master\VendorStatus;
use Customize\Enum\SessionNames;
use Customize\Repository\Master\AuthorityRepository;
use Customize\Repository\VendorRepository;
use Eccube\Request\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class CustomTwigInitializeListener implements EventSubscriberInterface
{
private Environment $twig;
private Context $requestContext;
private AuthorityRepository $authRepo;
private VendorRepository $vendorRepo;
private SessionInterface $session;
public function __construct(Environment $twig, Context $context, AuthorityRepository $authRepo, VendorRepository $vendorRepo, SessionInterface $session)
{
$this->twig = $twig;
$this->requestContext = $context;
$this->authRepo = $authRepo;
$this->vendorRepo = $vendorRepo;
$this->session = $session;
}
public function onKernelController(ControllerEvent $event)
{
if ($this->requestContext->isAdmin()) {
$this->setAdminGlobals($event);
}
}
private function setAdminGlobals($event)
{
$isSysAdmin = $this->authRepo->isSystemAdmin();
$curVendorId = $this->session->get(SessionNames::CURRENT_VENDOR_ID);
if ($isSysAdmin) {
$vendors = $this->vendorRepo->findBy(['Status' => VendorStatus::PUBLISHED]);
$filtered = array_filter($vendors, function ($item) use ($curVendorId) {
return $item['id'] == $curVendorId;
});
// In case of changing the status of the selected vendor
if (empty($filtered)) {
$this->session->set(SessionNames::CURRENT_VENDOR_ID, null);
}
$this->twig->addGlobal('vendors', $vendors);
$this->twig->addGlobal('current_vendor_id', $curVendorId);
} else {
$user = $this->requestContext->getCurrentUser();
$userVendorId = !empty($user) ? $user->getVendorId() : null;
if ($curVendorId != $userVendorId) {
$this->session->set(SessionNames::CURRENT_VENDOR_ID, $user->getVendorId());
}
}
$this->twig->addGlobal('isSysAdmin', $isSysAdmin);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}