cdn.lewisdale.dev/src/Lib/SqliteImageDb.php

56 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace ImageResizer\Lib;
use ImageResizer\Models\Image;
use ImageResizer\Models\ResizeParams;
class SqliteImageDb implements ImageDb {
public function __construct(
private readonly \PDO $db
) {
$this->up();
}
private function up() {
$this->db->exec('CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
width INTEGER NULLABLE,
height INTEGER NULLABLE,
quality INTEGER NULLABLE,
content TEXT NOT NULL
)');
}
public function findImage(string $path, ResizeParams $params): Image | null {
$stmt = $this->db->prepare('SELECT * FROM images WHERE path = :path AND width = :width AND height = :height AND quality = :quality');
$stmt->execute([
':path' => $path,
':width' => $params->width,
':height' => $params->height,
':quality' => $params->quality
]);
$result = $stmt->fetchObject();
return $result ? Image::fromString(base64_decode($result->content)) : null;
}
public function saveImage(
string $path,
ResizeParams $params,
string $content,
): void {
$stmt = $this->db->prepare("INSERT INTO images (path, width, height, quality, content) VALUES (:path, :width, :height, :quality, :content)"
);
$stmt->execute([
':path' => $path,
':width' => $params->width,
':height' => $params->height,
':quality' => $params->quality,
':content' => $content
]);
}
}