From 103a3d80a1df3c8a6aa6fe2852d8ce6688dd8d0c Mon Sep 17 00:00:00 2001 From: Jack McDade Date: Fri, 12 Mar 2021 09:38:47 -0500 Subject: [PATCH] SVG Assets now have heights and widths. References #2865. --- src/Assets/Dimensions.php | 47 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/Assets/Dimensions.php b/src/Assets/Dimensions.php index 3c4cc36fec..124d7c3f71 100644 --- a/src/Assets/Dimensions.php +++ b/src/Assets/Dimensions.php @@ -35,7 +35,13 @@ public function asset(Asset $asset) */ public function get() { - return $this->asset->isImage() ? $this->getImageDimensions() : [null, null]; + if ($this->asset->isImage()) { + return $this->getImageDimensions(); + } elseif ($this->asset->isSvg()) { + return $this->getSvgDimensions(); + } + + return [null, null]; } /** @@ -59,7 +65,7 @@ public function height() } /** - * Get the dimensions. + * Get the dimensions of an image. * * @return array */ @@ -87,6 +93,43 @@ private function getImageDimensions() return $size ? array_splice($size, 0, 2) : [null, null]; } + /** + * Get the dimensions of an SVG. + * + * @return array + */ + private function getSVGDimensions() + { + // Since assets may be located on external platforms like Amazon S3, we can't simply + // grab the dimensions. So we'll copy it locally and read the dimensions from there. + $manager = new MountManager([ + 'source' => $this->asset->disk()->filesystem()->getDriver(), + 'cache' => $cache = $this->getCacheFlysystem(), + ]); + + $cachePath = "{$this->asset->containerId()}/{$this->asset->path()}"; + + if ($manager->has($destination = "cache://{$cachePath}")) { + $manager->delete($destination); + } + + $manager->copy("source://{$this->asset->path()}", $destination); + + $svg = simplexml_load_file($cache->getAdapter()->getPathPrefix().$cachePath); + + $cache->delete($cachePath); + + if ($svg['width'] && $svg['height']) { + return [(int) $svg['width'], (int) $svg['height']]; + } elseif ($svg['viewBox']) { + $viewBox = preg_split('/[\s,]+/', $svg['viewBox'] ?: ''); + + return [$viewBox[2], $viewBox[3]]; + } + + return [null, null]; + } + private function getCacheFlysystem() { $disk = 'dimensions-cache';