Skip to content

Commit

Permalink
Merge pull request #56 from offline-agency/feat-add-hook
Browse files Browse the repository at this point in the history
Add hook for completed document reqeusts + handle throttle
  • Loading branch information
Giacomo92 authored Oct 21, 2021
2 parents a56cb01 + d055e85 commit c91c3e0
Show file tree
Hide file tree
Showing 6 changed files with 449 additions and 72 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"OfflineAgency\\FattureInCloud\\FattureInCloudServiceProvider"
],
"aliases": {
"FattureInCloud": "GarbinLuca\\FattureInCloud\\FattureInCloudFacade"
"FattureInCloud": "OfflineAgency\\FattureInCloud\\FattureInCloudFacade"
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions config/fatture-in-cloud.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,7 @@
'message' => 'Non è possibile completare la richiesta perché è stato raggiunto il limite massimo di anagrafiche.',
],
],
'timeout-errors-codes' => [
2002
]
];
237 changes: 202 additions & 35 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@
namespace OfflineAgency\FattureInCloud;

use Exception;
use OfflineAgency\FattureInCloud\Events\DocumentRequestPerformed;

class Auth
{
private $errors = [];
private $attempts;
private $params = [];

/**
* Auth constructor.
*
* @param string $apiUid
* @param string $apiKey
*
* @param string $apiUid
* @param string $apiKey
* @throws Exception
*/
public function __construct($apiUid = '', $apiKey = '')
public function __construct(
string $apiUid = '',
string $apiKey = ''
)
{
$this->errors = config('fatture-in-cloud.errors');
$this->attempts = 0;

if (empty($apiUid) || empty($apiKey)) {
throw new \Exception('You need to pass apiUid and apiKey');
Expand All @@ -32,68 +33,234 @@ public function __construct($apiUid = '', $apiKey = '')
}

/**
* Exec API call.
*
* @param string $url
* @param array $data
* @param string $method
* @return array|mixed
* @param string $url
* @param array $data
* @param string $method
* @param array $additional_data
* @param string $action
* @param string $type
* @return mixed|object
*/
private function call($url = '', $data = [], $method = 'post')
private function call(
string $url = '',
array $data = [],
string $method = 'post',
array $additional_data = [],
string $action = '',
string $type = ''
)
{
try {
$url = config('fatture-in-cloud.endpoint').$url;
$url = config('fatture-in-cloud.endpoint') . $url;

$options = [
'http' => [
'header' => "Content-type: text/json\r\n",
'method' => $method,
'header' => "Content-type: text/json\r\n",
'method' => $method,
'content' => json_encode($data),
],
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = file_get_contents($url, false, $context);

return self::parseResponse($result);
$response = $this->parseResponse(
$response,
$url,
$data,
$method,
$additional_data,
$action,
$type
);

event(new DocumentRequestPerformed(
$type,
$action,
$data,
$additional_data,
$response,
$this->parseHeaders($http_response_header)
));

return $response;
} catch (Exception $e) {
return (object) [
'error' => $e->getMessage(),
'code' => $e->getCode(),
$response = (object)[
'error' => $e->getMessage(),
'code' => $e->getCode(),
'success' => false,
];

event(new DocumentRequestPerformed(
$type,
$action,
$data,
$additional_data,
$response,
$this->parseHeaders($http_response_header)
));

return (object)[
'error' => $e->getMessage(),
'code' => $e->getCode(),
'success' => false,
];
}
}

/**
* Parse response.
*
* @param $response
* @param $url
* @param $data
* @param $method
* @param $additional_data
* @param $action
* @param $type
* @return mixed
*
* @throws Exception
*/
private function parseResponse($response)
private function parseResponse(
$response,
$url,
$data,
$method,
$additional_data,
$action,
$type
)
{
$json = json_decode($response);
if (isset($json->error)) {
throw new \Exception($json->error, $this->errors[$json->error_code]['code']);
if (
isset($json->error)
&& isset($json->error_code)
) {
$timeout_errors_codes = config('fatture-in-cloud.timeout-errors-codes');
if (in_array($json->error_code, $timeout_errors_codes)) {
$this->handleThrottle(
$json,
$url,
$data,
$method,
$additional_data,
$action,
$type
);
} else {
throw new \Exception($json->error, $json->error_code);
}
}

return $json;
}

/**
* POST call.
*
* @param $json
* @param $url
* @param $data
* @param $method
* @param $additional_data
* @param $action
* @param $type
* @throws Exception
*/
private function handleThrottle(
$json,
$url,
$data,
$method,
$additional_data,
$action,
$type
)
{
$attempts = $this->attempts;
$times = config('nom.config', 3);

if ($attempts < $times) {
$this->attempts++;
$seconds = $this->getRetrySeconds(
$json->error
);

$seconds = $seconds * 1000;
usleep($seconds);

$this->call(
$url,
$data,
$method,
$additional_data,
$action,
$type
);
} else {
throw new \Exception('Timeout error', 'OA0001');
}
}

/**
* @param $error_message
* @return float|int
*/
private function getRetrySeconds(
$error_message
)
{
$seconds = 0;
$split_error_message = explode('Attendi ', $error_message);
if (count($split_error_message) > 1) {
$split_error_message = explode(' secondi', $split_error_message[1]);
$seconds = (int)$split_error_message[0];
}
return $seconds * 1000;
}

/**
* @param $path
* @param array $data
* @return mixed|string
* @param array $data
* @param array $additional_data
* @param string $action
* @param string $type
* @return mixed|object
*/
public function post($path, $data = [])
public function post(
$path,
array $data = [],
array $additional_data = [],
string $action = '',
string $type = ''
)
{
$params = array_merge($this->params, $data);

return $this->call($path, $params, 'POST');
return $this->call(
$path, $params,
'POST',
$additional_data,
$action,
$type
);
}

/**
* @param $headers
* @return array
*/
private function parseHeaders(
$headers
): array
{
$head = array();
foreach ($headers as $k => $v) {
$t = explode(':', $v, 2);
if (isset($t[1]))
$head[trim($t[0])] = trim($t[1]);
else {
$head[] = $v;
if (preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#", $v, $out))
$head['reponse_code'] = intval($out[1]);
}
}
return $head;
}
}
Loading

0 comments on commit c91c3e0

Please sign in to comment.