Created
June 21, 2019 22:40
-
-
Save alexrusin/6935417323045fca94830d2012442353 to your computer and use it in GitHub Desktop.
Connector Retry Decorator
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 | |
namespace SunriseIntegration\PeruConnector\Connector; | |
class RetryDecorator | |
{ | |
protected $connector; | |
protected $method; | |
protected $arguments = []; | |
protected $soapFaultRetries = 0; | |
protected $invoiceExistsRetries = 0; | |
public function __construct($connector) | |
{ | |
$this->connector = $connector; | |
} | |
public function __call($method, $arguments) | |
{ | |
$this->method = $method; | |
$this->arguments = $arguments; | |
return $this; | |
} | |
public function retrySoapFault($times = 1) | |
{ | |
$this->soapFaultRetries = $times; | |
return $this; | |
} | |
public function retryInvoiceExists($times = 1) | |
{ | |
$this->invoiceExistsRetries = $times; | |
return $this; | |
} | |
public function go() | |
{ | |
if (!method_exists($this->connector, $this->method)) { | |
throw new \BadMethodCallException; | |
} | |
while(true) { | |
try { | |
$result = $this->connector->{$this->method}(...$this->arguments); | |
$code = $result->CODIGO ?? null; | |
$details = $result->DETALLE ?? null; | |
if ($this->invoiceExists($code, $details) && $this->invoiceExistsRetries > 0) { | |
if (array_key_exists(2, $this->arguments)) { | |
$this->arguments[2]->incrementInvoiceNumber(); | |
} | |
$this->invoiceExistsRetries --; | |
usleep(500000); | |
continue; | |
} | |
break; | |
} catch (\SoapFault $fault) { | |
if ($this->soapFaultRetries > 0) { | |
$this->soapFaultRetries--; | |
usleep(500000); | |
continue; | |
} else { | |
throw $fault; | |
} | |
} | |
} | |
return $result; | |
} | |
private function invoiceExists($code, $details) | |
{ | |
return $code == '002' && strpos($details, 'el recibo ya existe') !== false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment