You are here

public function RecurringOrderManager::renewOrder in Commerce Recurring Framework 8

Renews the given recurring order.

Parameters

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

Return value

\Drupal\commerce_order\Entity\OrderInterface|null The next recurring order, or NULL if none remain.

Overrides RecurringOrderManagerInterface::renewOrder

File

src/RecurringOrderManager.php, line 183

Class

RecurringOrderManager
Provides the default recurring order manager.

Namespace

Drupal\commerce_recurring

Code

public function renewOrder(OrderInterface $order) {
  $subscriptions = $this
    ->collectSubscriptions($order);

  /** @var \Drupal\commerce_recurring\Entity\SubscriptionInterface $subscription */
  $subscription = reset($subscriptions);
  if (!$subscription || $subscription
    ->getState()
    ->getId() != 'active') {

    // The subscription was deleted or deactivated.
    return NULL;
  }
  $billing_schedule = $subscription
    ->getBillingSchedule();
  $start_date = $subscription
    ->getStartDate();

  /** @var \Drupal\commerce_recurring\Plugin\Field\FieldType\BillingPeriodItem $billing_period_item */
  $billing_period_item = $order
    ->get('billing_period')
    ->first();
  $current_billing_period = $billing_period_item
    ->toBillingPeriod();
  $next_billing_period = $billing_schedule
    ->getPlugin()
    ->generateNextBillingPeriod($start_date, $current_billing_period);
  $next_order = $this
    ->createOrder($subscription, $next_billing_period);
  $this
    ->applyCharges($next_order, $subscription, $next_billing_period);

  // Allow the subscription type to modify the order before it is saved.
  $subscription
    ->getType()
    ->onSubscriptionRenew($subscription, $order, $next_order);
  $next_order
    ->save();

  // Update the subscription with the new order and renewal timestamp.
  $subscription
    ->addOrder($next_order);
  $subscription
    ->setRenewedTime($this->time
    ->getCurrentTime());
  $subscription
    ->setNextRenewalTime($next_billing_period
    ->getEndDate()
    ->getTimestamp());
  $subscription
    ->save();
  return $next_order;
}