public function LicenseAvailabilityCheckerExistingRights::check in Commerce License 8.2
Checks the availability of the given order item.
Parameters
\Drupal\commerce_order\Entity\OrderItemInterface $order_item: The order item.
\Drupal\commerce\Context $context: The context.
Return value
\Drupal\commerce_order\AvailabilityResult The availability result. AvailabilityResult::unavailable() should be used to indicate that the given order item is "unavailable" for purchase. Note that an optional "reason" can be specified.
Overrides AvailabilityCheckerInterface::check
File
- src/
LicenseAvailabilityCheckerExistingRights.php, line 91
Class
- LicenseAvailabilityCheckerExistingRights
- Prevents purchase of a license that grants rights the user already has.
Namespace
Drupal\commerce_licenseCode
public function check(OrderItemInterface $order_item, Context $context) {
// Hand over to the license type plugin configured in the product variation,
// to let it determine whether the user already has what the license would
// grant.
$customer = $context
->getCustomer();
$purchased_entity = $order_item
->getPurchasedEntity();
$license_type_plugin = $purchased_entity->license_type
->first()
->getTargetInstance();
// Load the full user entity for the plugin.
$user = $this->entityTypeManager
->getStorage('user')
->load($customer
->id());
$existing_rights_result = $license_type_plugin
->checkUserHasExistingRights($user);
if (!$existing_rights_result
->hasExistingRights()) {
return AvailabilityResult::neutral();
}
// Show a message that includes the reason from the rights check.
if ($user
->id() == $this->currentUser
->id()) {
$rights_check_message = $existing_rights_result
->getOwnerUserMessage();
}
else {
$rights_check_message = $existing_rights_result
->getOtherUserMessage();
}
$message = $rights_check_message . ' ' . t("You may not purchase the @product-label product.", [
'@product-label' => $purchased_entity
->label(),
]);
return AvailabilityResult::unavailable($message);
}