CLI
This commit is contained in:
64
cli/common/Service/Communicator.php
Normal file
64
cli/common/Service/Communicator.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
namespace ProVM\Common\Service;
|
||||
|
||||
use HttpResponseException;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use function Safe\json_encode;
|
||||
|
||||
class Communicator
|
||||
{
|
||||
public function __construct(ClientInterface $client)
|
||||
{
|
||||
$this->setClient($client);
|
||||
}
|
||||
|
||||
protected ClientInterface $client;
|
||||
|
||||
public function getClient(): ClientInterface
|
||||
{
|
||||
return $this->client;
|
||||
}
|
||||
|
||||
public function setClient(ClientInterface $client): Communicator
|
||||
{
|
||||
$this->client = $client;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function handleResponse(ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
if ($response->getStatusCode() < 200 or $response->getStatusCode() >= 300) {
|
||||
throw new HttpResponseException($response->getStatusCode(), $response->getReasonPhrase());
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
protected function request(string $method, string $uri, ?array $body = null): ResponseInterface
|
||||
{
|
||||
$options = [];
|
||||
if ($body !== null) {
|
||||
$options['headers'] = [
|
||||
'Content-Type' => 'application/json'
|
||||
];
|
||||
$options['body'] = json_encode($body);
|
||||
}
|
||||
return $this->handleResponse($this->getClient()->request($method, $uri, $options));
|
||||
}
|
||||
|
||||
public function get(string $uri): ResponseInterface
|
||||
{
|
||||
return $this->request('get', $uri);
|
||||
}
|
||||
public function post(string $uri, array $data): ResponseInterface
|
||||
{
|
||||
return $this->request('post', $uri, $data);
|
||||
}
|
||||
public function put(string $uri, array $data): ResponseInterface
|
||||
{
|
||||
return $this->request('put', $uri, $data);
|
||||
}
|
||||
public function delete(string $uri, array $data): ResponseInterface
|
||||
{
|
||||
return $this->request('delete', $uri, $data);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user