Skip to content

Instantly share code, notes, and snippets.

@alexrusin
Created June 21, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexrusin/6935417323045fca94830d2012442353 to your computer and use it in GitHub Desktop.
Save alexrusin/6935417323045fca94830d2012442353 to your computer and use it in GitHub Desktop.
Connector Retry Decorator
<?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