This commit is contained in:
Juan Pablo Vial
2025-06-25 18:07:08 -04:00
parent 7f97862324
commit ab7328b40b
8 changed files with 202 additions and 20 deletions

View File

@ -0,0 +1,99 @@
<?php
namespace Incoviba\Service;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use hollodotme\FastCGI as FCGI;
use Incoviba\Exception\Client\FastCGI as FastCGIException;
class FastCGI implements LoggerAwareInterface
{
public function __construct(protected string $hostname, protected int $port,
protected string $documentRoot,
protected int $connectionTimeout = 5000, protected int $readTimeout = 5000)
{
$this->client = new FCGI\Client();
}
public LoggerInterface $logger {
get {
return $this->logger;
}
set(LoggerInterface $logger) {
$this->logger = $logger;
}
}
protected FCGI\Client $client;
protected FCGI\Interfaces\ConfiguresSocketConnection $socket;
public function connect(): self
{
$this->socket = new FCGI\SocketConnections\NetworkSocket($this->hostname, $this->port, $this->connectionTimeout, $this->readTimeout);
return $this;
}
protected array $socketIds = [];
/**
* @throws FastCGIException
*/
public function sendRequest(FCGI\Interfaces\ProvidesRequestData $request): self
{
if (!isset($this->socket)) {
$this->connect();
}
try {
$this->socketIds []= $this->client->sendAsyncRequest($this->socket, $request);
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
$this->logger->error($exception->getMessage());
throw new FastCGIException($exception);
}
return $this;
}
/**
* @return array
*/
public function awaitResponses(): array
{
$responses = [];
while ($this->client->hasUnhandledResponses()) {
try {
$readyResponses = $this->client->readReadyResponses(3000);
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
$this->logger->error($exception->getMessage());
continue;
}
foreach ($readyResponses as $response) {
$responses []= $response;
}
}
return $responses;
}
/**
* @param string $uri
* @return FastCGI
* @throws FastCGIException
*/
public function get(string $uri): self
{
$request = new FCGI\Requests\GetRequest($this->documentRoot, '');
$request->setRequestUri($uri);
return $this->sendRequest($request);
}
/**
* @param string $uri
* @param ?array $data
* @return FastCGI
* @throws FastCGIException
*/
public function post(string $uri, ?array $data): self
{
$content = new FCGI\RequestContents\JsonData($data ?? []);
$request = FCGI\Requests\PostRequest::newWithRequestContent($this->documentRoot, $content);
$request->setRequestUri($uri);
return $this->sendRequest($request);
}
}