Compare commits

...
12 Commits
Author SHA1 Message Date
Lewis Dale 519611d06b Fix it again 2023-08-27 22:12:28 +01:00
Lewis Dale a0580ad085 Enforce uniqueness 2023-08-27 22:03:56 +01:00
Lewis Dale e2cf30a307 Actually fix the query and caching 2023-08-27 22:01:43 +01:00
Lewis Dale a9e8b61e0b More logging for broken query 2023-08-27 21:47:16 +01:00
Lewis Dale 782c5b4b38 Fix query to handle null params 2023-08-27 21:45:28 +01:00
Lewis Dale 3949e611ea Fix broken database 2023-08-27 21:41:49 +01:00
Lewis Dale 9164929969 Debuggy time 2023-08-27 21:36:01 +01:00
Lewis Dale 16e0a8f381 Fixed the logger 2023-08-27 21:32:27 +01:00
Lewis Dale 69d8ec33a5 Gitignore logs 2023-08-26 19:19:35 +01:00
Lewis Dale 967beadeb3 Add a cache-control header for the images so that the browser caches the image for a day 2023-08-26 19:15:54 +01:00
Lewis Dale 6f23c71773 Actually add the logging 2023-08-26 19:12:29 +01:00
Lewis Dale be8d37d4cb Revert "Revert "Add logging & some better error handling""
This reverts commit a1ac9edadc.
2023-08-26 19:11:30 +01:00
8 changed files with 123 additions and 16 deletions

No files matched your search

+2 -1
View File
@@ -1,4 +1,5 @@
/.env
/vendor/
/*.db
/.idea/
/.idea/
/*.log
+2 -1
View File
@@ -6,7 +6,8 @@
"vlucas/phpdotenv": "^5.5",
"ext-gd": "*",
"ext-pdo": "*",
"ext-pdo_sqlite": "*"
"ext-pdo_sqlite": "*",
"psr/log": "^3.0"
},
"autoload": {
"psr-4": {
Generated
+51 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "35cc1fc18887fe14e702beb8a8486527",
"content-hash": "2269f5deec22d5f78ed3c229cddb1359",
"packages": [
{
"name": "graham-campbell/result-type",
@@ -384,6 +384,56 @@
},
"time": "2021-11-05T16:47:00+00:00"
},
{
"name": "psr/log",
"version": "3.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001",
"reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001",
"shasum": ""
},
"require": {
"php": ">=8.0.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Log\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
],
"support": {
"source": "https://github.com/php-fig/log/tree/3.0.0"
},
"time": "2021-07-14T16:46:02+00:00"
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.27.0",
+14 -3
View File
@@ -3,18 +3,29 @@ error_reporting(E_ERROR | E_PARSE);
require_once './vendor/autoload.php';
use ImageResizer\Lib\FileLogger;
use ImageResizer\Lib\Resizer;
use ImageResizer\Lib\SqliteImageDb;
use ImageResizer\Models\ResizeParams;
$logger = new FileLogger("resizer.log");
$dotenv = Dotenv\Dotenv::createImmutable([__DIR__, __DIR__ . "/.."]);
$dotenv->load();
$imageDb = new SqliteImageDb(new PDO("sqlite:{$_ENV["db_name"]}"));
$pdo = new PDO("sqlite:".$_ENV["DB_NAME"]);
$imageDb = new SqliteImageDb($pdo, $logger);
$imgPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$params = new ResizeParams($_GET);
$resizer = new Resizer($imageDb);
$resizer = new Resizer($imageDb, $logger);
echo $resizer->performResize($imgPath, $params);
try {
$image = $resizer->performResize($imgPath, $params);
header("Cache-Control: max-age=86400, public");
echo $image;
} catch (\Exception $e) {
$logger->error($e->getMessage(), ['exception' => $e, 'path' => $imgPath, 'params' => $params]);
http_response_code(500);
echo "Internal Server Error";
}
+21
View File
@@ -0,0 +1,21 @@
<?php declare(strict_types=1);
namespace ImageResizer\Lib;
use DateTime;
use Psr\Log\AbstractLogger;
use Stringable;
class FileLogger extends AbstractLogger
{
function __construct(private readonly string $filename = 'php://stdout') {}
public function log($level, Stringable|string $message, array $context = []): void
{
$timestamp = new DateTime();
$callingClass = debug_backtrace()[2]['class'];
$callingFunction = debug_backtrace()[2]['function'];
$log = $timestamp->format(DATE_ATOM) . " [$level] $callingClass::$callingFunction $message " . json_encode($context);
fwrite(fopen($this->filename, 'a'), $log . PHP_EOL);
}
}
+8 -2
View File
@@ -6,10 +6,13 @@ namespace ImageResizer\Lib;
use ImageResizer\Models\ResizeParams;
use ImageResizer\Models\Image;
use Psr\Log\AbstractLogger;
class Resizer
{
public function __construct(
private readonly ImageDb $imageDb
private readonly ImageDb $imageDb,
private readonly AbstractLogger $logger,
)
{}
@@ -20,7 +23,7 @@ class Resizer
{
// Check if the image has already been processed
if ($image = $this->imageDb->findImage($path, $params)) {
$this->logger->info("Found existing image", ['path'=>$path, 'params'=>$params]);
header("Content-type: {${$image->getMime()}}");
return base64_decode($image->encode(75));
}
@@ -28,6 +31,7 @@ class Resizer
// Fetch the image at the given URL
$original_img = Image::fromUrl($_ENV['ROOT_DOMAIN'] . $path);
$converted = $this->createVariant($original_img, $params);
$this->logger->info("Created variant", ['path'=>$path, 'params'=>$params]);
// Store the image in the database
$this->imageDb->saveImage(
@@ -35,6 +39,7 @@ class Resizer
$params,
$converted
);
$this->logger->info("Saved image", ['path'=>$path, 'params'=>$params]);
header("Content-type: {$original_img->getMime()}");
return base64_decode($converted);
@@ -43,6 +48,7 @@ class Resizer
private function createVariant(Image $original, ResizeParams $params): string
{
$quality = $params->quality ?: -1;
$this->logger->info("Resizing image", ['params'=>$params]);
$original->toWidth($params->width ?? intval($_ENV["DEFAULT_WIDTH"]));
+24 -7
View File
@@ -5,10 +5,12 @@ namespace ImageResizer\Lib;
use ImageResizer\Models\Image;
use ImageResizer\Models\ResizeParams;
use Psr\Log\AbstractLogger;
class SqliteImageDb implements ImageDb {
public function __construct(
private readonly \PDO $db
private readonly \PDO $db,
private readonly AbstractLogger $logger,
) {
$this->up();
}
@@ -22,16 +24,31 @@ class SqliteImageDb implements ImageDb {
quality INTEGER NULLABLE,
content TEXT NOT NULL
)');
// Create a unique index on the path and params
$this->db->exec('CREATE UNIQUE INDEX IF NOT EXISTS images_path_width_height_quality ON images (path, width, height, quality)');
}
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([
$query = 'SELECT * FROM images WHERE path = :path';
$query .= $params->width ? ' AND width = :width' : ' AND width IS NULL';
$query .= $params->height ? ' AND height = :height' : ' AND height IS NULL';
$query .= $params->quality ? ' AND quality = :quality' : ' AND quality IS NULL';
$stmt = $this->db->prepare($query);
$queryParams = [
':path' => $path,
':width' => $params->width,
':height' => $params->height,
':quality' => $params->quality
]);
];
if ($params->width !== null) $queryParams[':width'] = $params->width;
if ($params->height !== null) $queryParams[':height'] = $params->height;
if ($params->quality !== null) $queryParams[':quality'] = $params->quality;
$stmt->execute($queryParams);
$this->logger->info("Querying images", ['query' => $stmt->queryString]);
$stmt->execute();
$result = $stmt->fetchObject();
+1 -1
View File
@@ -12,7 +12,7 @@ class ResizeParams
public function __construct(array $params)
{
$this->width = intval($params['width']) ?: intval($_ENV["DEFAULT_WIDTH"]);
$this->width = isset($params['width']) ? intval($params['width']) : intval($_ENV["DEFAULT_WIDTH"]);
$this->height = intval($params['height']) ?: null;
$this->quality = isset($params['quality']) ? intval($params['quality']) : null;
}