LicenseSubscription.php in Commerce License 8.2
File
src/Plugin/Commerce/SubscriptionType/LicenseSubscription.php
View source
<?php
namespace Drupal\commerce_license\Plugin\Commerce\SubscriptionType;
use Drupal\entity\BundleFieldDefinition;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_recurring\Entity\SubscriptionInterface;
use Drupal\commerce_recurring\Plugin\Commerce\SubscriptionType\SubscriptionTypeBase;
class LicenseSubscription extends SubscriptionTypeBase {
public function onSubscriptionCreate(SubscriptionInterface $subscription, OrderItemInterface $order_item) {
$purchased_entity = $subscription
->getPurchasedEntity();
$uid = $subscription
->getCustomerId();
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()));
}
if (empty($order_item->license->entity)) {
throw new \Exception(sprintf("Attempt to create a license subscription with order item ID %s that doesn't have a license.", $order_item
->id()));
}
$license = $order_item->license->entity;
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()));
}
$subscription->license = $license;
}
public function onSubscriptionActivate(SubscriptionInterface $subscription, OrderInterface $order) {
}
public function onSubscriptionRenew(SubscriptionInterface $subscription, OrderInterface $order, OrderInterface $next_order) {
$license = $subscription->license->entity;
$license
->setRenewedTime($subscription
->getRenewedTime());
$license
->save();
}
public function onSubscriptionExpire(SubscriptionInterface $subscription) {
$license = $subscription->license->entity;
$transition = $license
->getState()
->getWorkflow()
->getTransition('expire');
$license
->getState()
->applyTransition($transition);
$license
->save();
}
public function onSubscriptionCancel(SubscriptionInterface $subscription) {
$license = $subscription->license->entity;
$transition = $license
->getState()
->getWorkflow()
->getTransition('cancel');
$license
->getState()
->applyTransition($transition);
$license
->save();
}
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
$fields['license'] = BundleFieldDefinition::create('entity_reference')
->setLabel(t('License'))
->setDescription(t('The license this subscription controls.'))
->setCardinality(1)
->setRequired(TRUE)
->setSetting('target_type', 'commerce_license');
return $fields;
}
}