<?php
namespace Wabs\IgmTheme\Subscriber;
use PayonePayment\Components\TransactionStatus\TransactionStatusService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionDefinition;
use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\StateMachine\StateMachineRegistry;
use Shopware\Core\System\StateMachine\Transition;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FrontendSubscriber implements EventSubscriberInterface {
/**
* @var StateMachineRegistry
*/
protected StateMachineRegistry $stateMachineRegistry;
/**
* @var EntityRepositoryInterface
*/
protected EntityRepositoryInterface $paymentMethodRepository;
/**
* @param StateMachineRegistry $transactionStatusService
* @param EntityRepositoryInterface $paymentMethodRepository
*/
public function __construct(StateMachineRegistry $transactionStatusService, EntityRepositoryInterface $paymentMethodRepository) {
$this->stateMachineRegistry = $transactionStatusService;
$this->paymentMethodRepository = $paymentMethodRepository;
}
public static function getSubscribedEvents() {
return [
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced'
];
}
/**
* @param $methodName
* @param Context $context
* @return PaymentMethodEntity|null
*/
private function getPaymentMethodByName($methodName, Context $context): ?PaymentMethodEntity {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $methodName));
$criteria->addFilter(new EqualsFilter('active', true));
return $this->paymentMethodRepository->search($criteria, $context)->first();
}
public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event) {
$order = $event->getOrder();
$lastTransactions = $order->getTransactions()->last();
$currentPaymentMethod = $lastTransactions->getPaymentMethod();
$freePaymentMethod = $this->getPaymentMethodByName('Keine (kostenfreie Bestellung)', $event->getContext());
if ($currentPaymentMethod && $freePaymentMethod) {
if ($currentPaymentMethod->getId() === $freePaymentMethod->getId()) {
$this->stateMachineRegistry->transition(
new Transition(
OrderTransactionDefinition::ENTITY_NAME,
$lastTransactions->getId(),
'paid',
'stateId'
),
$event->getContext()
);
}
}
}
}