/
Mdi.php
114 lines (94 loc) · 3.11 KB
/
Mdi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
/**
* MDI PHP Helper
*
* Based on https://github.com/chteuchteu/MaterialDesignIcons-PHP
*
* @author Giuseppe Di Terlizzi <giuseppe.diterlizzi@gmail.com>
* @license MIT, GPLv2
*/
class Mdi
{
public static $iconsPath;
public static $defaultAttributes = array();
/**
* Add icon
*
* @param string $icon Icon name or full path
* @param string $class Icon Class
* @param int $size Icon size
* @param array $attrs Icon attributes
*
* @return string
*/
public static function icon($icon, $class = null, $size = 24, $attrs = array())
{
// Ensure that the icons path has been specified, or auto-detect it
if (!self::$iconsPath) {
msg('You forgot to specify MDI\'s path!', -1);
return false;
}
// Strip leading "mdi mdi-" or "mdi-"
if (strpos($icon, 'mdi mdi-') === 0) {
$icon = substr($icon, \strlen('mdi mdi-'));
}
if (strpos($icon, 'mdi-') === 0) {
$icon = substr($icon, \strlen('mdi-'));
}
// Find the icon, ensure it exists
if (file_exists($icon)) {
$file_path = $icon;
} else {
$file_path = self::$iconsPath . $icon . '.svg';
}
if (!is_file($file_path)) {
msg(sprintf('Unrecognized icon "%s" (svg file "%s" does not exist).', $icon, $file_path), -1);
return false;
}
// Read the file
$svg = file_get_contents($file_path);
// Only keep the <path d="..." /> part
// Old REGEX: (<path d=".+" \/>)
if (preg_match('/(<path\b([\s\S]*?)\/>)/', $svg, $matches) !== 1) {
msg(sprintf('"%s" could not be recognized as an icon file', $file_path), -1);
return false;
}
$svg = $matches[1];
// Add some (clean) attributes
$attributes = array_merge(
array(
'viewBox' => '0 0 24 24',
'xmlns' => 'http://www.w3.org/2000/svg',
'width' => $size,
'height' => $size,
'role' => 'presentation',
),
self::$defaultAttributes,
$attrs
);
if ($class !== null) {
$attributes['class'] = $class;
}
// Remove possibly empty-ish attributes (self::$defaultAttributes or $attrs may contain null values)
$attributes = array_filter($attributes);
return sprintf(
'<svg %s>%s</svg>',
self::attributes($attributes),
$svg
);
}
/**
* Turns a 1-dimension array into an HTML-ready attributes set.
*/
private static function attributes($attrs = array())
{
return implode(' ', array_map(
function ($val, $key) {
return $key . '="' . htmlspecialchars($val) . '"';
},
$attrs,
array_keys($attrs)
));
}
}
// kate: space-indent on; indent-width 4; replace-tabs on;