Completed
Pull Request — master (#2)
by
unknown
05:39
created

VatNumberCheck   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 21
c 1
b 0
f 0
dl 0
loc 77
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A check() 0 16 3
A normalize() 0 3 1
A getSoapDataSource() 0 13 2
1
<?php
2
namespace VatNumberCheck\Utility;
3
4
use Cake\Core\Configure;
5
use Cake\Http\Exception\InternalErrorException;
6
use VatNumberCheck\Model\Datasource\Soap;
7
8
/**
9
 * VatNumberCheck Utility.
10
 *
11
 */
12
class VatNumberCheck
13
{
14
15
/**
16
 * SOAP connection
17
 *
18
 * @var Soap
19
 */
20
protected $soapDataSource;
21
22
/**
23
 * check VAT SOAP action
24
 *
25
 * @var string
26
 */
27
const CHECK_VAT_SOAP_ACTION = 'checkVat';
28
29
    /**
30
     * Service to check vat numbers.
31
     *
32
     */
33
const CHECK_VAT_SERVICE = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
34
35
/**
36
 * Normalizes a VAT number.
37
 *
38
 * @param string $vatNumber A VAT number
39
 * @return string A (normalized) VAT number
40
  */
41
	public function normalize(string $vatNumber) : string
42
	{
43
        return preg_replace('/[^A-Z0-9]/', '', strtoupper($vatNumber));
44
    }
45
46
/**
47
 * Checks a given VAT number.
48
 *
49
 * @param string $vatNumber A VAT number
50
 * @return bool Valid or not
51
 * @throws InternalErrorException when it is not possible to check the data
52
 */
53
	public function check(string $prefixedVatNumber) : bool
54
	{
55
		$countryCode = substr($prefixedVatNumber, 0, 2);
56
		$vatNumber = substr($prefixedVatNumber, 2);
57
		$data = compact('countryCode', 'vatNumber');
58
59
		if (!$this->getSoapDataSource()->connect()) {
60
            throw new InternalErrorException('Unable to connect.');
61
        }
62
63
		$result = $this->soapDataSource->query(static::CHECK_VAT_SOAP_ACTION, $data);
64
		if (!$result) {
65
            throw new InternalErrorException('Unable to check data.');
66
        }
67
68
        return $result->valid;
69
	}
70
71
    /**
72
     * Returns an initialized Soap data source.
73
     *
74
     * @return Soap the soap datasource
75
     */
76
    protected function getSoapDataSource(): Soap
77
    {
78
		$wsdl = static::CHECK_VAT_SERVICE;
79
80
        if (!isset($this->soapDataSource)) {
81
			$this->soapDataSource = new Soap();
82
			$this->soapDataSource->setWsdl($wsdl);
83
			$this->soapDataSource->setOptions([
84
				'exceptions' => true
85
			]);
86
        }
87
88
        return $this->soapDataSource;
89
	}
90
}