94 lines
2.3 KiB
PHP
94 lines
2.3 KiB
PHP
<?php
|
|
namespace ProVM\Service;
|
|
|
|
use HttpResponseException;
|
|
use Psr\Http\Client\ClientInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
use Safe\Exceptions\JsonException;
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
*/
|
|
protected function handleResponse(ResponseInterface $response): ResponseInterface
|
|
{
|
|
if ($response->getStatusCode() < 200 or $response->getStatusCode() >= 300) {
|
|
throw new HttpResponseException($response->getStatusCode(), $response->getReasonPhrase());
|
|
}
|
|
return $response;
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
* @throws JsonException
|
|
*/
|
|
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));
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
* @throws JsonException
|
|
*/
|
|
public function get(string $uri): ResponseInterface
|
|
{
|
|
return $this->request('get', $uri);
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
* @throws JsonException
|
|
*/
|
|
public function post(string $uri, array $data): ResponseInterface
|
|
{
|
|
return $this->request('post', $uri, $data);
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
* @throws JsonException
|
|
*/
|
|
public function put(string $uri, array $data): ResponseInterface
|
|
{
|
|
return $this->request('put', $uri, $data);
|
|
}
|
|
|
|
/**
|
|
* @throws HttpResponseException
|
|
* @throws JsonException
|
|
*/
|
|
public function delete(string $uri, array $data): ResponseInterface
|
|
{
|
|
return $this->request('delete', $uri, $data);
|
|
}
|
|
}
|