You are here

public function RecurringOrderManager::closeOrder in Commerce Recurring Framework 8

Closes the given recurring order.

A payment will be created and the order will be placed.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: The recurring order.

Throws

\Drupal\commerce_payment\Exception\HardDeclineException Thrown when no payment method was found.

\Drupal\commerce_payment\Exception\PaymentGatewayException Thrown when the transaction fails for any reason. This includes child exceptions such as HardDeclineException and SoftDeclineException.

Overrides RecurringOrderManagerInterface::closeOrder

File

src/RecurringOrderManager.php, line 132

Class

RecurringOrderManager
Provides the default recurring order manager.

Namespace

Drupal\commerce_recurring

Code

public function closeOrder(OrderInterface $order) {
  $order_state = $order
    ->getState()
    ->getId();
  if ($order
    ->isPaid()) {
    if (in_array('mark_paid', array_keys($order
      ->getState()
      ->getTransitions()))) {
      $order
        ->getState()
        ->applyTransitionById('mark_paid');
      $order
        ->save();
    }
  }
  if (in_array($order_state, [
    'canceled',
    'completed',
  ]) || $order
    ->isPaid()) {
    return;
  }
  if ($order_state == 'draft') {
    $order
      ->getState()
      ->applyTransitionById('place');
    $order
      ->save();
  }
  $subscriptions = $this
    ->collectSubscriptions($order);
  $payment_method = $this
    ->selectPaymentMethod($subscriptions);
  if (!$payment_method) {
    throw new HardDeclineException('Payment method not found.');
  }
  $payment_gateway = $payment_method
    ->getPaymentGateway();
  if (!$payment_gateway) {
    throw new HardDeclineException('Payment gateway not found');
  }

  /** @var \Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\OnsitePaymentGatewayInterface $payment_gateway_plugin */
  $payment_gateway_plugin = $payment_gateway
    ->getPlugin();
  if (!$order
    ->isPaid()) {
    $payment_storage = $this->entityTypeManager
      ->getStorage('commerce_payment');

    /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
    $payment = $payment_storage
      ->create([
      'payment_gateway' => $payment_gateway
        ->id(),
      'payment_method' => $payment_method
        ->id(),
      'order_id' => $order
        ->id(),
      'amount' => $order
        ->getTotalPrice(),
      'state' => 'new',
    ]);

    // The createPayment() call might throw a decline exception, which is
    // supposed to be handled by the caller, to allow for dunning.
    $payment_gateway_plugin
      ->createPayment($payment);
    $order
      ->getState()
      ->applyTransitionById('mark_paid');
    $order
      ->save();
  }
}