feat: refactor API client socket logic to trait
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\BusProNet;
|
||||
|
||||
use App\BusProNet\Exception\ApiClientException;
|
||||
|
||||
trait ApiClientTrait
|
||||
{
|
||||
/**
|
||||
* @throws ApiClientException
|
||||
*/
|
||||
private function connect(string $host, int $port, int $maxRetries = 25)
|
||||
{
|
||||
$tries = 1;
|
||||
$errNo = $errStr = '';
|
||||
$errorCodesForRetry = [
|
||||
SOCKET_ECONNREFUSED,
|
||||
SOCKET_EBADF,
|
||||
];
|
||||
|
||||
$openSocket = function (&$errNo, &$errStr) use ($host, $port) {
|
||||
return @fsockopen(
|
||||
$host,
|
||||
$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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user