You are here

public function RecurringOrderManager::startTrial in Commerce Recurring Framework 8

Starts the trial for the given subscription.

Creates a recurring order covering the trial period. The order will be closed once the trial period is over.

Since there can only be a single trial period, the trial order is one-off, never renewed. A new recurring order is created by startRecurring() once the subscription is activated.

Parameters

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

Return value

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

Throws

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

Overrides RecurringOrderManagerInterface::startTrial

File

src/RecurringOrderManager.php, line 48

Class

RecurringOrderManager
Provides the default recurring order manager.

Namespace

Drupal\commerce_recurring

Code

public function startTrial(SubscriptionInterface $subscription) {
  $state = $subscription
    ->getState()
    ->getId();
  if ($state != 'trial') {
    throw new \InvalidArgumentException(sprintf('Unexpected subscription state "%s".', $state));
  }
  $billing_schedule = $subscription
    ->getBillingSchedule();
  if (!$billing_schedule
    ->getPlugin()
    ->allowTrials()) {
    throw new \InvalidArgumentException(sprintf('The billing schedule "%s" does not allow trials.', $billing_schedule
      ->id()));
  }
  $start_date = $subscription
    ->getTrialStartDate();
  $end_date = $subscription
    ->getTrialEndDate();
  $trial_period = new BillingPeriod($start_date, $end_date);
  $order = $this
    ->createOrder($subscription, $trial_period);
  $this
    ->applyCharges($order, $subscription, $trial_period);

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