Files
PVM/public_html/classes/IMSApi.CheckPartitaIva.class.php
2021-10-20 16:32:11 +02:00

103 lines
3.4 KiB
PHP

<?php
namespace IMSApi;
class CheckPartitaIva extends \IMSApi {
private $countryCode = null;
private $vatNumber = null;
// <editor-fold desc="SETTERS" defaultstate="collapsed">
public function countryCode($value) {
$this->countryCode = strtoupper($value);
return $this;
}
public function vatNumber($value) {
$this->vatNumber = $value;
return $this;
}
// </editor-fold>
public function __construct() {
$this->countryCode("IT")->service("checkPartitaIva")->post()->asJson();
}
private static function get_indirizzo($address) { // portarlo fuori
$IMSApi = new \IMSApi("geocode");
$Ret = $IMSApi->queryParams(array("address" => $address))->send();
if ($Ret->is_OK()) {
$retData = $Ret->get_data();
if (isset($retData[0]["dto"])) {
$Ret->set_data($retData[0]["dto"]);
} else {
$Ret->set_data(null);
}
}
return $Ret;
}
public function send() {
$Ret = new \Ret;
if (!is_null($this->countryCode) && !is_null($this->vatNumber)) {
if ($this->is_valid()) {
$body = array("countryCode" => $this->countryCode, "vatNumber" => $this->vatNumber);
$this->body($body);
$Ret = parent::send();
if ($Ret->is_OK()) {
$retData = $Ret->get_data();
$dto = $retData[0]["dto"];
$newtemp = true;
if (!$newtemp) {
$return = array(
"valid" => $dto["valid"],
"name" => $dto["name"],
"ragSoc" => $dto["name"],
"indirizzo" => null,
"citta" => null,
"cap" => null,
"prov" => null
);
$Ret2 = self::get_indirizzo($dto["address"]);
if ($Ret2->is_OK()) {
$retData = $Ret2->get_data();
$return["indirizzo"] = $retData["indirizzo"];
$return["citta"] = $retData["citta"];
$return["cap"] = $retData["cap"];
$return["prov"] = $retData["prov"];
}
$Ret->set_data($return);
} else {
$Ret->set_data($dto);
}
} else {
if ($Ret->get_number() == 400) {
$Ret->set_error("Partita IVA non formalmente valida");
}
}
} else {
$Ret->set_error("Partita IVA non valida");
}
} else {
$Ret->set_error("Parametri incompleti");
}
return $Ret;
}
private function is_valid() {
if ($this->countryCode == "IT") {
$pi = $this->vatNumber;
if (is_string($pi) && strlen($pi) == 11 && is_numeric($pi)) {
$checksum = "";
foreach (str_split(strrev($pi)) as $i => $d) {
$checksum .= $i % 2 !== 0 ? $d * 2 : $d;
}
return array_sum(str_split($checksum)) % 10 === 0;
}
return false;
}
return true;
}
}