Skip to content

Commit

Permalink
Instantiate client only when required.
Browse files Browse the repository at this point in the history
This improves this repo in two ways:

1. WSDL only requested when validate method actually used.
2. The WSDL client constructor can throw; and this is now properly
catched and wrapped in a ViesException.
  • Loading branch information
Roel van Duijnhoven committed Dec 4, 2017
1 parent ffc5cd5 commit 37cbe08
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ public function validateExistence($vatNumber) {
* @param string $vatNumber Either the full VAT number (incl. country) or just the part after the country code.
*
* @return boolean
*
* @throws Vies\ViesException
*/
public function validate( $vatNumber ) {
return $this->validateFormat( $vatNumber ) && $this->validateExistence( $vatNumber );
Expand Down
23 changes: 20 additions & 3 deletions src/Vies/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,20 @@ class Client {
/**
* @var SoapClient
*/
protected $client;
private $client;

/**
* @var int
*/
protected $timeout;

/**
* Client constructor.
*
* @param int $timeout How long should we wait before aborting the request to VIES?
*/
public function __construct($timeout = 10) {
$this->client = new SoapClient( self::URL, [ 'connection_timeout' => $timeout ]);
$this->timeout = $timeout;
}

/**
Expand All @@ -36,7 +41,7 @@ public function __construct($timeout = 10) {
*/
public function checkVat( $countryCode, $vatNumber ) {
try {
$response = $this->client->checkVat(
$response = $this->getClient()->checkVat(
array(
'countryCode' => $countryCode,
'vatNumber' => $vatNumber
Expand All @@ -48,4 +53,16 @@ public function checkVat( $countryCode, $vatNumber ) {

return (bool) $response->valid;
}

/**
* @return SoapClient
*/
protected function getClient()
{
if ($this->client === null) {
$this->client = new SoapClient(self::URL, ['connection_timeout' => $this->timeout]);
}

return $this->client;
}
}

0 comments on commit 37cbe08

Please sign in to comment.