You are here

public function OrderSubscriber::onPlace in Commerce Recurring Framework 8

Creates subscriptions when the initial order is placed.

Parameters

\Drupal\state_machine\Event\WorkflowTransitionEvent $event: The transition event.

File

src/EventSubscriber/OrderSubscriber.php, line 65

Class

OrderSubscriber

Namespace

Drupal\commerce_recurring\EventSubscriber

Code

public function onPlace(WorkflowTransitionEvent $event) {

  /** @var \Drupal\commerce_recurring\SubscriptionStorageInterface $subscription_storage */
  $subscription_storage = $this->entityTypeManager
    ->getStorage('commerce_subscription');

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event
    ->getEntity();
  if ($order
    ->bundle() == 'recurring') {
    return;
  }
  $payment_method = $order
    ->get('payment_method')->entity;
  $start_time = $this->time
    ->getRequestTime();
  foreach ($order
    ->getItems() as $order_item) {
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    if (!$purchased_entity || !$purchased_entity
      ->hasField('subscription_type')) {
      continue;
    }
    $subscription_type_item = $purchased_entity
      ->get('subscription_type');
    $billing_schedule_item = $purchased_entity
      ->get('billing_schedule');
    if ($subscription_type_item
      ->isEmpty() || $billing_schedule_item
      ->isEmpty()) {
      continue;
    }

    /** @var \Drupal\commerce_recurring\Entity\BillingScheduleInterface $billing_schedule */
    $billing_schedule = $billing_schedule_item->entity;

    // If the trial is not allowed and no payment method was collected, we
    // cannot proceed to the subscription creation.
    if (!$billing_schedule
      ->getPlugin()
      ->allowTrials() && empty($payment_method)) {
      continue;
    }
    $subscription = $subscription_storage
      ->createFromOrderItem($order_item, [
      'type' => $subscription_type_item->target_plugin_id,
      'billing_schedule' => $billing_schedule,
    ]);

    // Set the payment method if known, it's not required to start a free
    // trial if it wasn't collected.
    if (!empty($payment_method)) {
      $subscription
        ->setPaymentMethod($payment_method);
    }
    if ($billing_schedule
      ->getPlugin()
      ->allowTrials()) {
      $subscription
        ->setState('trial');
      $subscription
        ->setTrialStartTime($start_time);
      $subscription
        ->save();
      $this->recurringOrderManager
        ->startTrial($subscription);
    }
    else {
      $subscription
        ->setState('active');
      $subscription
        ->setStartTime($start_time);
      $subscription
        ->save();
      $this->recurringOrderManager
        ->startRecurring($subscription);
    }
  }
}