From ffc17d5a34b458747341fe1d9376163741d55342 Mon Sep 17 00:00:00 2001 From: philipp lang Date: Wed, 28 Oct 2020 22:24:59 +0100 Subject: [PATCH] Add TagPresenter --- Plugin.php | 4 +++ classes/TagPresenter.php | 69 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 classes/TagPresenter.php diff --git a/Plugin.php b/Plugin.php index a4badbf..1f26c32 100644 --- a/Plugin.php +++ b/Plugin.php @@ -10,6 +10,7 @@ use Aweos\Resizer\Console\ResizeMake; use Illuminate\Support\Facades\Cache; use Aweos\Resizer\Console\ResizePurge; use Aweos\Resizer\FormWidgets\Responsiveimage; +use Aweos\Resizer\Classes\TagPresenter; /** * resizer Plugin Information File @@ -187,6 +188,9 @@ class Plugin extends PluginBase return 'src="'.$l->getPathUrl($media).'" '.$srcset.' '.$s.' '.$normalSize; }); + }, + 'responsiveimage' => function($id, $data = []) { + return (new TagPresenter($id, $data))->cacheOutput(); } ] ]; diff --git a/classes/TagPresenter.php b/classes/TagPresenter.php new file mode 100644 index 0000000..16be3bb --- /dev/null +++ b/classes/TagPresenter.php @@ -0,0 +1,69 @@ +attachment = Attachment::find($id); + $this->attrs = data_get($data, 'attrs'); + $this->breakpoints = data_get($data, 'breakpoints', []); + $this->sizes = Setting::get('srcx'); + } + + public function cacheOutput() { + return $this->output(); + } + + public function output() { + ksort($this->breakpoints); + + $files = collect(Storage::disk($this->disk)->files($this->attachment->path))->filter(function($file) { + return preg_match($this->attachment->versionRegex, $file); + })->map(function($file) { + $sizes = getimagesize(Storage::disk($this->disk)->path($file)); + + return collect([ + 'url' => Storage::disk($this->disk)->url($file), + 'width' => $sizes[0], + 'height' => $sizes[1] + ]); + })->sortBy('width'); + + if ($files->isEmpty()) { + return 'src="'.$this->attachment->url.'"'; + } + + $sizes = $files->map(function($file) { + return "(max-width: {$file->get('width')}px) {$file->get('width')}px"; + }); + + $srcset = $files->map(function($file) { + return "{$file->get('url')} {$file->get('width')}w"; + }); + + return $this->htmlAttributes(collect([ + 'width' => $files->last()->get('width'), + 'height' => $files->last()->get('height'), + 'sizes' => $sizes->implode(', '), + 'srcset' => $srcset->implode(', '), + 'alt' => $this->attachment->title + ])).' '.$this->attrs; + } + + private function htmlAttributes($attr) { + return $attr->map(function($value, $key) { + return "{$key}=\"{$value}\""; + })->implode(' '); + } +}