TaxRatePercentage.php in Commerce Core 8.2
File
modules/tax/src/TaxRatePercentage.php
View source
<?php
namespace Drupal\commerce_tax;
use Drupal\commerce_price\Calculator;
use Drupal\commerce_price\Price;
use Drupal\Core\Datetime\DrupalDateTime;
class TaxRatePercentage {
protected $number;
protected $startDate;
protected $endDate;
public function __construct(array $definition) {
foreach ([
'number',
'start_date',
] as $required_property) {
if (!isset($definition[$required_property]) || $definition[$required_property] === '') {
throw new \InvalidArgumentException(sprintf('Missing required property "%s".', $required_property));
}
}
if (is_float($definition['number'])) {
throw new \InvalidArgumentException(sprintf('The provided number "%s" must be a string, not a float.', $definition['number']));
}
if (!is_numeric($definition['number'])) {
throw new \InvalidArgumentException(sprintf('The provided number "%s" is not a numeric value.', $definition['number']));
}
$this->number = $definition['number'];
$this->startDate = $definition['start_date'];
$this->endDate = !empty($definition['end_date']) ? $definition['end_date'] : NULL;
}
public function toString() {
if ($this->endDate) {
return t('@number (@start_date - @end_date)', [
'@number' => $this->number * 100 . '%',
'@start_date' => $this
->getStartDate()
->format('M jS Y'),
'@end_date' => $this
->getEndDate()
->format('M jS Y'),
]);
}
else {
return t('@number (Since @start_date)', [
'@number' => $this->number * 100 . '%',
'@start_date' => $this
->getStartDate()
->format('M jS Y'),
]);
}
}
public function getNumber() {
return $this->number;
}
public function getStartDate($store_timezone = 'UTC') {
return new DrupalDateTime($this->startDate, $store_timezone);
}
public function getEndDate($store_timezone = 'UTC') {
if ($this->endDate) {
return new DrupalDateTime($this->endDate, $store_timezone);
}
}
public function toArray() : array {
return array_filter([
'number' => $this->number,
'start_date' => $this->startDate,
'end_date' => $this->endDate,
]);
}
public function calculateTaxAmount(Price $price, $included = FALSE) {
$tax_amount = $price
->multiply($this->number);
if ($included) {
$divisor = Calculator::add('1', $this->number);
$tax_amount = $tax_amount
->divide($divisor);
}
return $tax_amount;
}
}