From d4d8755735ed62063edff76d8948bd237623139d Mon Sep 17 00:00:00 2001 From: Arnaud Ligny Date: Thu, 14 Mar 2024 11:44:27 +0100 Subject: [PATCH] perf: cache WebP conversion (#1925) --- src/Assets/Asset.php | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Assets/Asset.php b/src/Assets/Asset.php index 03a2611cf..6b0c57d13 100644 --- a/src/Assets/Asset.php +++ b/src/Assets/Asset.php @@ -508,12 +508,19 @@ public function webp(?int $quality = null): self return $assetWebp; // returns the asset with the new extension ('webp') only: CDN do the rest of the job } - $img = ImageManager::make($assetWebp['content']); - $assetWebp['content'] = (string) $img->encode($format, $quality); - $img->destroy(); - $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']); - $assetWebp['subtype'] = "image/$format"; - $assetWebp['size'] = \strlen($assetWebp['content']); + $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); + $cacheKey = $cache->createKeyFromAsset($assetWebp, ["q$quality"]); + if (!$cache->has($cacheKey)) { + $img = ImageManager::make($assetWebp['content']); + $assetWebp['content'] = (string) $img->encode($format, $quality); + $img->destroy(); + $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']); + $assetWebp['subtype'] = "image/$format"; + $assetWebp['size'] = \strlen($assetWebp['content']); + + $cache->set($cacheKey, $assetWebp->data); + } + $assetWebp->data = $cache->get($cacheKey); return $assetWebp; }