You are here

public function OrderSubscriber::onPlace in Commerce License 8.2

Reacts to an order being placed.

Creates the licenses for licensable order items, and optionally activate them if configured to do so at the product variation type level.

Parameters

\Drupal\state_machine\Event\WorkflowTransitionEvent $event: The event we subscribed to.

File

src/EventSubscriber/OrderSubscriber.php, line 83

Class

OrderSubscriber
Changes a license's state in sync with an order's workflow.

Namespace

Drupal\commerce_license\EventSubscriber

Code

public function onPlace(WorkflowTransitionEvent $event) {

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $event
    ->getEntity();
  $licensable_order_items = $this
    ->getLicensableOrderItems($order);
  $product_variation_type_storage = $this->entityTypeManager
    ->getStorage('commerce_product_variation_type');
  foreach ($licensable_order_items as $order_item) {
    $license = $order_item
      ->get('license')->entity;

    // We don't need to do anything if there is already an active license
    // referenced by this order item.
    if ($license && $license
      ->getState()
      ->getId() === 'active') {
      continue;
    }
    if (!$license) {
      $license = $this
        ->createLicenseFromOrderItem($order_item);
    }
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    $product_variation_type = $product_variation_type_storage
      ->load($purchased_entity
      ->bundle());
    $activate_on_place = $product_variation_type
      ->getThirdPartySetting('commerce_license', 'activate_on_place');

    // License activation shouldn't happen when the order is placed, skip
    // to the next order item.
    if (!$activate_on_place) {
      continue;
    }
    $license
      ->set('state', 'active');
    $license
      ->save();
  }
}