You are here

public function TaxRate::getPercentage in Commerce Core 8.2

Gets the percentage valid for the given date.

Parameters

\Drupal\Core\Datetime\DrupalDateTime $date: The date.

Return value

\Drupal\commerce_tax\TaxRatePercentage|null The percentage, or NULL if none found.

File

modules/tax/src/TaxRate.php, line 122

Class

TaxRate
Represents a tax rate.

Namespace

Drupal\commerce_tax

Code

public function getPercentage(DrupalDateTime $date = NULL) {

  // Default to the current date.
  $date = $date ?: new DrupalDateTime();

  // Unlike DateTime, DrupalDateTime objects can't be compared directly.
  // Convert them to timestamps, after discarding the time portion.
  $time = $date
    ->setTime(0, 0, 0)
    ->format('U');
  $timezone = $date
    ->getTimezone();
  foreach ($this->percentages as $percentage) {
    $start_date = $percentage
      ->getStartDate($timezone);
    $start_time = $start_date
      ->setTime(0, 0, 0)
      ->format('U');
    $end_date = $percentage
      ->getEndDate($timezone);
    $end_time = $end_date ? $end_date
      ->setTime(0, 0, 0)
      ->format('U') : 0;
    if ($start_time <= $time && (!$end_time || $end_time >= $time)) {
      return $percentage;
    }
  }
  return NULL;
}