You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

98 lines
2.5 KiB

  1. <?php
  2. /**
  3. * SVG PHP Helper
  4. *
  5. * Based on https://github.com/chteuchteu/MaterialDesignIcons-PHP
  6. *
  7. * @author Giuseppe Di Terlizzi <giuseppe.diterlizzi@gmail.com>
  8. * @license MIT, GPLv2
  9. */
  10. namespace dokuwiki\template\bootstrap3;
  11. class SVG
  12. {
  13. public static $iconsPath;
  14. public static $defaultAttributes = array();
  15. /**
  16. * Add icon
  17. *
  18. * @param string $icon Icon name or full path
  19. * @param string $class Icon Class
  20. * @param int $size Icon size
  21. * @param array $attrs Icon attributes
  22. *
  23. * @return string
  24. */
  25. public static function icon($icon, $class = null, $size = 24, $attrs = array())
  26. {
  27. // Find the icon, ensure it exists
  28. if (file_exists($icon)) {
  29. $file_path = $icon;
  30. } else {
  31. $file_path = self::$iconsPath . $icon . '.svg';
  32. }
  33. if (!is_file($file_path)) {
  34. msg(sprintf('Unrecognized icon "%s" (svg file "%s" does not exist).', $icon, $file_path), -1);
  35. return false;
  36. }
  37. // Read the file
  38. $svg = file_get_contents($file_path);
  39. // Only keep the <path d="..." /> part
  40. // Old REGEX: (<path d=".+" \/>)
  41. if (preg_match('/((<path\b([\s\S]*?)\/>)|(<path\b([\s\S]*?)><\/path>))/', $svg, $matches) !== 1) {
  42. msg(sprintf('"%s" could not be recognized as an icon file', $file_path), -1);
  43. return false;
  44. }
  45. $svg = $matches[1];
  46. // Add some (clean) attributes
  47. $attributes = array_merge(
  48. array(
  49. 'viewBox' => '0 0 24 24',
  50. 'xmlns' => 'http://www.w3.org/2000/svg',
  51. 'width' => $size,
  52. 'height' => $size,
  53. 'role' => 'presentation',
  54. ),
  55. self::$defaultAttributes,
  56. $attrs
  57. );
  58. if ($class !== null) {
  59. $attributes['class'] = $class;
  60. }
  61. // Remove possibly empty-ish attributes (self::$defaultAttributes or $attrs may contain null values)
  62. $attributes = array_filter($attributes);
  63. return sprintf(
  64. '<svg %s>%s</svg>',
  65. self::attributes($attributes),
  66. $svg
  67. );
  68. }
  69. /**
  70. * Turns a 1-dimension array into an HTML-ready attributes set.
  71. */
  72. private static function attributes($attrs = array())
  73. {
  74. return implode(' ', array_map(
  75. function ($val, $key) {
  76. return $key . '="' . htmlspecialchars($val) . '"';
  77. },
  78. $attrs,
  79. array_keys($attrs)
  80. ));
  81. }
  82. }