OrderCancellation.php 2.38 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Magento\Braintree\Plugin;

use Magento\Braintree\Model\Paypal\OrderCancellationService;
use Magento\Braintree\Model\Ui\ConfigProvider;
use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider;
use Magento\Framework\Exception\LocalizedException;
use Magento\Quote\Api\CartManagementInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\PaymentInterface;

/**
 * Cancels an order and an authorization transaction.
 */
class OrderCancellation
{
    /**
     * @var OrderCancellationService
     */
    private $orderCancellationService;

    /**
     * @var CartRepositoryInterface
     */
    private $quoteRepository;

    /**
     * @param OrderCancellationService $orderCancellationService
     * @param CartRepositoryInterface $quoteRepository
     */
    public function __construct(
        OrderCancellationService $orderCancellationService,
        CartRepositoryInterface $quoteRepository
    ) {
        $this->orderCancellationService = $orderCancellationService;
        $this->quoteRepository = $quoteRepository;
    }

    /**
     * Cancels an order if an exception occurs during the order creation.
     *
     * @param CartManagementInterface $subject
     * @param \Closure $proceed
     * @param int $cartId
     * @param PaymentInterface $payment
     * @return int
     * @throws \Exception
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function aroundPlaceOrder(
        CartManagementInterface $subject,
        \Closure $proceed,
        $cartId,
        PaymentInterface $payment = null
    ) {
        try {
            return $proceed($cartId, $payment);
        } catch (\Exception $e) {
            $quote = $this->quoteRepository->get((int) $cartId);
            $payment = $quote->getPayment();
            $paymentCodes = [
                ConfigProvider::CODE,
                ConfigProvider::CC_VAULT_CODE,
                PayPalConfigProvider::PAYPAL_CODE,
                PayPalConfigProvider::PAYPAL_VAULT_CODE
            ];
            if (in_array($payment->getMethod(), $paymentCodes)) {
                $incrementId = $quote->getReservedOrderId();
                $this->orderCancellationService->execute($incrementId);
            }

            throw $e;
        }
    }
}