diff --git a/README.md b/README.md index 79bcf60..da50f7b 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ $vatCalculator->isValidVatNumber('NL123456789B01'); - [Validate EU VAT numbers](#validate-eu-vat-numbers) - [Get EU VAT number details](#vat-number-details) - [Get the IP based country of your user](#get-ip-based-country) + - [Get all known rates for a country](#all-known-rates) - [Countries](#countries) - [License](#license) - [Contributing](#contributing) @@ -149,6 +150,18 @@ try { } ``` + +### Get all known rates for a country + +Get all known rates (current, high & low, historical & future, exceptions) for a country by: + +```php +$vatRates = new VatRates(); +$vatRates->getAllKnownRates('DE'); +``` + +The returned array of rates is unsorted. This method can be useful when you want to prefill a selectbox with known VAT rates for a country for example, or when you want to validate user-provided rates. + ## Countries diff --git a/src/VatRates.php b/src/VatRates.php index d45311f..dad54a2 100644 --- a/src/VatRates.php +++ b/src/VatRates.php @@ -452,4 +452,49 @@ private function getRules(string $countryCode, ?DateTimeInterface $date = null): return $this->taxRules[$countryCode]; } + + /** + * Get an array of all known VAT rates for given country. + * + * Returns current rate, high & low rates, historical & future rates, exceptions, unsorted. + * + * @param string $country + * @return array + */ + public function getAllKnownRates(string $country): array + { + if (!isset($this->taxRules[$country])) { + return []; + } + + $rates = $this->getRates($this->taxRules[$country]); + if (isset($this->taxRules[$country]['since'])) { + foreach ($this->taxRules[$country]['since'] as $sinceRules) { + $rates = array_merge($rates, $this->getRates($sinceRules)); + } + } + return array_values(array_unique($rates)); + } + + + /** + * @param array{rate: float, rates?: array, exceptions?: array} $taxRules + * @return array + */ + private function getRates(array $taxRules): array + { + $rates = [$taxRules['rate']]; + if (isset($taxRules['rates'])) { + foreach ($taxRules['rates'] as $rate) { + $rates[] = $rate; + } + } + if (isset($taxRules['exceptions'])) { + foreach ($taxRules['exceptions'] as $rate) { + $rates[] = $rate; + } + } + return $rates; + } + } diff --git a/tests/VatRatesTest.php b/tests/VatRatesTest.php index 9c5ac3e..954395e 100644 --- a/tests/VatRatesTest.php +++ b/tests/VatRatesTest.php @@ -66,4 +66,13 @@ public function testGetRatesSince(): void $this->assertEquals(0.19, $this->vatRates->getTaxRateForLocation('DE', null, VatRates::GENERAL, new DateTimeImmutable($date))); } + + public function testGetAllKnownRates(): void + { + $this->assertEquals([0.20, 0.19], $this->vatRates->getAllKnownRates('AT')); + $this->assertEquals([0.21], $this->vatRates->getAllKnownRates('CZ')); + $this->assertEquals([0.19, 0, 0.16], $this->vatRates->getAllKnownRates('DE')); + $this->assertEquals([0.21, 0.09], $this->vatRates->getAllKnownRates('NL')); + } + }