1
+ <?php
2
+
3
+ class FontAwesomeSVG {
4
+
5
+ public $ svg_dir ;
6
+
7
+ public function __construct ($ svg_dir ) {
8
+ $ this ->svg_dir = $ svg_dir ;
9
+ }
10
+
11
+
12
+
13
+
14
+ /**
15
+ *
16
+ */
17
+ public function get_svg ($ id , $ opts =false ) {
18
+ try {
19
+ $ icon = $ this ->get_icon_details ($ id );
20
+ } catch (Exception $ e ) {
21
+ return false ;
22
+ }
23
+
24
+ $ doc = new DOMDocument ();
25
+ $ doc ->load ($ icon ['filepath ' ]);
26
+
27
+ $ default_opts = [
28
+ 'title ' => false ,
29
+ 'class ' => false ,
30
+ 'default_class ' => true ,
31
+ 'role ' => 'img ' ,
32
+ ];
33
+
34
+ if (is_array ($ opts )) {
35
+ $ opts = array_merge ($ default_opts , $ opts );
36
+ } else {
37
+ $ opts = $ default_opts ;
38
+ }
39
+
40
+
41
+
42
+ $ classes = '' ;
43
+ if ($ opts ['default_class ' ]) {
44
+ $ classes .= 'svg-inline--fa ' ;
45
+ }
46
+ if ($ opts ['class ' ]) {
47
+ $ classes .= ' ' . $ opts ['class ' ];
48
+ }
49
+
50
+
51
+ foreach ($ doc ->getElementsByTagName ('svg ' ) as $ item ) {
52
+ if ($ classes != '' ) $ item ->setAttribute ('class ' , $ classes );
53
+ if ($ opts ['role ' ]) $ item ->setAttribute ('role ' , $ opts ['role ' ]);
54
+
55
+
56
+ if ($ opts ['title ' ]) {
57
+ $ title = $ doc ->createElement ("title " );
58
+ $ title ->nodeValue = $ opts ['title ' ];
59
+
60
+ // TODO: add aria-labelledby
61
+ //$title->setAttribute('id', '');
62
+ //$item->setAttribute('aria-labelledby', '');
63
+
64
+ $ item ->appendChild ($ title );
65
+ } else {
66
+ $ item ->setAttribute ('aria-hidden ' , 'true ' );
67
+ }
68
+ }
69
+
70
+ return $ doc ->saveHTML ();
71
+ }
72
+
73
+
74
+
75
+
76
+ /**
77
+ *
78
+ */
79
+ public function get_icon_details ($ id ) {
80
+ $ icon = array ();
81
+
82
+ $ id = explode (' ' , $ id );
83
+ $ dir = $ this ->get_icon_dir ($ id [0 ]);
84
+ $ filename = $ this ->get_icon_filename ($ id [1 ]);
85
+
86
+ $ icon ['dir ' ] = $ dir ;
87
+ $ icon ['filename ' ] = $ filename ;
88
+ $ icon ['filepath ' ] = str_replace ('/ ' , DIRECTORY_SEPARATOR , "$ this ->svg_dir / $ dir/ $ filename.svg " );
89
+
90
+ if (!is_file ($ icon ['filepath ' ])) {
91
+ throw new Exception ('File ' . $ icon ['filepath ' ] . ' does not exist. ' );
92
+ }
93
+
94
+ return $ icon ;
95
+ }
96
+
97
+
98
+
99
+
100
+ /**
101
+ *
102
+ */
103
+ public function get_icon_dir ($ iconID ) {
104
+ switch ($ iconID ) {
105
+ case 'fas ' :
106
+ $ dir = 'solid ' ;
107
+ break ;
108
+
109
+ case 'far ' :
110
+ $ dir = 'regular ' ;
111
+ break ;
112
+
113
+ case 'fal ' :
114
+ $ dir = 'light ' ;
115
+ break ;
116
+
117
+ case 'fab ' :
118
+ $ dir = 'brands ' ;
119
+ break ;
120
+
121
+ default :
122
+ $ dir = 'solid ' ;
123
+ }
124
+
125
+ return $ dir ;
126
+ }
127
+
128
+
129
+
130
+
131
+ /**
132
+ *
133
+ */
134
+ public function get_icon_filename ($ icon_name ) {
135
+ return str_replace ('fa- ' , '' , $ icon_name );
136
+ }
137
+ }
0 commit comments