Skip to content

Commit

Permalink
πŸ› Fix #76: file extension handling (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzzyfox authored Sep 27, 2024
1 parent 098b3e0 commit 01f1869
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/Actions/GenerateOgImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static function handle(string $mdPath): string
->setScreenshotType('webp', 85)
->screenshot();

$filename = Str::slug(str_replace('/', '-', $mdPath)).'.png';
$filename = Str::slug(str_replace('/', '-', $mdPath)).'.webp';
$filepath = 'images/ogimages/'.$filename;
Storage::disk(GetPrezetDisk::handle())->put($filepath, $screenshot);

Expand Down
11 changes: 6 additions & 5 deletions src/Actions/GetImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ class GetImage
{
public static function handle(string $path): string
{
self::validateFileExtension($path);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
self::validateFileExtension($extension);

$size = self::extractSize($path);
$path = self::removeSize($path);
Expand All @@ -21,13 +22,12 @@ public static function handle(string $path): string
$image = self::resizeImage($image, $size);
}

return self::outputImage($image, pathinfo($path, PATHINFO_EXTENSION));
return self::outputImage($image, $extension);
}

protected static function validateFileExtension(string $path): void
protected static function validateFileExtension(string $extension): void
{
$allowedExtensions = ['png', 'jpg', 'webp'];
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$allowedExtensions = ['png', 'jpg', 'jpeg', 'webp'];

if (! in_array($extension, $allowedExtensions)) {
abort(404, 'Invalid file extension');
Expand Down Expand Up @@ -99,6 +99,7 @@ private static function outputImage(GdImage $image, string $extension): string
imagepng($image);
break;
case 'jpg':
case 'jpeg':
imagejpeg($image);
break;
case 'webp':
Expand Down
6 changes: 5 additions & 1 deletion src/Http/Controllers/ImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ public function __invoke(Request $request, string $path): Response
$file = GetImage::handle($path);

return response($file, 200, [
'Content-Type' => 'image/webp',
'Content-Type' => match (pathinfo($path, PATHINFO_EXTENSION)) {
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
default => 'image/webp'
},
'Cache-Control' => 'public, max-age=31536000',
]);
}
Expand Down

0 comments on commit 01f1869

Please sign in to comment.