Changed way to connect to api

This commit is contained in:
2022-11-30 10:40:36 -03:00
parent f8500e061c
commit a5d97729dc
12 changed files with 129 additions and 43 deletions

View File

@ -0,0 +1,17 @@
<?php
namespace ProVM\Common\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use ProVM\Common\Service\Api as Service;
class Api
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service $service): ResponseInterface
{
$body = $request->getBody();
$json = \Safe\json_decode($body->getContents(), JSON_OBJECT_AS_ARRAY);
return $service->sendRequest($json);
}
}

47
ui/common/Service/Api.php Normal file
View File

@ -0,0 +1,47 @@
<?php
namespace ProVM\Common\Service;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseInterface;
class Api
{
public function __construct(ClientInterface $client, RequestFactoryInterface $factory)
{
$this->setClient($client)
->setFactory($factory);
}
protected ClientInterface $client;
protected RequestFactoryInterface $factory;
public function getClient(): ClientInterface
{
return $this->client;
}
public function getFactory(): RequestFactoryInterface
{
return $this->factory;
}
public function setClient(ClientInterface $client): Api
{
$this->client = $client;
return $this;
}
public function setFactory(RequestFactoryInterface $factory): Api
{
$this->factory = $factory;
return $this;
}
public function sendRequest(array $request_data): ResponseInterface
{
$request = $this->getFactory()->createRequest(strtoupper($request_data['method']) ?? 'GET', $request_data['uri']);
if (strtolower($request_data['method']) !== 'get') {
$request->getBody()->write(\Safe\json_encode($request_data['data']));
$request->withHeader('Content-Type', 'application/json');
}
return $this->getClient()->sendRequest($request);
}
}