vendor/ibexa/payment/src/bundle/EventSubscriber/PaymentCancellingSubscriber.php line 46

Open in your IDE?
  1. <?php
  2. /**
  3. * @copyright Copyright (C) Ibexa AS. All rights reserved.
  4. * @license For full copyright and license information view LICENSE file distributed with this source code.
  5. */
  6. declare(strict_types=1);
  7. namespace Ibexa\Bundle\Payment\EventSubscriber;
  8. use Ibexa\Contracts\OrderManagement\Event\BeforeCancelOrderEvent;
  9. use Ibexa\Contracts\OrderManagement\Value\Order\OrderInterface;
  10. use Ibexa\Contracts\Payment\Payment\PaymentInterface;
  11. use Ibexa\Contracts\Payment\Payment\PaymentQuery;
  12. use Ibexa\Contracts\Payment\Payment\PaymentUpdateStruct;
  13. use Ibexa\Contracts\Payment\Payment\Query\Criterion\Order as PaymentOrderCriterion;
  14. use Ibexa\Contracts\Payment\PaymentServiceInterface;
  15. use Ibexa\Payment\Workflow\WorkflowResolver;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. final class PaymentCancellingSubscriber implements EventSubscriberInterface
  18. {
  19. private PaymentServiceInterface $paymentService;
  20. private WorkflowResolver $workflowResolver;
  21. public function __construct(
  22. PaymentServiceInterface $paymentService,
  23. WorkflowResolver $workflowResolver
  24. ) {
  25. $this->paymentService = $paymentService;
  26. $this->workflowResolver = $workflowResolver;
  27. }
  28. public static function getSubscribedEvents(): array
  29. {
  30. return [
  31. BeforeCancelOrderEvent::class => 'cancelPayment',
  32. ];
  33. }
  34. /**
  35. * @throws \Ibexa\Contracts\Core\Repository\Exceptions\UnauthorizedException
  36. * @throws \Ibexa\Contracts\Core\Repository\Exceptions\BadStateException
  37. */
  38. public function cancelPayment(BeforeCancelOrderEvent $event): void
  39. {
  40. $payment = $this->getOrderPayment($event->getOrder());
  41. if ($payment === null) {
  42. return;
  43. }
  44. $workflow = $this->workflowResolver->resolveWorkflow($payment);
  45. if ($workflow->can($payment, 'cancel')) {
  46. $this->paymentService->updatePayment($payment, new PaymentUpdateStruct('cancel'));
  47. }
  48. }
  49. private function getOrderPayment(OrderInterface $order): ?PaymentInterface
  50. {
  51. $payments = $this->paymentService->findPayments(
  52. new PaymentQuery(new PaymentOrderCriterion($order))
  53. )->getPayments();
  54. return $payments[0] ?? null;
  55. }
  56. }