<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\Payment\EventSubscriber;
use Ibexa\Contracts\OrderManagement\Event\BeforeCancelOrderEvent;
use Ibexa\Contracts\OrderManagement\Value\Order\OrderInterface;
use Ibexa\Contracts\Payment\Payment\PaymentInterface;
use Ibexa\Contracts\Payment\Payment\PaymentQuery;
use Ibexa\Contracts\Payment\Payment\PaymentUpdateStruct;
use Ibexa\Contracts\Payment\Payment\Query\Criterion\Order as PaymentOrderCriterion;
use Ibexa\Contracts\Payment\PaymentServiceInterface;
use Ibexa\Payment\Workflow\WorkflowResolver;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class PaymentCancellingSubscriber implements EventSubscriberInterface
{
private PaymentServiceInterface $paymentService;
private WorkflowResolver $workflowResolver;
public function __construct(
PaymentServiceInterface $paymentService,
WorkflowResolver $workflowResolver
) {
$this->paymentService = $paymentService;
$this->workflowResolver = $workflowResolver;
}
public static function getSubscribedEvents(): array
{
return [
BeforeCancelOrderEvent::class => 'cancelPayment',
];
}
/**
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\UnauthorizedException
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\BadStateException
*/
public function cancelPayment(BeforeCancelOrderEvent $event): void
{
$payment = $this->getOrderPayment($event->getOrder());
if ($payment === null) {
return;
}
$workflow = $this->workflowResolver->resolveWorkflow($payment);
if ($workflow->can($payment, 'cancel')) {
$this->paymentService->updatePayment($payment, new PaymentUpdateStruct('cancel'));
}
}
private function getOrderPayment(OrderInterface $order): ?PaymentInterface
{
$payments = $this->paymentService->findPayments(
new PaymentQuery(new PaymentOrderCriterion($order))
)->getPayments();
return $payments[0] ?? null;
}
}