Last active
February 13, 2020 21:13
-
-
Save xavismeh/248449ee405885dff69df36267b170a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace MyPackage\Validator\Constraints\Vat; | |
use Psr\Log\LoggerInterface; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
use Symfony\Component\Validator\Exception\UnexpectedTypeException; | |
class EuropeanVatValidator extends ConstraintValidator | |
{ | |
/** | |
* @var LoggerInterface | |
*/ | |
protected $logger; | |
public function __construct(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validate($value, Constraint $constraint) | |
{ | |
if (!$constraint instanceof EuropeanVat) { | |
throw new UnexpectedTypeException($constraint, EuropeanVat::class); | |
} | |
if (\count($this->context->getViolations())) { | |
return; | |
} | |
$countryCode = mb_substr($value, 0, 2); | |
$vatNumber = mb_substr($value, 2); | |
$data = $this->context->getRoot()->getData(); | |
if ($countryCode != $data->getAddress()->getCountryCode()) { | |
$this->context->addViolation($constraint->invalidCountryCode); | |
return; | |
} | |
try { | |
$client = new \SoapClient($constraint->wsdlValidationUrl); | |
$result = $client->checkVat([ | |
'countryCode' => $countryCode, | |
'vatNumber' => $vatNumber, | |
]); | |
} catch (\SoapFault $e) { | |
// TODO: since the server is frequently unavailable, we do not blame the user for it... | |
$this->logger->error($e->getMessage()); | |
//$this->context->addViolation($constraint->serverUnreachable); | |
return; | |
} | |
if ($result->valid) { | |
return; | |
} | |
$this->context->addViolation($constraint->message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment