feat: refactor API client socket logic to trait

This commit is contained in:
Björn Fromme
2025-01-15 15:28:37 +01:00
parent 13385a10e3
commit e6d7a10874
2 changed files with 87 additions and 73 deletions
+9 -73
View File
@@ -21,6 +21,8 @@ use Symfony\Component\Serializer\SerializerInterface;
class ApiClient
{
use ApiClientTrait;
public const TYPE_NOTIFICATION = 'HINWEIS';
public const TYPE_CUSTOMER_DATA = 'KUNDENKONTO';
public const TYPE_BASE_DATA_COUNTRIES = 'STAMMLAENDER';
@@ -279,77 +281,6 @@ class ApiClient
return $this->sendRequest(static::TYPE_CUSTOMER_DATA, $data);
}
/**
* @throws ApiClientException
*/
private function connect()
{
$tries = 1;
$errNo = $errStr = '';
$maxRetries = $this->config['max_retries'];
$errorCodesForRetry = [
SOCKET_ECONNREFUSED,
SOCKET_EBADF,
];
$openSocket = function (&$errNo, &$errStr) {
return @fsockopen(
$this->config['bpn_api_ip'],
$this->config['bpn_api_port'],
$errNo,
$errStr,
10
);
};
$socket = $openSocket($errNo, $errStr);
while (false === $socket && true === in_array($errNo, $errorCodesForRetry) && $maxRetries > $tries) {
$this->logger->warning('Could not connect to socket, retrying', [
'error_message' => $errStr,
'error_number' => $errNo,
]);
++$tries;
sleep(1);
$socket = $openSocket($errNo, $errStr);
}
if (false !== $socket) {
stream_set_timeout($socket, 60);
} else {
$this->logger->error('Unable to open socket', [
'error_message' => $errStr,
'error_number' => $errNo,
]);
throw new ApiClientException('Unable to open socket');
}
return $socket;
}
private function send($socket, string $data): void
{
// message length is prepended to actual message
$send = sprintf('%010s', strlen($data)) . $data;
fwrite($socket, $send);
}
private function receive($socket): string
{
$response = '';
while (false === feof($socket)) {
$response .= fread($socket, 4096);
}
return $response;
}
private function disconnect($socket): void
{
@fclose($socket);
}
/**
* @throws ApiClientException
* @throws ResponseParserException
@@ -371,12 +302,17 @@ class ApiClient
$this->dumpXmlToFile('request', $requestId, $body);
}
$socket = $this->connect();
$socket = $this->connect(
$this->config['bpn_api_ip'],
$this->config['bpn_api_port'],
$this->config['max_retries']
);
$this->send($socket, $body);
$response = $this->receive($socket);
$this->disconnect($socket);
// message length (10 bytes) is prepended to actual message
$xml = substr($response, 10);
$this->disconnect($socket);
if (true === $this->config['debug']) {
$this->dumpXmlToFile('response', $requestId, $xml);