Last active
September 2, 2017 19:58
-
-
Save clrockwell/9c8d585b58d8110adba7dafd6e715eb0 to your computer and use it in GitHub Desktop.
A service for creating licenses programmatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\free_trial; | |
use Drupal\Core\Entity\EntityTypeManager; | |
use Drupal\user\RoleInterface; | |
/** | |
* Class CreateLicense. | |
*/ | |
class CreateLicense implements CreateLicenseInterface { | |
/** | |
* Drupal\Core\Entity\EntityTypeManager definition. | |
* | |
* @var \Drupal\Core\Entity\EntityTypeManager | |
*/ | |
protected $entityTypeManager; | |
/** | |
* @var \Drupal\Core\Entity\EntityStorageInterface|mixed|object | |
*/ | |
protected $licenseStorage; | |
/** | |
* Constructs a new CreateLicense object. | |
*/ | |
public function __construct(EntityTypeManager $entity_type_manager) { | |
$this->entityTypeManager = $entity_type_manager; | |
$this->licenseStorage = $this->entityTypeManager->getStorage('commerce_license'); | |
} | |
/** | |
* Usage: | |
* \Drupal::service('free_trial.create_license')->addLicense( | |
* 'role', | |
* 1, | |
* [ | |
* 'target_plugin_id' => 'interval', | |
* 'target_plugin_configuration' => [ | |
* 'interval' => [ | |
* 'interval' => '7', | |
* 'period' => 'day' | |
* ] | |
* ] | |
* ], | |
* 'new', | |
* TRUE); | |
* | |
* @param $type | |
* The CommerceLicenseType type, e.g. 'role' or 'file' | |
* @param $uid | |
* The user to whom the license should be granted | |
* @param $expiration_type | |
* A plugin configuration for a CommerceLicenseExpiration | |
* @param $role | |
* If 'role', provide a Drupal\user\RoleInterface | |
* @param string $state | |
* The state the license should be in, see commerce_license.workflows.yml | |
* @param bool $activate | |
* Whether or not the license should be immediately activated. | |
* @return \Drupal\Core\Entity\EntityInterface | |
* a License entity | |
*/ | |
public function addLicense($type, $uid, array $expiration_type, RoleInterface $role = null, $state = 'new', $activate = TRUE) { | |
$license = $this->licenseStorage->create([ | |
'type' => $type, | |
'state' => $state, | |
'uid' => $uid, | |
'expiration_type' => $expiration_type, | |
'license_role'=> $role, | |
]); | |
$license->save(); | |
if ($activate) { | |
$transition = $license->getState()->getWorkflow()->getTransition('confirm'); | |
$license->getState()->applyTransition($transition); | |
$license->save(); | |
} | |
return $license; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment