CommerceLicenseRole.class.php in Commerce License 7
File
modules/commerce_license_role/plugins/license_type/CommerceLicenseRole.class.php
View source
<?php
class CommerceLicenseRole extends CommerceLicenseBase {
public function isConfigurable() {
return FALSE;
}
public function save() {
if ($this->uid && $this->product_id) {
$role = $this->wrapper->product->commerce_license_role
->value();
$owner = $this->wrapper->owner
->value();
$save_owner = FALSE;
if (!empty($this->license_id)) {
$this->original = entity_load_unchanged('commerce_license', $this->license_id);
if ($this->original->product_id && $this->product_id != $this->original->product_id) {
$previous_role = $this->original->wrapper->product->commerce_license_role
->value();
if (isset($owner->roles[$previous_role])) {
$this
->revokeRole($owner, $previous_role);
$save_owner = TRUE;
}
}
}
if ($this->status == COMMERCE_LICENSE_ACTIVE) {
if (!isset($owner->roles[$role])) {
$owner->roles[$role] = $role;
$save_owner = TRUE;
}
}
elseif ($this->status > COMMERCE_LICENSE_ACTIVE) {
if (isset($owner->roles[$role])) {
$this
->revokeRole($owner, $role);
$save_owner = TRUE;
}
}
if ($save_owner) {
user_save($owner);
}
}
parent::save();
}
private function revokeRole($owner, $role) {
$revoke = TRUE;
$efq = new EntityFieldQuery();
$results = $efq
->entityCondition('entity_type', 'commerce_license')
->propertyCondition('type', 'role')
->propertyCondition('uid', $owner->uid)
->propertyCondition('status', COMMERCE_LICENSE_ACTIVE)
->propertyCondition('license_id', $this->license_id, '!=')
->execute();
if (!empty($results)) {
$licenses = entity_load('commerce_license', array_keys($results['commerce_license']));
foreach ($licenses as $license) {
$license_wrapper = entity_metadata_wrapper('commerce_license', $license);
try {
$license_role = $license_wrapper->product->commerce_license_role
->value();
} catch (EntityMetadataWrapperException $ex) {
$license_role = FALSE;
}
if ($license_role == $role) {
$revoke = FALSE;
}
}
}
if ($revoke && isset($owner->roles[$role])) {
unset($owner->roles[$role]);
}
}
}