<?php
/*
ここは、Symfonyの「controller実行前」イベントすべてに反応する
⇒ 大前提:shopping 以外はスルー。
*/
namespace Plugin\SDream\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Eccube\Controller\ShoppingController;
use Psr\Log\LoggerInterface;
use Eccube\Service\CartService;
use Symfony\Component\Security\Core\Security;
use Plugin\SDream\Service\PaymentRestrictionService;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
class ShoppingIndexSubscriber implements EventSubscriberInterface
{
private RouterInterface $router;
private LoggerInterface $logger;
private Security $security;
private CartService $cartService;
private PaymentRestrictionService $paymentRestrictionService;
private FlashBagInterface $flashBag;
public function __construct(
RouterInterface $router,
LoggerInterface $logger,
Security $security,
CartService $cartService,
PaymentRestrictionService $paymentRestrictionService,
FlashBagInterface $flashBag
)
{
$this->router = $router;
$this->logger = $logger;
$this->security = $security;
$this->cartService = $cartService;
$this->paymentRestrictionService = $paymentRestrictionService;
$this->flashBag = $flashBag;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onController',
];
}
public function onController(ControllerEvent $event)
{
// メインリクエスト以外は無視
if (!$event->isMainRequest()) {
return;
}
$route = $event->getRequest()->attributes->get('_route');
// shopping 以外は何もしない
if ($route !== 'shopping') {
return; //大前提:shopping 以外はスルー。
}
$controller = $event->getController();
// ShoppingControllerのみ
// 通常、[ Controllerインスタンス, 'method名' ]の形で、kernel.controller の $event->getController() を扱っているから、違う形「!is_array($controller)」の場合はスルー
if (!is_array($controller) || !$controller[0] instanceof ShoppingController) {
return;
}
$this->logger->info('onController called (test log)');
$this->logger->info('route name: '.$event->getRequest()->attributes->get('_route'));
$Cart = $this->cartService->getCart();
if (!$Cart) {
return;
}
$Customer = $this->security->getUser();
$allowedPayments = $this->paymentRestrictionService
->resolveAllowedPayments($Cart, $Customer);
$allowedPaymentIds = array_map(
fn($p) => $p->getId(),
$allowedPayments
);
if (empty($allowedPaymentIds)) {
$this->flashBag->add(
'eccube.front.shopping.error',
'現在のご注文内容ではご利用いただける支払方法がありません。'
);
}
/*
$this->logger->info(
'[ShoppingIndex] allowedPaymentIds',
['allowedPaymentIds' => $allowedPaymentIds]
);
*/
$event->getRequest()->attributes->set(
'allowedPaymentIds',
$allowedPaymentIds
);
}
}