From a4ba1b4163c86804ee575a3182940db419f52a35 Mon Sep 17 00:00:00 2001 From: kpitn Date: Fri, 28 Jun 2024 16:50:19 +0200 Subject: [PATCH] feat: Add getViewFilePath --- ViewModel/ImageDisplay.php | 63 ++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/ViewModel/ImageDisplay.php b/ViewModel/ImageDisplay.php index cd33a23..81d4ab5 100644 --- a/ViewModel/ImageDisplay.php +++ b/ViewModel/ImageDisplay.php @@ -4,6 +4,11 @@ namespace Web200\ImageResize\ViewModel; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\State; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Filesystem; +use Magento\Framework\View\Asset\Repository; use Magento\Framework\View\Element\Block\ArgumentInterface; use Web200\ImageResize\Model\Display; @@ -18,22 +23,20 @@ */ class ImageDisplay implements ArgumentInterface { - /** - * Display - * - * @var Display $display - */ - protected $display; - /** * ImageDisplay constructor. * - * @param Display $display + * @param Display $display + * @param Repository $assetRepository + * @param Filesystem $filesystem + * @param State $state */ public function __construct( - Display $display + protected Display $display, + protected Repository $assetRepository, + protected Filesystem $filesystem, + protected State $state ) { - $this->display = $display; } /** @@ -45,4 +48,44 @@ public function getDisplay(): Display { return $this->display; } + + /** + * @param $imagePath + * + * @return string + * @throws LocalizedException + */ + public function getViewFilePath($imagePath): string + { + if ($this->isDeveloperMode()) { + return $this->getViewFileUrl($imagePath); + } + $asset = $this->assetRepository->createAsset($imagePath); + $directoryRead = $this->filesystem->getDirectoryRead(DirectoryList::STATIC_VIEW); + return $directoryRead->getAbsolutePath($asset->getPath()); + } + + /** + * @return bool + */ + public function isDeveloperMode(): bool + { + return $this->state->getMode() == State::MODE_DEVELOPER; + } + + /** + * Retrieve url of a view file + * + * @param string $fileId + * + * @return string + */ + public function getViewFileUrl(string $fileId) + { + try { + return $this->assetRepository->getUrl($fileId); + } catch (LocalizedException $e) { + return ''; + } + } }