TaxRateDefaultWidget.php in Commerce Product Tax 8
File
src/Plugin/Field/FieldWidget/TaxRateDefaultWidget.php
View source
<?php
namespace Drupal\commerce_product_tax\Plugin\Field\FieldWidget;
use Drupal\commerce_price\Calculator;
use Drupal\commerce_tax\Entity\TaxType;
use Drupal\commerce_tax\Entity\TaxTypeInterface;
use Drupal\commerce_tax\Resolver\TaxRateResolverInterface;
use Drupal\commerce_tax\TaxZone;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget;
class TaxRateDefaultWidget extends OptionsSelectWidget {
protected function getOptions(FieldableEntityInterface $entity) {
if (isset($this->options)) {
return $this->options;
}
$tax_type = $this
->getFieldSetting('tax_type');
$this->options = [];
if ($empty_label = $this
->getEmptyLabel()) {
$this->options = [
'_none' => $empty_label,
];
}
$no_applicable_tax = TaxRateResolverInterface::NO_APPLICABLE_TAX_RATE;
$no_applicable_tax_label = $this
->t('No tax');
if (!$tax_type) {
return $this->options;
}
$tax_type = TaxType::load($tax_type);
$tax_type_plugin = $tax_type
->getPlugin();
foreach ($tax_type_plugin
->getZones() as $zone) {
if (!$this
->isAllowed($tax_type, $zone)) {
continue;
}
$label = (string) $zone
->getLabel();
$this->options[$label] = [
$zone
->getId() . '|' . $no_applicable_tax => $no_applicable_tax_label,
];
foreach ($zone
->getRates() as $rate) {
$rate_label = $this
->t('@label', [
'@label' => $rate
->getLabel(),
]);
if ($percentage = $rate
->getPercentage()) {
$rate_label = $this
->t('@label (@percentage%)', [
'@label' => $rate
->getLabel(),
'@percentage' => Calculator::multiply($percentage
->getNumber(), '100'),
]);
}
$this->options[$label][$zone
->getId() . '|' . $rate
->getId()] = $rate_label;
}
}
return $this->options;
}
protected function isAllowed(TaxTypeInterface $tax_type, TaxZone $zone) {
if ($tax_type
->getPluginId() == 'european_union_vat' && $zone
->getId() == 'ic') {
return FALSE;
}
$allowed_zones = $this
->getFieldSetting('allowed_zones');
if (empty($allowed_zones)) {
return TRUE;
}
return in_array($zone
->getId(), $allowed_zones);
}
}