diff --git a/Plugin.php b/Plugin.php index 5631192..7762e22 100644 --- a/Plugin.php +++ b/Plugin.php @@ -59,6 +59,8 @@ class Plugin extends PluginBase return new ImageResizer($disk, $dir, $media); }); + app()->bind('resize', fn () => app(CacheManager::class)); + Event::listen('media.file.upload', function($widget, $filePath, $uploadedFile) { if ((new MediaPath($filePath))->shouldProcess()) { Queue::push(ResizeJob::class, [$filePath]); diff --git a/classes/CacheManager.php b/classes/CacheManager.php index bac4da3..55727e7 100644 --- a/classes/CacheManager.php +++ b/classes/CacheManager.php @@ -49,4 +49,11 @@ class CacheManager return "resizer.{$path->normal()}"; } + public function biggestVersion(string $path, string $size): string + { + $path = new MediaPath($path); + + return $this->tagGenerator->singleFile($path, $size); + } + } diff --git a/classes/TagGenerator.php b/classes/TagGenerator.php index 8f40312..4b58add 100644 --- a/classes/TagGenerator.php +++ b/classes/TagGenerator.php @@ -54,6 +54,7 @@ class TagGenerator { } $result->push(collect([ + 'path' => $version->get('path'), 'url' => $version->get('url'), 'width' => $version->get('width'), 'height' => $version->get('height'), @@ -99,6 +100,17 @@ class TagGenerator { ])); } + public function singleFile(MediaPath $path, ?string $ratio = 'original'): string + { + $this->path = $path; + + $versions = $this->possibleFiles($ratio); + + throw_unless(count($versions), Exception::class, "No files for {$path->root()} found"); + + return url($this->possibleFiles($ratio)->last()->get('url')); + } + private function htmlAttributes($attr) { return $attr->map(function($value, $key) { return "{$key}=\"{$value}\""; diff --git a/tests/ImageTagTest.php b/tests/ImageTagTest.php index ce60391..bb8dda9 100644 --- a/tests/ImageTagTest.php +++ b/tests/ImageTagTest.php @@ -169,4 +169,18 @@ class ImageTagTest extends TestCase $this->assertStringContainsString('sizes="(min-width: 200px) 10px, (min-width: 500px) 20px, 1rem"', $output); } + public function testItGeneratesOnlySingleImage() + { + Setting::set('folders', ['pages']); + Setting::set('sizes', []); + Setting::set('breakpoints', [100]); + $this->media->put('/pages/test.jpg', UploadedFile::fake()->image('test.jpg', 500, 500)->get()); + UploadedFile::fake()->image('test.jpg', 100, 100)->storeAs('uploads/public/c/pages', 'test-100x100.jpg', 'local'); + + $this->assertEquals( + url("/storage/uploads/public/c/pages/test-100x100.jpg"), + app('resize')->biggestVersion('pages/test.jpg', 'original'), + ); + } + }