Files
remote_ip/app/common/Service/Ipify.php
2023-06-16 21:44:35 -04:00

28 lines
790 B
PHP

<?php
namespace ProVM\Service;
use Exception;
use Psr\Http\Client\ClientInterface;
use Psr\Log\LoggerInterface;
use function Safe\json_decode;
class Ipify
{
public function __construct(protected ClientInterface $client, protected LoggerInterface $logger) {}
public function get(): string
{
$this->logger->debug('Getting IP');
$response = $this->client->get('?format=json');
if (round($response->getCode() / 100, 0) !== 2) {
throw new Exception("Could not connect to '{$this->client->base_uri}'");
}
$body = $response->getBody();
$json = json_decode($body->getContents());
if (!isset($json->ip)) {
throw new Exception('Missing `ip` in JSON response');
}
return $json->ip;
}
}