pH-7 / eu-vat-validator

:moneybag: A simple and clean PHP library that validates EU VAT registration numbers against the central ec.europa.eu database (using the official europa API) :eu:
https://github.com/pH-7/eu-vat-validator
GNU General Public License v3.0
93 stars 17 forks source link

Add function to detect is country is valid or not. #15

Closed ortegafernando closed 4 months ago

ortegafernando commented 4 months ago

Hi, about my last PR I have added some useful code. Again, not pretty:

EuropaTIN class:

    protected const TIN_EU_COUNTRY_LIST = ['AT','BE','BG','CY','CZ','DE','DK','EE','EL','ES','FI','FR','HR','HU','IE','IT','LU','LV','LT','MT','NL','PL','PT','RO','SE','SI','SK'];
    private const COUNTRY_NOT_VALID = 'Country not valid in Europa TIN Service: %s';

    public function getResource($sTinNumber, string $sCountryCode): stdClass
    {
        if (!in_array(strtoupper($sCountryCode), self::TIN_EU_COUNTRY_LIST)) {
            throw new Exception(
                sprintf(self::COUNTRY_NOT_VALID, strtoupper($sCountryCode))
            );
        }
        try {
            $aDetails = [
                'countryCode' => strtoupper($sCountryCode),
                'tinNumber' => $sTinNumber
            ];
            return $this->oClient->checkTin($aDetails);
        } catch (SoapFault $oExcept) {
            throw new Exception(
                sprintf(self::IMPOSSIBLE_RETRIEVE_DATA_MESSAGE, $oExcept->faultstring)
            );
        }
    }

And EuropaVAT class (it also has Northern Ireland):

    protected const VAT_EU_COUNTRY_LIST = ['AT','BE','BG','CY','CZ','DE','DK','EE','EL','ES','FI','FR','HR','HU','IE','IT','LU','LV','LT','MT','NL','PL','PT','RO','SE','SI','SK','XI'];
    private const COUNTRY_NOT_VALID = 'Country not valid in Europa VAT Service: %s';

    public function getResource($sVatNumber, string $sCountryCode): stdClass
    {
        if (!in_array(strtoupper($sCountryCode), self::VAT_EU_COUNTRY_LIST)) {
            throw new Exception(
                sprintf(self::COUNTRY_NOT_VALID, strtoupper($sCountryCode))
            );
        }        
        try {
            $aDetails = [
                'countryCode' => strtoupper($sCountryCode),
                'vatNumber' => $sVatNumber
            ];
            return $this->oClient->checkVat($aDetails);
        } catch (SoapFault $oExcept) {
            throw new Exception(
                sprintf(self::IMPOSSIBLE_RETRIEVE_DATA_MESSAGE, $oExcept->faultstring)
            );
        }
    }

May you can implement this any other way or as you think is better.

Thanks a lot

ortegafernando commented 4 months ago

Added to PR https://github.com/pH-7/eu-vat-validator/pull/14