-
Notifications
You must be signed in to change notification settings - Fork 2
/
EuVatValidator.php
98 lines (89 loc) · 2.81 KB
/
EuVatValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace elvenpath\yii2_eu_vatvalidator;
use Exception;
use SoapClient;
use SoapFault;
use stdClass;
use Yii;
use yii\validators\Validator;
/**
* Class EuVatValidator
*
* @package elvenpath\yii2_eu_vatvalidator
*/
class EuVatValidator extends Validator
{
/** @var string */
public $wsdl_uri = "http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl";
/** @var string 2 letter country code */
public $country_code;
/**
* @var bool
*
* If true the $model_name_attribute and $model_address_attribute will be populated
* with the EU official company name and address
*/
public $populate_model = false;
/** @var string */
public $model_name_attribute = 'name';
/** @var string */
public $model_address_attribute = 'address';
/** @var SoapClient */
private $client;
public function init()
{
parent::init();
if (!class_exists('SoapClient')) {
throw new Exception('The Soap library has to be installed and enabled');
}
$this->client = new SoapClient($this->wsdl_uri, ['trace' => false]);
}
/**
* @param \yii\base\Model $model
* @param string $attribute
* @return bool
*/
public function validateAttribute($model, $attribute)
{
try {
/** @var stdClass $rs */
/** @noinspection PhpUndefinedMethodInspection */
$rs = $this->client->checkVat([
'countryCode' => $this->country_code,
'vatNumber' => preg_replace('/^' . $this->country_code . '/', '', $model->$attribute)
]);
} catch (SoapFault $e) {
$this->addError($model, $attribute,
$this->message ? $this->message : Yii::t('yii',
'Cannot check {attribute} at this point. Please try again later.'));
}
if (isset($rs)) {
if (!$rs->valid) {
$this->addError($model, $attribute,
$this->message ? $this->message : Yii::t('yii', '{attribute} is invalid.'));
} else {
if ($this->populate_model) {
$this->model_name_attribute = $this->cleanUpString($rs->name);
$this->model_address_attribute = $this->cleanUpString($rs->address);
}
}
}
}
private function cleanUpString($string)
{
for ($i = 0; $i < 100; $i++) {
$newString = str_replace(" ", " ", $string);
if ($newString === $string) {
break;
} else {
$string = $newString;
}
}
$newString = "";
$words = explode(" ", $string);
foreach ($words as $k => $w) {
$newString .= ucfirst(strtolower($w)) . " ";
}
return $newString;
}
}