Add single file

This commit is contained in:
philipp lang 2021-09-19 23:08:11 +02:00
parent 8013f66b42
commit 328e3784c1
4 changed files with 35 additions and 0 deletions

View File

@ -59,6 +59,8 @@ class Plugin extends PluginBase
return new ImageResizer($disk, $dir, $media); return new ImageResizer($disk, $dir, $media);
}); });
app()->bind('resize', fn () => app(CacheManager::class));
Event::listen('media.file.upload', function($widget, $filePath, $uploadedFile) { Event::listen('media.file.upload', function($widget, $filePath, $uploadedFile) {
if ((new MediaPath($filePath))->shouldProcess()) { if ((new MediaPath($filePath))->shouldProcess()) {
Queue::push(ResizeJob::class, [$filePath]); Queue::push(ResizeJob::class, [$filePath]);

View File

@ -49,4 +49,11 @@ class CacheManager
return "resizer.{$path->normal()}"; return "resizer.{$path->normal()}";
} }
public function biggestVersion(string $path, string $size): string
{
$path = new MediaPath($path);
return $this->tagGenerator->singleFile($path, $size);
}
} }

View File

@ -54,6 +54,7 @@ class TagGenerator {
} }
$result->push(collect([ $result->push(collect([
'path' => $version->get('path'),
'url' => $version->get('url'), 'url' => $version->get('url'),
'width' => $version->get('width'), 'width' => $version->get('width'),
'height' => $version->get('height'), '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) { private function htmlAttributes($attr) {
return $attr->map(function($value, $key) { return $attr->map(function($value, $key) {
return "{$key}=\"{$value}\""; return "{$key}=\"{$value}\"";

View File

@ -169,4 +169,18 @@ class ImageTagTest extends TestCase
$this->assertStringContainsString('sizes="(min-width: 200px) 10px, (min-width: 500px) 20px, 1rem"', $output); $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'),
);
}
} }