diff --git a/index.php b/index.php index 921206e..52452ae 100644 --- a/index.php +++ b/index.php @@ -3,17 +3,41 @@ @include_once __DIR__ . '/vendor/autoload.php'; @include_once __DIR__ . '/src/webp.php'; +function shouldGenerateWebP($file) { + return $file->kirby()->option('kirby3-webp', false); +} + +function generateWebP($file) { + (new WebP\Convert)->generateWebP($file); +} + +function deleteWebPFiles($file) { + $webpFile = dirname($file->root()) . '/' . $file->name() . '.webp'; + $webpTxtFile = dirname($file->root()) . '/' . $file->name() . '.webp.txt'; + deleteIfExist($webpFile); + deleteIfExist($webpTxtFile); +} + +function deleteIfExist($file) { + if (F::exists($file)) { + F::remove($file); + } +} + Kirby::plugin('felixhaeberle/kirby3-webp', [ 'hooks' => [ 'file.create:after' => function ($file) { - if ($this->option('kirby3-webp', false)) { - (new WebP\Convert)->generateWebP($file); + if (shouldGenerateWebP($file)) { + generateWebP($file); } }, 'file.replace:after' => function ($newFile, $oldFile) { - if ($this->option('kirby3-webp', false)) { - (new WebP\Convert)->generateWebP($newFile); + if (shouldGenerateWebP($newFile)) { + generateWebP($newFile); } }, + 'file.delete:after' => function ($file) { + deleteWebPFiles($file); + }, ], ]); diff --git a/lib/Convert.php b/lib/Convert.php index 342fe0e..873c535 100644 --- a/lib/Convert.php +++ b/lib/Convert.php @@ -29,7 +29,7 @@ public function generateWebP($file) { try { // Checking file type since only images are processed - if ($file->type() == 'image') { + if (in_array($file->extension(), ['jpg', 'jpeg', 'png'])) { // WebPConvert options $path = $file->contentFileDirectory() . '/'; $input = $path . $file->filename();