Skip to content

Commit

Permalink
SVG Assets now have heights and widths. References #2865.
Browse files Browse the repository at this point in the history
  • Loading branch information
jackmcdade committed Mar 12, 2021
1 parent e38e6f9 commit 103a3d8
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions src/Assets/Dimensions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}

/**
Expand All @@ -59,7 +65,7 @@ public function height()
}

/**
* Get the dimensions.
* Get the dimensions of an image.
*
* @return array
*/
Expand Down Expand Up @@ -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';
Expand Down

0 comments on commit 103a3d8

Please sign in to comment.