90 lines
3.1 KiB
PHP
90 lines
3.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domovoy\Repositories;
|
|
|
|
use Domovoy\Models\Credential;
|
|
use PDO;
|
|
|
|
class CredentialRepository
|
|
{
|
|
public function __construct(private PDO $pdo)
|
|
{
|
|
}
|
|
|
|
public function findByDevice(int $deviceId): array
|
|
{
|
|
$stmt = $this->pdo->prepare('SELECT * FROM credentials WHERE device_id = :device_id ORDER BY name ASC');
|
|
$stmt->execute(['device_id' => $deviceId]);
|
|
$results = [];
|
|
while ($row = $stmt->fetch()) {
|
|
$results[] = Credential::fromArray($row);
|
|
}
|
|
return $results;
|
|
}
|
|
|
|
public function findById(int $id): ?Credential
|
|
{
|
|
$stmt = $this->pdo->prepare('SELECT * FROM credentials WHERE id = :id');
|
|
$stmt->execute(['id' => $id]);
|
|
$row = $stmt->fetch();
|
|
return $row ? Credential::fromArray($row) : null;
|
|
}
|
|
|
|
public function save(Credential $credential): void
|
|
{
|
|
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
|
|
$stmt = $this->pdo->prepare(
|
|
'INSERT INTO credentials
|
|
(device_id, type, name, username, port, auth_method, encrypted_secret,
|
|
encrypted_private_key, public_key_fingerprint, last_test_status,
|
|
last_test_at, created_at, updated_at)
|
|
VALUES
|
|
(:device_id, :type, :name, :username, :port, :auth_method, :encrypted_secret,
|
|
:encrypted_private_key, :public_key_fingerprint, :last_test_status,
|
|
:last_test_at, :created_at, :updated_at)'
|
|
);
|
|
$stmt->execute([
|
|
'device_id' => $credential->deviceId,
|
|
'type' => $credential->type,
|
|
'name' => $credential->name,
|
|
'username' => $credential->username,
|
|
'port' => $credential->port,
|
|
'auth_method' => $credential->authMethod,
|
|
'encrypted_secret' => $credential->encryptedSecret,
|
|
'encrypted_private_key' => $credential->encryptedPrivateKey,
|
|
'public_key_fingerprint' => $credential->publicKeyFingerprint,
|
|
'last_test_status' => $credential->lastTestStatus,
|
|
'last_test_at' => $credential->lastTestAt?->format('Y-m-d H:i:s'),
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
$credential->id = (int)$this->pdo->lastInsertId();
|
|
}
|
|
|
|
public function updateTestResult(int $id, string $status): void
|
|
{
|
|
$stmt = $this->pdo->prepare(
|
|
'UPDATE credentials SET last_test_status = :last_test_status,
|
|
last_test_at = :last_test_at, updated_at = :updated_at WHERE id = :id'
|
|
);
|
|
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
|
|
$stmt->execute([
|
|
'id' => $id,
|
|
'last_test_status' => $status,
|
|
'last_test_at' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
}
|
|
|
|
public function deleteForDevice(int $id, int $deviceId): void
|
|
{
|
|
$stmt = $this->pdo->prepare('DELETE FROM credentials WHERE id = :id AND device_id = :device_id');
|
|
$stmt->execute([
|
|
'id' => $id,
|
|
'device_id' => $deviceId,
|
|
]);
|
|
}
|
|
}
|