diff --git a/src/Validator/Constraints/VatNumber.php b/src/Validator/Constraints/VatNumber.php index 30a67d2..732f280 100644 --- a/src/Validator/Constraints/VatNumber.php +++ b/src/Validator/Constraints/VatNumber.php @@ -8,8 +8,11 @@ class VatNumber extends Constraint { public const INVALID_ERROR_CODE = '59421d43-d474-489c-b18c-7701329d51a0'; + public const VIES_EXCEPTION_ERROR_CODE = 'a1be6ee0-f27e-4d51-a132-f0a753c0b01e'; public string $message = '"{{ string }}" does not look like a valid VAT number.'; + public string $exceptionMessage = 'An error occurred while checking VAT number, please try again later'; public bool $checkExistence = true; + public bool $violateOnException = false; } diff --git a/src/Validator/Constraints/VatNumberValidator.php b/src/Validator/Constraints/VatNumberValidator.php index 920c83a..216b4bd 100644 --- a/src/Validator/Constraints/VatNumberValidator.php +++ b/src/Validator/Constraints/VatNumberValidator.php @@ -36,6 +36,14 @@ public function validate(mixed $value, Constraint $constraint) : void try { $valid = $this->validator->validateVatNumber($value); } catch (ViesException $e) { + if ($constraint->violateOnException) { + $this->context->buildViolation($constraint->exceptionMessage) + ->setCode(VatNumber::VIES_EXCEPTION_ERROR_CODE) + ->addViolation(); + + return; + } + // ignore VIES VAT exceptions (when the service is down) // this could mean that an unexisting VAT number passes validation, // but it's (probably) better than a hard-error diff --git a/tests/Validator/Constraints/VatNumberExceptionValidatorTest.php b/tests/Validator/Constraints/VatNumberExceptionValidatorTest.php new file mode 100644 index 0000000..cf530f1 --- /dev/null +++ b/tests/Validator/Constraints/VatNumberExceptionValidatorTest.php @@ -0,0 +1,43 @@ +createMock(Validator::class); + $mockValidator + ->method('validateVatNumber') + ->willThrowException(new ViesException()); + + return new VatNumberValidator($mockValidator); + } + + public function testViesExceptionValid() + { + $constraint = new VatNumber([ + 'violateOnException' => false, + ]); + $this->validator->validate('IE6388047V', $constraint); + $this->assertNoViolation(); + } + + public function testViesExceptionError() + { + $constraint = new VatNumber([ + 'violateOnException' => true, + ]); + $this->validator->validate('IE6388047V', $constraint); + $this->buildViolation('An error occurred while checking VAT number, please try again later') + ->setCode('a1be6ee0-f27e-4d51-a132-f0a753c0b01e') + ->assertRaised(); + } +}