OrderCancellation.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Braintree\Plugin;
  8. use Magento\Braintree\Model\Paypal\OrderCancellationService;
  9. use Magento\Braintree\Model\Ui\ConfigProvider;
  10. use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider;
  11. use Magento\Framework\Exception\LocalizedException;
  12. use Magento\Quote\Api\CartManagementInterface;
  13. use Magento\Quote\Api\CartRepositoryInterface;
  14. use Magento\Quote\Api\Data\PaymentInterface;
  15. /**
  16. * Cancels an order and an authorization transaction.
  17. */
  18. class OrderCancellation
  19. {
  20. /**
  21. * @var OrderCancellationService
  22. */
  23. private $orderCancellationService;
  24. /**
  25. * @var CartRepositoryInterface
  26. */
  27. private $quoteRepository;
  28. /**
  29. * @param OrderCancellationService $orderCancellationService
  30. * @param CartRepositoryInterface $quoteRepository
  31. */
  32. public function __construct(
  33. OrderCancellationService $orderCancellationService,
  34. CartRepositoryInterface $quoteRepository
  35. ) {
  36. $this->orderCancellationService = $orderCancellationService;
  37. $this->quoteRepository = $quoteRepository;
  38. }
  39. /**
  40. * Cancels an order if an exception occurs during the order creation.
  41. *
  42. * @param CartManagementInterface $subject
  43. * @param \Closure $proceed
  44. * @param int $cartId
  45. * @param PaymentInterface $payment
  46. * @return int
  47. * @throws \Exception
  48. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  49. */
  50. public function aroundPlaceOrder(
  51. CartManagementInterface $subject,
  52. \Closure $proceed,
  53. $cartId,
  54. PaymentInterface $payment = null
  55. ) {
  56. try {
  57. return $proceed($cartId, $payment);
  58. } catch (\Exception $e) {
  59. $quote = $this->quoteRepository->get((int) $cartId);
  60. $payment = $quote->getPayment();
  61. $paymentCodes = [
  62. ConfigProvider::CODE,
  63. ConfigProvider::CC_VAULT_CODE,
  64. PayPalConfigProvider::PAYPAL_CODE,
  65. PayPalConfigProvider::PAYPAL_VAULT_CODE
  66. ];
  67. if (in_array($payment->getMethod(), $paymentCodes)) {
  68. $incrementId = $quote->getReservedOrderId();
  69. $this->orderCancellationService->execute($incrementId);
  70. }
  71. throw $e;
  72. }
  73. }
  74. }