Files
emails/cli/common/Service/Communicator.php
2023-06-12 21:14:07 -04:00

77 lines
2.0 KiB
PHP

<?php
namespace ProVM\Service;
use HttpResponseException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Safe\Exceptions\JsonException;
use function Safe\json_encode;
class Communicator
{
public function __construct(protected ClientInterface $client) {}
/**
* @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->client->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);
}
}