EuVatNumberValidator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 43
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A validateFormat() 0 3 1
A __construct() 0 2 1
A getCountries() 0 13 3
A validate() 0 6 2
A validateCountry() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewebe\SyliusVATPlugin\Vat\Number\Validator;
6
7
use Gewebe\SyliusVATPlugin\Vat\Number\ClientException;
8
use Gewebe\SyliusVATPlugin\Vat\Number\VatNumberValidatorInterface;
9
use Ibericode\Vat\Countries;
10
use Ibericode\Vat\Validator;
11
use Ibericode\Vat\Vies\ViesException;
12
13
/**
14
 * European VAT number validator
15
 */
16
final class EuVatNumberValidator implements VatNumberValidatorInterface
17
{
18
    public function __construct(private Validator $validator)
19
    {
20
    }
21
22
    public function getCountries(): array
23
    {
24
        $countries = new Countries();
25
        $euCountries = [];
26
27
        /** @var string $countryCode */
28
        foreach (array_keys(iterator_to_array($countries)) as $countryCode) {
29
            if ($countries->isCountryCodeInEU($countryCode)) {
30
                $euCountries[] = $countryCode;
31
            }
32
        }
33
34
        return $euCountries;
35
    }
36
37
    public function validateCountry(string $vatNumber, string $countryCode): bool
38
    {
39
        $country = substr($vatNumber, 0, 2);
40
41
        if (strtolower($country) === strtolower($countryCode)) {
42
            return true;
43
        }
44
45
        return false;
46
    }
47
48
    public function validateFormat(string $vatNumber): bool
49
    {
50
        return $this->validator->validateVatNumberFormat($vatNumber);
51
    }
52
53
    public function validate(string $vatNumber): bool
54
    {
55
        try {
56
            return $this->validator->validateVatNumber($vatNumber);
57
        } catch (ViesException $e) {
58
            throw new ClientException($e->getMessage(), $e->getCode());
59
        }
60
    }
61
}
62