From 37cbe082df2c07bd3d43f014b4686c6cd1553242 Mon Sep 17 00:00:00 2001 From: Roel van Duijnhoven Date: Mon, 4 Dec 2017 13:30:02 +0100 Subject: [PATCH] Instantiate client only when required. 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. --- src/Validator.php | 2 ++ src/Vies/Client.php | 23 ++++++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/Validator.php b/src/Validator.php index 083d187..e23e217 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -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 ); diff --git a/src/Vies/Client.php b/src/Vies/Client.php index f76f9c9..bea301a 100644 --- a/src/Vies/Client.php +++ b/src/Vies/Client.php @@ -15,7 +15,12 @@ class Client { /** * @var SoapClient */ - protected $client; + private $client; + + /** + * @var int + */ + protected $timeout; /** * Client constructor. @@ -23,7 +28,7 @@ class Client { * @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; } /** @@ -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 @@ -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; + } }