VectorImageMedium.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * @package Grav\Common\Page
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Page\Medium;
  9. use Grav\Common\Data\Blueprint;
  10. /**
  11. * Class StaticImageMedium
  12. * @package Grav\Common\Page\Medium
  13. */
  14. class VectorImageMedium extends StaticImageMedium
  15. {
  16. /**
  17. * Construct.
  18. *
  19. * @param array $items
  20. * @param Blueprint|null $blueprint
  21. */
  22. public function __construct($items = [], Blueprint $blueprint = null)
  23. {
  24. parent::__construct($items, $blueprint);
  25. // If we already have the image size, we do not need to do anything else.
  26. $width = $this->get('width');
  27. $height = $this->get('height');
  28. if ($width && $height) {
  29. return;
  30. }
  31. // Make sure that getting image size is supported.
  32. if ($this->mime !== 'image/svg+xml' || !\extension_loaded('simplexml')) {
  33. return;
  34. }
  35. // Make sure that the image exists.
  36. $path = $this->get('filepath');
  37. if (!$path || !file_exists($path) || !filesize($path)) {
  38. return;
  39. }
  40. $xml = simplexml_load_string(file_get_contents($path));
  41. $attr = $xml ? $xml->attributes() : null;
  42. if (!$attr instanceof \SimpleXMLElement) {
  43. return;
  44. }
  45. // Get the size from svg image.
  46. if ($attr->width && $attr->height) {
  47. $width = (string)$attr->width;
  48. $height = (string)$attr->height;
  49. } elseif ($attr->viewBox && \count($size = explode(' ', (string)$attr->viewBox)) === 4) {
  50. [,$width,$height,] = $size;
  51. }
  52. if ($width && $height) {
  53. $this->def('width', (int)$width);
  54. $this->def('height', (int)$height);
  55. }
  56. }
  57. }