v0.5.0
This commit is contained in:
27
app/common/Service/Ipify.php
Normal file
27
app/common/Service/Ipify.php
Normal file
@ -0,0 +1,27 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
13
app/common/Service/Remote.php
Normal file
13
app/common/Service/Remote.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace ProVM\Service;
|
||||
|
||||
class Remote
|
||||
{
|
||||
public function __construct(protected Ipify $ipService, protected Repository $dbService) {}
|
||||
|
||||
public function update(): void
|
||||
{
|
||||
$ip = $this->ipService->get();
|
||||
$this->dbService->update($ip);
|
||||
}
|
||||
}
|
41
app/common/Service/Repository.php
Normal file
41
app/common/Service/Repository.php
Normal file
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
namespace ProVM\Service;
|
||||
|
||||
use PDO;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Repository
|
||||
{
|
||||
public function __construct(protected PDO $connection, protected string $table, protected LoggerInterface $logger) {}
|
||||
|
||||
public function update(string $ip): void
|
||||
{
|
||||
$this->logger->debug('Updating Database');
|
||||
|
||||
$old_ip = $this->getOld();
|
||||
$this->logger->debug($old_ip);
|
||||
|
||||
if ($old_ip === $ip) {
|
||||
$this->logger->debug('No change in IP');
|
||||
return;
|
||||
}
|
||||
|
||||
$this->doUpdate();
|
||||
$this->logger->debug('Updated IP');
|
||||
}
|
||||
|
||||
protected function getOld(): string
|
||||
{
|
||||
$query = "SELECT `ip` FROM `{$this->table}` WHERE `host` = ?";
|
||||
$statement = $this->connection->prepare($query);
|
||||
$statement->execute(['vialdelamaza']);
|
||||
|
||||
return $statement->fetch()['ip'];
|
||||
}
|
||||
protected function doUpdate(string $ip): void
|
||||
{
|
||||
$query = "UPDATE `remote_ip` SET `ip` = ?, `updated` = CURRENT_TIMESTAMP() WHERE `host` = ?";
|
||||
$statement = $this->connection->prepare($query);
|
||||
$statement->execute([$ip, 'vialdelamaza']);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user