You are here

public function OrderSubscriber::onCancel in Commerce Recurring Framework 8

Cancels subscriptions when the initial order is canceled.

Parameters

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

File

src/EventSubscriber/OrderSubscriber.php, line 126

Class

OrderSubscriber

Namespace

Drupal\commerce_recurring\EventSubscriber

Code

public function onCancel(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;
  }

  /** @var \Drupal\commerce_recurring\Entity\SubscriptionInterface[] $subscriptions */
  $query = $subscription_storage
    ->getQuery();
  $query
    ->condition('initial_order', $order
    ->id())
    ->condition('state', [
    'trial',
    'active',
  ], 'IN')
    ->accessCheck(FALSE);
  $result = $query
    ->execute();

  // No subscriptions were found, stop here.
  if (!$result) {
    return;
  }
  $subscriptions = $subscription_storage
    ->loadMultiple($result);
  foreach ($subscriptions as $subscription) {
    $subscription
      ->getState()
      ->applyTransitionById('cancel');
    $subscription
      ->save();
  }
}