TaxZone.php in Commerce Core 8.2
File
modules/tax/src/TaxZone.php
View source
<?php
namespace Drupal\commerce_tax;
use CommerceGuys\Addressing\AddressInterface;
use CommerceGuys\Addressing\Zone\ZoneTerritory;
class TaxZone {
protected $id;
protected $label;
protected $displayLabel;
protected $territories;
protected $rates;
public function __construct(array $definition) {
foreach ([
'id',
'label',
'display_label',
'territories',
'rates',
] as $required_property) {
if (empty($definition[$required_property])) {
throw new \InvalidArgumentException(sprintf('Missing required property "%s".', $required_property));
}
}
foreach ([
'territories',
'rates',
] as $property) {
if (!is_array($definition[$property])) {
throw new \InvalidArgumentException(sprintf('The property "%s" must be an array.', $property));
}
}
$this->id = $definition['id'];
$this->label = $definition['label'];
$this->displayLabel = $definition['display_label'];
foreach ($definition['territories'] as $territory_definition) {
$this->territories[] = new ZoneTerritory($territory_definition);
}
foreach ($definition['rates'] as $rate_definition) {
$tax_rate = new TaxRate($rate_definition);
$this->rates[$tax_rate
->getId()] = $tax_rate;
}
}
public function getId() {
return $this->id;
}
public function getLabel() {
return $this->label;
}
public function getDisplayLabel() {
return $this->displayLabel;
}
public function getTerritories() {
return $this->territories;
}
public function getRates() {
return $this->rates;
}
public function toArray() : array {
return [
'id' => $this->id,
'label' => $this->label,
'display_label' => $this->displayLabel,
'territories' => array_map(function (ZoneTerritory $territory) {
return array_filter([
'country_code' => $territory
->getCountryCode(),
'administrative_area' => $territory
->getAdministrativeArea(),
'locality' => $territory
->getLocality(),
'dependent_locality' => $territory
->getDependentLocality(),
'included_postal_codes' => $territory
->getIncludedPostalCodes(),
'excluded_postal_codes' => $territory
->getExcludedPostalCodes(),
]);
}, $this->territories),
'rates' => array_map(function (TaxRate $rate) {
return $rate
->toArray();
}, array_values($this->rates)),
];
}
public function getRate($rate_id) {
return isset($this->rates[$rate_id]) ? $this->rates[$rate_id] : NULL;
}
public function getDefaultRate() {
$default_rate = reset($this->rates);
foreach ($this->rates as $rate) {
if ($rate
->isDefault()) {
$default_rate = $rate;
break;
}
}
return $default_rate;
}
public function match(AddressInterface $address) {
foreach ($this->territories as $territory) {
if ($territory
->match($address)) {
return TRUE;
}
}
return FALSE;
}
}