You are here

public function LicenseSubscription::onSubscriptionCreate in Commerce License 8.2

Acts on a subscription after it has been created from an order item.

Called before the subscription is saved.

Parameters

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

\Drupal\commerce_order\Entity\OrderItemInterface $order_item: The order item.

Overrides SubscriptionTypeBase::onSubscriptionCreate

File

src/Plugin/Commerce/SubscriptionType/LicenseSubscription.php, line 25

Class

LicenseSubscription
Provides a Commerce Recurring subscription type for use with licenses.

Namespace

Drupal\commerce_license\Plugin\Commerce\SubscriptionType

Code

public function onSubscriptionCreate(SubscriptionInterface $subscription, OrderItemInterface $order_item) {
  $purchased_entity = $subscription
    ->getPurchasedEntity();
  $uid = $subscription
    ->getCustomerId();

  // Ensure that the order item being used has the license trait, otherwise
  // the license won't get handled properly.
  if (!$order_item
    ->hasField('license')) {
    throw new \Exception(sprintf("Order item type %s used for product variation %s is missing the license field.", $order_item
      ->bundle(), $purchased_entity
      ->id()));
  }

  // The order item should already have a license set, as our
  // \Drupal\commerce_license\EventSubscriber\OrderSubscriber's
  // commerce_order.place.pre_transition listener
  // should run before Commerce Recurring's
  // \Drupal\commerce_recurring\EventSubscriber\EventSubscriber listener,
  // which is what then creates the subscription.
  if (empty($order_item->license->entity)) {

    // Something's gone wrong: either other code has changed priorities, or
    // the modules' relative priorities have become out of sync due to changes
    // in code.
    throw new \Exception(sprintf("Attempt to create a license subscription with order item ID %s that doesn't have a license.", $order_item
      ->id()));
  }

  // Get the license the order item refers to.
  $license = $order_item->license->entity;

  // Ensure that the license expiry is unlimited.
  if ($license->expiration_type->target_plugin_id != 'unlimited') {
    throw new \Exception(sprintf("Invalid expiry type %s on product variation %s", $license->expiration_type->target_plugin_id, $purchased_entity
      ->id()));
  }

  // Set the license on the subscription, but don't save the subscription, as
  // it's currently only being created by the storage handler.
  $subscription->license = $license;
}