domovoy/app/Repositories/NetworkRangeRepository.php

84 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Domovoy\Repositories;
use Domovoy\Models\NetworkRange;
use PDO;
class NetworkRangeRepository
{
private PDO $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function findById(int $id): ?NetworkRange
{
$stmt = $this->pdo->prepare('SELECT * FROM network_ranges WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row ? NetworkRange::fromArray($row) : null;
}
public function findAll(): array
{
$stmt = $this->pdo->query('SELECT * FROM network_ranges ORDER BY name ASC');
$results = [];
while ($row = $stmt->fetch()) {
$results[] = NetworkRange::fromArray($row);
}
return $results;
}
public function findEnabled(): array
{
$stmt = $this->pdo->prepare('SELECT * FROM network_ranges WHERE enabled = 1 ORDER BY name ASC');
$stmt->execute();
$results = [];
while ($row = $stmt->fetch()) {
$results[] = NetworkRange::fromArray($row);
}
return $results;
}
public function save(NetworkRange $range): void
{
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
if ($range->id === null) {
$stmt = $this->pdo->prepare(
'INSERT INTO network_ranges (name, cidr, enabled, created_at, updated_at)
VALUES (:name, :cidr, :enabled, :created_at, :updated_at)'
);
$stmt->execute([
'name' => $range->name,
'cidr' => $range->cidr,
'enabled' => $range->enabled ? 1 : 0,
'created_at' => $now,
'updated_at' => $now,
]);
$range->id = (int)$this->pdo->lastInsertId();
} else {
$stmt = $this->pdo->prepare(
'UPDATE network_ranges SET name = :name, cidr = :cidr, enabled = :enabled, updated_at = :updated_at WHERE id = :id'
);
$stmt->execute([
'id' => $range->id,
'name' => $range->name,
'cidr' => $range->cidr,
'enabled' => $range->enabled ? 1 : 0,
'updated_at' => $now,
]);
}
}
public function delete(int $id): void
{
$stmt = $this->pdo->prepare('DELETE FROM network_ranges WHERE id = :id');
$stmt->execute(['id' => $id]);
}
}