├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── .gitlab-ci.yml
├── .gitlab
└── CODEOWNERS
├── .php-cs-fixer.dist.php
├── LICENSE
├── README.md
├── composer.json
├── phpstan.neon.dist
├── phpunit.xml
├── src
├── Countries
│ ├── Iso2.php
│ └── ResolvesCountries.php
├── Exceptions
│ ├── VatFetchFailedException.php
│ └── VatNumberValidateFailedException.php
├── Vat.php
├── VatNumbers
│ ├── ValidatesVatNumbers.php
│ └── ViesClient.php
└── VatRates
│ ├── ResolvesVatRates.php
│ └── TaxesEuropeDatabaseClient.php
└── tests
├── Countries
└── ValidateCountriesTest.php
├── IntegrationTest.php
├── VatNumbers
├── VatClientTest.php
└── numbers_snapshot.php
├── VatRates
├── TedbClientTest.php
├── gr_rates_snapshot.php
└── nl_rates_snapshot.php
└── VatServiceTest.php
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: ${{ matrix.operating-system }}
13 | strategy:
14 | matrix:
15 | operating-system: [ubuntu-latest]
16 | php-versions: ['8.1']
17 |
18 | name: PHP ${{ matrix.php-versions }} Test on ${{ matrix.operating-system }}
19 | steps:
20 | - uses: actions/checkout@v2
21 |
22 | - name: Setup PHP
23 | uses: shivammathur/setup-php@v2
24 | with:
25 | php-version: ${{ matrix.php-versions }}
26 | extensions: mbstring, intl
27 | ini-values: post_max_size=256M, short_open_tag=On
28 | coverage: xdebug
29 | tools: php-cs-fixer, phpunit
30 |
31 | - name: Validate composer.json and composer.lock
32 | run: composer validate --strict
33 |
34 | - name: Install dependencies
35 | run: composer install --prefer-dist --no-progress --no-suggest
36 |
37 | - name: Check codestyle
38 | run: vendor/bin/php-cs-fixer fix --dry-run --show-progress=none -vvv
39 |
40 | - name: Run static analysis
41 | run: vendor/bin/phpstan analyze
42 |
43 | - name: Run test suite
44 | run: vendor/bin/phpunit
45 |
46 | - name: Upload code coverage
47 | env:
48 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
49 | run: bash <(curl -s https://codecov.io/bash)
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.phpunit.cache/
2 | /vendor/
3 | /.idea/
4 | composer.lock
5 | .php-cs-fixer.cache
6 | clover.xml
7 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | #
2 | # DO NOT EDIT THIS FILE
3 | # Changes to the CI configuration must be submitted to the sandwave/infra repo.
4 | #
5 |
6 | include:
7 | - project: sandwave/infra
8 | ref: $INFRA_PIPELINE_REF
9 | file: .gitlab/ci/vat-php.gitlab-ci.yml
10 |
--------------------------------------------------------------------------------
/.gitlab/CODEOWNERS:
--------------------------------------------------------------------------------
1 | CODEOWNERS @sandwave/team-infra @sandwave/circle-architecture
2 | /.gitlab/ @sandwave/team-infra
3 | *.gitlab-ci.yml @sandwave/team-infra
4 |
--------------------------------------------------------------------------------
/.php-cs-fixer.dist.php:
--------------------------------------------------------------------------------
1 | true,
5 | ]);
6 | $config->getFinder()
7 | ->in(__DIR__ . "/src")
8 | ->in(__DIR__ . "/tests");
9 |
10 | return $config;
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Sandwave Software
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://sandwave.io)
2 |
3 | # European VAT utility for PHP
4 |
5 | [](https://codecov.io/gh/sandwave-io/vat-php)
6 | [](https://packagist.org/packages/sandwave-io/vat)
7 | [](https://packagist.org/packages/sandwave-io/vat)
8 | [](https://packagist.org/packages/sandwave-io/vat)
9 | [](https://packagist.org/packages/sandwave-io/vat)
10 |
11 | ## Usage
12 |
13 | ```shell
14 | composer require sandwave-io/vat
15 | ```
16 |
17 | ```php
18 | $vatService = new \SandwaveIo\Vat\Vat;
19 |
20 | $vatService->validateEuropeanVatNumber("YOURVATNUMBERHERE", "COUNTRYCODE"); // true
21 |
22 | $vatService->countryInEurope('NL'); // true
23 |
24 | $vatService->europeanVatRate("YOURVATNUMBERHERE"); // 0.0
25 | ```
26 |
27 | ### Caching
28 |
29 | If you resolve VAT rates for a country quite often, it can be a little slow. If you want to, you can cache the results
30 | by passing a `Psr\SimpleCache\CacheInterface` to the `Vat()` service. The implementation might differ based on your
31 | application, but all major frameworks implement this interface on their cache.
32 |
33 | ```php
34 | /** @var Psr\SimpleCache\CacheInterface $cache */
35 |
36 | $vatService = new \SandwaveIo\Vat\Vat(cache: $cache);
37 | ```
38 |
39 |
40 | ## External documentation
41 |
42 | * [VIES API](https://ec.europa.eu/taxation_customs/vies/technicalInformation.html)
43 | * [TEDB- "Taxes in Europe" database](https://ec.europa.eu/taxation_customs/economic-analysis-taxation/taxes-europe-database-tedb_en)
44 |
45 | ## How to contribute
46 |
47 | Feel free to create a PR if you have any ideas for improvements. Or create an issue.
48 |
49 | * When adding code, make sure to add tests for it (phpunit).
50 | * Make sure the code adheres to our coding standards (use php-cs-fixer to check/fix).
51 | * Also make sure PHPStan does not find any bugs.
52 |
53 | ```bash
54 | vendor/bin/php-cs-fixer fix
55 |
56 | vendor/bin/phpstan analyze
57 |
58 | vendor/bin/phpunit --coverage-text
59 | ```
60 |
61 | These tools will also run in GitHub actions on PR's and pushes on master.
62 |
63 | ### About the testsuite
64 |
65 | There is also an integration test, in order to skip this (heavy) test, run:
66 | ```bash
67 | vendor/bin/phpunit --exclude=large
68 | ```
69 |
70 | We generate coverage in PHPUnit. On the CI we use XDebug to do that. If you have XDebug installed, you can run:
71 | ```bash
72 | vendor/bin/phpunit --coverage-text
73 |
74 | # or generate an interactive report.
75 | vendor/bin/phpunit --coverage-html=coverage_report
76 | ```
77 |
78 | Alternatively, you can use _PHPDBG_ as coverage driver:
79 | ```bash
80 | phpdbg -qrr vendor/bin/phpunit --coverage-text
81 | ```
82 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sandwave-io/vat",
3 | "description": "European VAT rates and number validation.",
4 | "type": "library",
5 | "license": "MIT",
6 | "authors": [
7 | {
8 | "name": "Jesse Kramer",
9 | "email": "jesse@kramerventures.nl"
10 | },
11 | {
12 | "name": "Armando van Oeffelen",
13 | "email": "armando@sandwave.io"
14 | },
15 | {
16 | "name": "Daan Barbiers",
17 | "email": "daan@sandwave.io"
18 | },
19 | {
20 | "name": "Thomas Ploegaert",
21 | "email": "thomas@sandwave.io"
22 | }
23 | ],
24 | "require": {
25 | "php": "^8.1",
26 | "ext-soap": "*",
27 | "divineomega/php-countries": "^2.3",
28 | "psr/simple-cache": "^1.0"
29 | },
30 | "require-dev": {
31 | "phpunit/phpunit": "^10.0.15",
32 | "phpstan/phpstan": "^1.10.6",
33 | "friendsofphp/php-cs-fixer": "^3.14.4",
34 | "phpstan/phpstan-strict-rules": "^1.5.0",
35 | "phpstan/phpstan-deprecation-rules": "^1.1.2",
36 | "phpstan/phpstan-phpunit": "^1.3.10",
37 | "ergebnis/phpstan-rules": "^1.0.0",
38 | "sandwave-io/php-cs-fixer-config": "^1.0.0"
39 | },
40 | "autoload": {
41 | "psr-4": {
42 | "SandwaveIo\\Vat\\": "./src"
43 | }
44 | },
45 | "autoload-dev": {
46 | "psr-4": {
47 | "SandwaveIo\\Vat\\Tests\\": "tests/"
48 | }
49 | },
50 | "scripts": {
51 | "test": [
52 | "Composer\\Config::disableProcessTimeout",
53 | "@test:types",
54 | "@lint",
55 | "@test:unit"
56 | ],
57 | "test:unit": [
58 | "vendor/bin/phpunit --coverage-text"
59 | ],
60 | "test:types": [
61 | "vendor/bin/phpstan analyze"
62 | ],
63 | "lint": [
64 | "vendor/bin/php-cs-fixer fix --dry-run --diff --show-progress=none -vvv"
65 | ],
66 | "lint:fix": [
67 | "vendor/bin/php-cs-fixer fix"
68 | ]
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/phpstan.neon.dist:
--------------------------------------------------------------------------------
1 | includes:
2 | - vendor/phpstan/phpstan-strict-rules/rules.neon
3 | - vendor/phpstan/phpstan-deprecation-rules/rules.neon
4 | - vendor/phpstan/phpstan-phpunit/extension.neon
5 | - vendor/ergebnis/phpstan-rules/rules.neon
6 | parameters:
7 | checkGenericClassInNonGenericObjectType: true
8 | checkMissingIterableValueType: true
9 | ergebnis:
10 | classesAllowedToBeExtended:
11 | - PHPUnit\Framework\TestCase
12 | - RuntimeException
13 | level: 8
14 | paths:
15 | - src
16 | - tests
17 | ignoreErrors:
18 | - '#Method [A-Za-z\\]+::[a-zA-Z0-9\\_]+\(\) has parameter [\$A-Za-z]+ (with a nullable type declaration|with null as default value).#'
19 | - '#Method [A-Za-z\\]+::[a-zA-Z0-9\\_]+\(\) has a nullable return type declaration.#'
20 | - '#Constructor in [A-Za-z\\]+ has parameter [\$A-Za-z]+ with default value.#'
21 | - '#Language construct isset\(\) should not be used.#'
22 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | src
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/Countries/Iso2.php:
--------------------------------------------------------------------------------
1 | getByIsoCode($countryCode);
21 |
22 | return isset($country);
23 | }
24 |
25 | public function isCountryInEu(string $countryCode): bool
26 | {
27 | $country = self::$countries->getByIsoCode($countryCode);
28 |
29 | return $country && $country->region == self::$europe;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Countries/ResolvesCountries.php:
--------------------------------------------------------------------------------
1 | > */
11 | public array $payload;
12 |
13 | /**
14 | * VatFetchFailedException constructor.
15 | *
16 | * @param array> $payload
17 | */
18 | public function __construct(string $message = '', array $payload = [], int $code = 0, ?Throwable $previous = null)
19 | {
20 | parent::__construct($message, $code, $previous);
21 | $this->payload = $payload;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Exceptions/VatNumberValidateFailedException.php:
--------------------------------------------------------------------------------
1 | > */
11 | public array $payload;
12 |
13 | /**
14 | * VatNumberValidateFailedException constructor.
15 | *
16 | * @param array> $payload
17 | */
18 | public function __construct(string $message = '', array $payload = [], int $code = 0, ?Throwable $previous = null)
19 | {
20 | parent::__construct($message, $code, $previous);
21 | $this->payload = $payload;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Vat.php:
--------------------------------------------------------------------------------
1 | countryResolver = $countryResolver ?? new Iso2();
29 | $this->vatRateResolver = $vatRateResolver ?? new TaxesEuropeDatabaseClient();
30 | $this->vatNumberVerifier = $vatNumberVerifier ?? new ViesClient();
31 | if ($cache !== null) {
32 | $this->vatRateResolver->setCache($cache);
33 | }
34 | }
35 |
36 | public function validateEuropeanVatNumber(string $vatNumber, string $countryCode): bool
37 | {
38 | // The VIES service is EU only. Non-EU VAT numbers are not checked and assumed invalid.
39 | if (! $this->countryInEurope($countryCode)) {
40 | return false;
41 | }
42 |
43 | // Most people include the Country Code as the first letters of the VAT number. VIES doesn't support this.
44 | if (str_starts_with($vatNumber, $countryCode)) {
45 | $vatNumber = substr($vatNumber, strlen($countryCode));
46 | }
47 |
48 | return $this->vatNumberVerifier->verifyVatNumber($vatNumber, $countryCode);
49 | }
50 |
51 | public function countryInEurope(string $countryCode): bool
52 | {
53 | return $this->countryResolver->isCountryValid($countryCode) && $this->countryResolver->isCountryInEu($countryCode);
54 | }
55 |
56 | public function europeanVatRate(string $countryCode, ?DateTimeImmutable $date = null, float $fallbackRate = 0.0): float
57 | {
58 | if (! $this->countryInEurope($countryCode)) {
59 | return $fallbackRate;
60 | }
61 | return $this->vatRateResolver->getDefaultVatRateForCountry($countryCode, $date) ?? $fallbackRate;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/VatNumbers/ValidatesVatNumbers.php:
--------------------------------------------------------------------------------
1 | client = $client;
18 | }
19 |
20 | public function verifyVatNumber(string $vatNumber, string $countryCode): bool
21 | {
22 | $params = [
23 | 'countryCode' => $countryCode,
24 | 'vatNumber' => $vatNumber,
25 | ];
26 |
27 | try {
28 | $response = $this->getClient()->checkVat($params);
29 |
30 | return $response->valid;
31 | } catch (SoapFault $fault) {
32 | throw new VatNumberValidateFailedException(
33 | 'Unable to verify VAT number using VIES API: ' . $fault->faultstring,
34 | ['checkVat' => $params],
35 | );
36 | }
37 | }
38 |
39 | public function getClient(): SoapClient
40 | {
41 | if (! $this->client instanceof SoapClient) {
42 | $this->client = new SoapClient(self::WSDL);
43 | }
44 |
45 | return $this->client;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/VatRates/ResolvesVatRates.php:
--------------------------------------------------------------------------------
1 | client = $client;
24 | $this->cache = null;
25 | }
26 |
27 | public function setCache(?CacheInterface $cache): void
28 | {
29 | $this->cache = $cache;
30 | }
31 |
32 | /**
33 | * Retrieve the default VAT rate for a given country. If the countries VAT rate cannot be resolved, null is returned.
34 | * This also happens if the country does not exist in the European Tax Database.
35 | *
36 | * @param string $countryCode ISO country code
37 | * @param ?DateTimeImmutable $dateTime Date of checking, defaults to today.
38 | *
39 | * @return float|null
40 | */
41 | public function getDefaultVatRateForCountry(string $countryCode, ?DateTimeImmutable $dateTime = null): ?float
42 | {
43 | $date = $dateTime ?? new DateTimeImmutable();
44 | $response = $this->call('retrieveVatRates', [
45 | 'retrieveVatRatesRequest' => [
46 | 'memberStates' => [$countryCode],
47 | 'situationOn' => $date->format('Y-m-d'),
48 | ],
49 | ]);
50 |
51 | if ($response === null) {
52 | return null;
53 | }
54 |
55 | return $this->parseRetrieveVatRateResponse($response, $countryCode, self::RATE_TYPE_STANDARD, self::RATE_VALUE_TYPE_DEFAULT);
56 | }
57 |
58 | private function parseRetrieveVatRateResponse(object $response, string $countryCode, string $rateType, string $rateValueType): ?float
59 | {
60 | if (! isset($response->vatRateResults)) {
61 | return null;
62 | }
63 |
64 | foreach ($response->vatRateResults as $vatRateResult) {
65 | if (
66 | isset($vatRateResult->memberState) &&
67 | isset($vatRateResult->rate) &&
68 | isset($vatRateResult->rate->type) &&
69 | isset($vatRateResult->rate->value) &&
70 | isset($vatRateResult->type) &&
71 | (
72 | $vatRateResult->memberState === $countryCode ||
73 | (
74 | /** There is a European alias for Greece (GR) which is EL. */
75 | $vatRateResult->memberState === 'EL' && $countryCode === 'GR'
76 | )
77 | ) &&
78 | $vatRateResult->type === $rateType &&
79 | $vatRateResult->rate->type === $rateValueType &&
80 | (
81 | ! isset($vatRateResult->comment) ||
82 | strpos($vatRateResult->comment, 'Canary Islands') === false
83 | )
84 | ) {
85 | return $vatRateResult->rate->value;
86 | }
87 | }
88 | return null;
89 | }
90 |
91 | /**
92 | * @param array> $params
93 | */
94 | private function call(string $call, array $params): ?object
95 | {
96 | $cacheKey = $this->generateCacheKey($call, $params);
97 | if ($this->cache !== null && $this->cache->has($cacheKey)) {
98 | return $this->cache->get($cacheKey);
99 | }
100 | try {
101 | $response = $this->getClient()->__soapCall($call, $params);
102 | } catch (SoapFault $fault) {
103 | throw new VatFetchFailedException(
104 | 'Could not fetch VAT rate from TEDB: ' . $fault->faultstring,
105 | $params
106 | );
107 | }
108 | if (! is_object($response)) {
109 | return null;
110 | }
111 | if ($this->cache !== null) {
112 | $this->cache->set($cacheKey, $response);
113 | }
114 | return $response;
115 | }
116 |
117 | /**
118 | * @param string $call
119 | * @param array> $params
120 | *
121 | * @return string
122 | */
123 | private function generateCacheKey(string $call, array $params): string
124 | {
125 | return 'eu_taxes_response_' . md5(serialize(['call' => $call, 'params' => $params]));
126 | }
127 |
128 | private function getClient(): SoapClient
129 | {
130 | if (! $this->client instanceof SoapClient) {
131 | $this->client = new SoapClient(self::WSDL);
132 | }
133 |
134 | return $this->client;
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/tests/Countries/ValidateCountriesTest.php:
--------------------------------------------------------------------------------
1 | isCountryValid($countryCode), 'Unexpected value, country code valid/invalid.');
18 | Assert::assertSame($inEu, $countries->isCountryInEu($countryCode), 'Unexpected value, country in/not-in eu.');
19 | }
20 |
21 | /**
22 | * @return Generator>
23 | */
24 | public static function countriesProvider(): Generator
25 | {
26 | yield ['NL', true, true];
27 | yield ['OM', true, false];
28 | yield ['XX', false, false];
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tests/IntegrationTest.php:
--------------------------------------------------------------------------------
1 | service = new Vat();
26 | }
27 |
28 | public function testEuropeanVatRate(): void
29 | {
30 | sleep(2);
31 | Assert::assertSame(21.0, $this->service->europeanVatRate('NL'));
32 | }
33 |
34 | /** @depends testEuropeanVatRate */
35 | public function testNonEuropeanVatRate(): void
36 | {
37 | sleep(2);
38 | Assert::assertSame(0.0, $this->service->europeanVatRate('OM'));
39 | }
40 |
41 | /** @depends testNonEuropeanVatRate */
42 | public function testEuropeanVatNumber(): void
43 | {
44 | sleep(2);
45 | Assert::assertTrue($this->service->validateEuropeanVatNumber('NL861350480B01', 'NL'));
46 | Assert::assertFalse($this->service->validateEuropeanVatNumber('NL138250460B01', 'NL'));
47 | }
48 |
49 | /** @depends testEuropeanVatNumber */
50 | public function testNonEuropeanVatNumber(): void
51 | {
52 | sleep(2);
53 | Assert::assertFalse($this->service->validateEuropeanVatNumber('NL861350480B01', 'OM'));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/tests/VatNumbers/VatClientTest.php:
--------------------------------------------------------------------------------
1 | getMockFromWsdl(ViesClient::WSDL);
21 | $mockedSoapClient->method('checkVat')->willReturn($validated);
22 |
23 | $client = new ViesClient($mockedSoapClient);
24 |
25 | Assert::assertTrue($client->verifyVatNumber('NL138250460B01', 'NL'));
26 | }
27 |
28 | public function testGetRatesException(): void
29 | {
30 | /** @var MockObject&SoapClient $mockedSoapClient */
31 | $mockedSoapClient = $this->getMockFromWsdl(ViesClient::WSDL);
32 | $mockedSoapClient->method('checkVat')
33 | ->willThrowException(new SoapFault('test', 'testtest'));
34 |
35 | $client = new ViesClient($mockedSoapClient);
36 |
37 | $this->expectException(VatNumberValidateFailedException::class);
38 | $client->verifyVatNumber('NL138250460B01', 'NL');
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tests/VatNumbers/numbers_snapshot.php:
--------------------------------------------------------------------------------
1 | getMockFromWsdl(TaxesEuropeDatabaseClient::WSDL);
23 | $mockedSoapClient->method('__soapCall')->with('retrieveVatRates')->willReturn($rates);
24 | $client = new TaxesEuropeDatabaseClient($mockedSoapClient);
25 |
26 | $result = $client->getDefaultVatRateForCountry($countryCode);
27 | Assert::assertSame($rate, $result);
28 | }
29 |
30 | public function testGetRatesException(): void
31 | {
32 | /** @var MockObject&SoapClient $mockedSoapClient */
33 | $mockedSoapClient = $this->getMockFromWsdl(TaxesEuropeDatabaseClient::WSDL);
34 | $mockedSoapClient->method('__soapCall')
35 | ->with('retrieveVatRates')
36 | ->willThrowException(new SoapFault('test', 'testtest'));
37 | $client = new TaxesEuropeDatabaseClient($mockedSoapClient);
38 |
39 | $this->expectException(VatFetchFailedException::class);
40 | $client->getDefaultVatRateForCountry('NL');
41 | }
42 |
43 | /** @return Generator> */
44 | public static function soapTestData(): Generator
45 | {
46 | yield ['NL', unserialize(include 'nl_rates_snapshot.php'), 21.0];
47 | yield ['GR', unserialize(include 'gr_rates_snapshot.php'), 24.0];
48 | yield ['NL', null, null];
49 | yield ['NL', (object) [], null];
50 | yield ['NL', (object) ['vatRateResults' => []], null];
51 | }
52 |
53 | public function testWithColdCache(): void
54 | {
55 | /** @var MockObject&SoapClient $mockedSoapClient */
56 | $mockedSoapClient = $this->getMockFromWsdl(TaxesEuropeDatabaseClient::WSDL);
57 | $mockedSoapClient
58 | ->expects(TestCase::once())
59 | ->method('__soapCall')
60 | ->with('retrieveVatRates')
61 | ->willReturn(unserialize(include 'nl_rates_snapshot.php'));
62 |
63 | $cache = $this->createMock(CacheInterface::class);
64 | $cache->expects(TestCase::once())->method('has')->willReturn(false);
65 | $cache->expects(TestCase::never())->method('get');
66 | $cache->expects(TestCase::once())->method('set');
67 |
68 | $client = new TaxesEuropeDatabaseClient($mockedSoapClient);
69 | $client->setCache($cache);
70 | $client->getDefaultVatRateForCountry('NL');
71 | }
72 |
73 | public function testWithWarmCache(): void
74 | {
75 | /** @var MockObject&SoapClient $mockedSoapClient */
76 | $mockedSoapClient = $this->getMockFromWsdl(TaxesEuropeDatabaseClient::WSDL);
77 | $mockedSoapClient->expects(TestCase::never())->method('__soapCall');
78 |
79 | $cache = $this->createMock(CacheInterface::class);
80 | $cache->expects(TestCase::once())->method('has')->willReturn(true);
81 | $cache->expects(TestCase::once())->method('get')->willReturn(unserialize(include 'nl_rates_snapshot.php'));
82 | $cache->expects(TestCase::never())->method('set');
83 |
84 | $client = new TaxesEuropeDatabaseClient($mockedSoapClient);
85 | $client->setCache($cache);
86 | $client->getDefaultVatRateForCountry('NL');
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/tests/VatRates/gr_rates_snapshot.php:
--------------------------------------------------------------------------------
1 | createMock(ResolvesCountries::class);
21 | $mock->method('isCountryValid')->willReturn($validCountry);
22 | $mock->method('isCountryInEu')->willReturn($inEu);
23 | $service = new Vat($mock);
24 |
25 | Assert::assertSame($result, $service->countryInEurope('NL'));
26 | }
27 |
28 | /** @return Generator> */
29 | public static function countryTestData(): Generator
30 | {
31 | yield [true, true, true];
32 | yield [true, false, false];
33 | yield [false, true, false];
34 | yield [false, false, false];
35 | }
36 |
37 | /** @dataProvider vatNumberTestData */
38 | public function testValidateVatNumber(
39 | bool $valid,
40 | bool $validCountry,
41 | bool $inEu,
42 | string $vatNumber,
43 | string $countryCode,
44 | bool $result
45 | ): void {
46 | $countryResolverMock = $this->createMock(ResolvesCountries::class);
47 | $countryResolverMock->method('isCountryValid')->willReturn($validCountry);
48 | $countryResolverMock->method('isCountryInEu')->willReturn($inEu);
49 |
50 | $vatVerifyMock = $this->createMock(ValidatesVatNumbers::class);
51 | $vatVerifyMock->method('verifyVatNumber')->willReturn($valid);
52 | $service = new Vat($countryResolverMock, null, $vatVerifyMock);
53 |
54 | Assert::assertSame($result, $service->validateEuropeanVatNumber($vatNumber, $countryCode));
55 | }
56 |
57 | /** @return Generator> */
58 | public static function vatNumberTestData(): Generator
59 | {
60 | yield [true, true, true, '138250460B01', 'NL', true];
61 | yield [true, true, true, 'NL138250460B01', 'NL', true];
62 | yield [true, true, false, 'NL138250460B01', 'AZ', false];
63 | yield [false, true, true, 'invalidVatNumber', 'DE', false];
64 | yield [false, true, false, 'invalidVatNumber', 'IN', false];
65 | }
66 |
67 | /** @dataProvider euVatRateTestData */
68 | public function testEuropeanVatRate(string $countryCode, bool $validCountry, bool $inEu, ?float $rate, float $result): void
69 | {
70 | $countryResolverMock = $this->createMock(ResolvesCountries::class);
71 | $countryResolverMock->method('isCountryValid')->willReturn($validCountry);
72 | $countryResolverMock->method('isCountryInEu')->willReturn($inEu);
73 |
74 | $vatResolverMock = $this->createMock(ResolvesVatRates::class);
75 | $vatResolverMock->method('getDefaultVatRateForCountry')->willReturn($rate);
76 |
77 | $service = new Vat($countryResolverMock, $vatResolverMock);
78 |
79 | Assert::assertSame($result, $service->europeanVatRate($countryCode));
80 | }
81 |
82 | /** @return Generator> */
83 | public static function euVatRateTestData(): Generator
84 | {
85 | yield ['NL', true, true, 21.0, 21.0];
86 | yield ['LU', true, true, 17.0, 17.0];
87 | yield ['OM', true, false, 3.0, 0.0];
88 | yield ['CA', true, false, null, 0.0];
89 | yield ['XX', false, false, null, 0.0];
90 | }
91 |
92 | public function testWithoutCache(): void
93 | {
94 | $vat = new Vat();
95 | // Get Vat::vatRateResolver property.
96 | $vatReflection = new \ReflectionClass($vat);
97 | $resolverProperty = $vatReflection->getProperty('vatRateResolver');
98 | $resolverProperty->setAccessible(true);
99 | $resolver = $resolverProperty->getValue($vat);
100 | // Get TaxesEuropeDatabaseClient::cache property.
101 | $resolverReflection = new \ReflectionClass($resolver);
102 | $cacheProperty = $resolverReflection->getProperty('cache');
103 | $cacheProperty->setAccessible(true);
104 | $cache = $cacheProperty->getValue($resolver);
105 |
106 | Assert::assertNull($cache);
107 | }
108 |
109 | public function testWithCache(): void
110 | {
111 | $vat = new Vat(null, null, null, $this->createStub(CacheInterface::class));
112 | // Get Vat::vatRateResolver property.
113 | $vatReflection = new \ReflectionClass($vat);
114 | $resolverProperty = $vatReflection->getProperty('vatRateResolver');
115 | $resolverProperty->setAccessible(true);
116 | $resolver = $resolverProperty->getValue($vat);
117 | // Get TaxesEuropeDatabaseClient::cache property.
118 | $resolverReflection = new \ReflectionClass($resolver);
119 | $cacheProperty = $resolverReflection->getProperty('cache');
120 | $cacheProperty->setAccessible(true);
121 | $cache = $cacheProperty->getValue($resolver);
122 |
123 | Assert::assertInstanceOf(CacheInterface::class, $cache);
124 | }
125 | }
126 |
--------------------------------------------------------------------------------