<?php declare(strict_types=1);
namespace VRPayment\VRPay\Subscriber;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use VRPayment\VRPay\Core\Checkout\Order\TransactionDefinition;
/**
* Class CheckoutSubscriber
* Filters available payment methods
*
* @package VRPayment\VRPay\Subscriber
*/
class CheckoutSubscriber implements EventSubscriberInterface
{
/**
* @var SystemConfigService $systemConfigService
*/
private $systemConfigService;
public static function getSubscribedEvents()
{
return [
CheckoutConfirmPageLoadedEvent::class => 'onConfirmPageLoaded',
];
}
/**
* CheckoutSubscriber constructor.
*
* @param SystemConfigService $systemConfigService
*/
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
/**
* called when the confirm page was loaded. Filters out any of our payment methods that are currently not
* available (because they're inactive, not properly configured or any other restrictions apply)
*
* @param CheckoutConfirmPageLoadedEvent $event
*/
public function onConfirmPageLoaded(CheckoutConfirmPageLoadedEvent $event)
{
$page = $event->getPage();
$cart = $page->getCart();
$salesChannelContext = $event->getSalesChannelContext();
$page->setPaymentMethods(
$page->getPaymentMethods()->filter(function(PaymentMethodEntity $item) use ($cart, $salesChannelContext) {
if(0 !== strpos($item->getHandlerIdentifier(), 'VRPayment\VRPay\Service\Payment'))
{
return true;
}
return $this->isPaymentMethodAvailable($item, $cart, $salesChannelContext);
})
);
}
/*
* internals
*/
/**
* checks if the given payment method is currently available
*
* @param PaymentMethodEntity $method
* @param Cart $cart
* @param SalesChannelContext $salesChannelContext
*
* @return bool
*/
private function isPaymentMethodAvailable(PaymentMethodEntity $method, Cart $cart, SalesChannelContext $salesChannelContext)
{
$handler = $method->getHandlerIdentifier();
if(is_callable([$handler, 'isActive']))
{
return $handler::isActive($cart, $this->systemConfigService, $salesChannelContext);
}
return true;
}
}