UsageLimitFormatter.php in Commerce Core 8.2
File
modules/promotion/src/Plugin/Field/FieldFormatter/UsageLimitFormatter.php
View source
<?php
namespace Drupal\commerce_promotion\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UsageLimitFormatter extends FormatterBase {
protected $usage;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->usage = $container
->get('commerce_promotion.usage');
return $instance;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$field_name = $items
->getFieldDefinition()
->getName();
$entity = $items
->getEntity();
if ($field_name === 'usage_limit') {
$current_usage = $entity
->getEntityTypeId() === 'commerce_promotion' ? $this->usage
->load($entity) : $this->usage
->loadByCoupon($entity);
$usage_limit = $entity
->getUsageLimit();
$usage_limit = $usage_limit ?: $this
->t('Unlimited');
$usage = $current_usage . ' / ' . $usage_limit;
}
else {
$customer_limit = $entity
->getCustomerUsageLimit();
$usage = $customer_limit ?: $this
->t('Unlimited');
}
$elements[0] = [
'#markup' => $usage,
];
return $elements;
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
$entity_type = $field_definition
->getTargetEntityTypeId();
$field_name = $field_definition
->getName();
$applicable_entity_type = in_array($entity_type, [
'commerce_promotion',
'commerce_promotion_coupon',
]);
$applicable_field_name = in_array($field_name, [
'usage_limit',
'usage_limit_customer',
]);
return $applicable_entity_type && $applicable_field_name;
}
}