2023-06-16 21:44:35 -04:00
|
|
|
<?php
|
|
|
|
namespace ProVM\Service;
|
|
|
|
|
|
|
|
use Exception;
|
|
|
|
use Psr\Http\Client\ClientInterface;
|
|
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
use function Safe\json_decode;
|
|
|
|
|
|
|
|
class Ipify
|
|
|
|
{
|
2023-06-16 22:35:41 -04:00
|
|
|
public function __construct(protected ClientInterface $client, protected string $uri, protected LoggerInterface $logger) {}
|
2023-06-16 21:44:35 -04:00
|
|
|
|
|
|
|
public function get(): string
|
|
|
|
{
|
|
|
|
$this->logger->debug('Getting IP');
|
|
|
|
$response = $this->client->get('?format=json');
|
2023-06-16 22:35:41 -04:00
|
|
|
if (round($response->getStatusCode() / 100, 0) != 2) {
|
|
|
|
throw new Exception("Could not connect to '{$this->uri}'");
|
2023-06-16 21:44:35 -04:00
|
|
|
}
|
|
|
|
$body = $response->getBody();
|
|
|
|
$json = json_decode($body->getContents());
|
|
|
|
if (!isset($json->ip)) {
|
|
|
|
throw new Exception('Missing `ip` in JSON response');
|
|
|
|
}
|
2023-06-18 19:20:06 -04:00
|
|
|
$this->logger->debug("Current IP: {$json->ip}");
|
2023-06-16 21:44:35 -04:00
|
|
|
return $json->ip;
|
|
|
|
}
|
|
|
|
}
|