You are here

class TaxRateResolver in Commerce Product Tax 8

Returns the tax rate configured on the product variation.

Hierarchy

Expanded class hierarchy of TaxRateResolver

1 string reference to 'TaxRateResolver'
commerce_product_tax.services.yml in ./commerce_product_tax.services.yml
commerce_product_tax.services.yml
1 service uses TaxRateResolver
commerce_product_tax.tax_rate_resolver in ./commerce_product_tax.services.yml
Drupal\commerce_product_tax\Resolver\TaxRateResolver

File

src/Resolver/TaxRateResolver.php, line 16

Namespace

Drupal\commerce_product_tax\Resolver
View source
class TaxRateResolver implements TaxRateResolverInterface, TaxTypeAwareInterface {
  use TaxTypeAwareTrait;

  /**
   * {@inheritdoc}
   */
  public function resolve(TaxZone $zone, OrderItemInterface $order_item, ProfileInterface $customer_profile) {
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    if (!$purchased_entity) {
      return NULL;
    }
    $tax_field_names = $this
      ->getTaxFieldNames($purchased_entity);
    foreach ($tax_field_names as $field_name) {
      $field_items = $purchased_entity
        ->get($field_name);
      if ($field_items
        ->isEmpty()) {
        continue;
      }
      $tax_type = $field_items
        ->getFieldDefinition()
        ->getSetting('tax_type');
      if ($tax_type != $this->taxType
        ->id()) {
        continue;
      }
      foreach ($field_items as $tax_rate) {
        list($zone_id, $rate_id) = explode('|', $tax_rate->value);
        if ($zone
          ->getId() != $zone_id) {
          continue;
        }
        if ($rate_id === static::NO_APPLICABLE_TAX_RATE) {
          return static::NO_APPLICABLE_TAX_RATE;
        }
        foreach ($zone
          ->getRates() as $rate) {
          if ($rate
            ->getId() == $rate_id) {
            return $rate;
          }
        }
      }
    }
  }

  /**
   * Gets the tax field names attached to the purchasable entity.
   *
   * @param \Drupal\commerce\PurchasableEntityInterface $entity
   *   The purchasable entity.
   *
   * @return array
   *   An array of tax field names.
   */
  protected function getTaxFieldNames(PurchasableEntityInterface $entity) {
    $field_names = [];
    foreach ($entity
      ->getFieldDefinitions() as $field) {
      if ($field
        ->getType() == 'commerce_tax_rate') {
        $field_names[] = $field
          ->getName();
      }
    }
    return $field_names;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
TaxRateResolver::getTaxFieldNames protected function Gets the tax field names attached to the purchasable entity.
TaxRateResolver::resolve public function Resolves the tax rate for the given tax zone. Overrides TaxRateResolverInterface::resolve
TaxRateResolverInterface::NO_APPLICABLE_TAX_RATE constant
TaxTypeAwareTrait::$taxType protected property The tax type.
TaxTypeAwareTrait::setTaxType public function