You are here

public function RecurringOrderManager::startRecurring in Commerce Recurring Framework 8

Starts the recurring process for the given subscription.

Creates a recurring order covering the first billing period. The order will be closed and renewed once the billing period is over.

Parameters

\Drupal\commerce_recurring\Entity\SubscriptionInterface $subscription: The active subscription.

Return value

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

Throws

\InvalidArgumentException Thrown if subscription state is not "active".

Overrides RecurringOrderManagerInterface::startRecurring

File

src/RecurringOrderManager.php, line 76

Class

RecurringOrderManager
Provides the default recurring order manager.

Namespace

Drupal\commerce_recurring

Code

public function startRecurring(SubscriptionInterface $subscription) {
  $state = $subscription
    ->getState()
    ->getId();
  if ($state != 'active') {
    throw new \InvalidArgumentException(sprintf('Unexpected subscription state "%s".', $state));
  }
  $start_date = $subscription
    ->getStartDate();
  $billing_schedule = $subscription
    ->getBillingSchedule();
  $billing_period = $billing_schedule
    ->getPlugin()
    ->generateFirstBillingPeriod($start_date);
  $subscription
    ->setNextRenewalTime($billing_period
    ->getEndDate()
    ->getTimestamp());
  $order = $this
    ->createOrder($subscription, $billing_period);
  $this
    ->applyCharges($order, $subscription, $billing_period);

  // Allow the type to modify the subscription and order before they're saved.
  $subscription
    ->getType()
    ->onSubscriptionActivate($subscription, $order);
  $order
    ->save();
  $subscription
    ->addOrder($order);
  $subscription
    ->save();
  return $order;
}