VatNumber.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. *
  4. * PHP Pro Bid $Id$ 8wErA/YvHYujRUGXtkmqJ0b4n6A683Rt4G0WDGhr6DI=
  5. *
  6. * @link http://www.phpprobid.com
  7. * @copyright Copyright (c) 2017 Online Ventures Software & CodeCube SRL
  8. * @license http://www.phpprobid.com/license Commercial License
  9. *
  10. * @version 7.9 [rev.7.9.01]
  11. */
  12. /**
  13. * EU VAT number validator class
  14. */
  15. namespace Ppb\Validate;
  16. use Cube\Validate\AbstractValidate;
  17. class VatNumber extends AbstractValidate
  18. {
  19. const WEBSERVICE_URL = "http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl";
  20. protected $_message = "'%s': '%value%' is not a valid VAT number.";
  21. /**
  22. *
  23. * checks if the value is a valid VAT number
  24. * using the VIES web service
  25. *
  26. * @return bool
  27. * @throws \Exception
  28. */
  29. public function isValid()
  30. {
  31. $value = $this->getValue();
  32. if (empty($value)) {
  33. return true;
  34. }
  35. $formattedValue = preg_replace('/[ \-,.]/', '', $value);
  36. $countryCode = substr($formattedValue, 0, 2); // get country code - first two letters of VAT ID
  37. $vatNumber = substr($formattedValue, 2);
  38. if (!class_exists('SoapClient')) {
  39. throw new \Exception('The Soap library has to be installed and enabled.');
  40. }
  41. try {
  42. $client = new \SoapClient(self::WEBSERVICE_URL, array('trace' => true));
  43. } catch (\Exception $e) {
  44. throw new \Exception('Web Service Error: ' . $e->getMessage());
  45. }
  46. try {
  47. $rs = $client->checkVat(array('countryCode' => $countryCode, 'vatNumber' => $vatNumber));
  48. if ($rs->valid) {
  49. return true;
  50. }
  51. } catch (\Exception $e) {
  52. }
  53. $this->setMessage(
  54. str_replace('%value%', $value, $this->getMessage()));
  55. return false;
  56. }
  57. }