Files
remote_ip/app/common/Service/Ipify.php
2023-06-18 19:20:06 -04:00

29 lines
862 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 string $uri, protected LoggerInterface $logger) {}
public function get(): string
{
$this->logger->debug('Getting IP');
$response = $this->client->get('?format=json');
if (round($response->getStatusCode() / 100, 0) != 2) {
throw new Exception("Could not connect to '{$this->uri}'");
}
$body = $response->getBody();
$json = json_decode($body->getContents());
if (!isset($json->ip)) {
throw new Exception('Missing `ip` in JSON response');
}
$this->logger->debug("Current IP: {$json->ip}");
return $json->ip;
}
}