24
24
*/
25
25
final class IconFinder
26
26
{
27
- public function __construct (private Environment $ twig )
28
- {
27
+ public function __construct (
28
+ private Environment $ twig ,
29
+ private string $ iconDirectory ,
30
+ ) {
29
31
}
30
32
31
33
/**
@@ -35,42 +37,48 @@ public function icons(): array
35
37
{
36
38
$ found = [];
37
39
38
- foreach ($ this ->files ($ this ->twig ->getLoader ()) as $ file ) {
40
+ // https://regex101.com/r/WGa4iF/1
41
+ $ token = '[a-z0-9]+(?:-[a-z0-9]+)* ' ;
42
+ $ pattern = "#(?:' $ token: $ token')|(?: \"$ token: $ token \")#i " ;
43
+
44
+ // Extract icon names from strings in app templates
45
+ foreach ($ this ->templateFiles ($ this ->twig ->getLoader ()) as $ file ) {
39
46
$ contents = file_get_contents ($ file );
47
+ if (preg_match_all ($ pattern , $ contents , $ matches )) {
48
+ $ found [] = array_map (fn ($ res ) => trim ($ res , '" \'' ), $ matches [0 ]);
49
+ }
50
+ }
51
+ $ found = array_merge (...$ found );
40
52
41
- if (preg_match_all ('#[" \']([\w:-]+)[" \']# ' , $ contents , $ matches )) {
42
- $ found [] = $ matches [1 ];
53
+ // Extract prefix-less SVG files from the root of the icon directory
54
+ if (is_dir ($ this ->iconDirectory )) {
55
+ $ icons = (new Finder ())->files ()->in ($ this ->iconDirectory )->depth (0 )->name ('*.svg ' );
56
+ foreach ($ icons as $ icon ) {
57
+ $ found [] = $ icon ->getBasename ('.svg ' );
43
58
}
44
59
}
45
60
46
- return array_unique (array_merge (... $ found) );
61
+ return array_unique ($ found );
47
62
}
48
63
49
64
/**
50
65
* @return string[]
51
66
*/
52
- private function files (LoaderInterface $ loader ): iterable
67
+ private function templateFiles (LoaderInterface $ loader ): iterable
53
68
{
54
- $ files = [];
55
-
56
69
if ($ loader instanceof FilesystemLoader) {
70
+ $ paths = [];
57
71
foreach ($ loader ->getNamespaces () as $ namespace ) {
58
- foreach ($ loader ->getPaths ($ namespace ) as $ path ) {
59
- foreach ((new Finder ())->files ()->in ($ path )->name ('*.twig ' ) as $ file ) {
60
- $ file = (string ) $ file ;
61
- if (!\in_array ($ file , $ files , true )) {
62
- yield $ file ;
63
- }
64
-
65
- $ files [] = $ file ;
66
- }
67
- }
72
+ $ paths = [...$ paths , ...$ loader ->getPaths ($ namespace )];
73
+ }
74
+ foreach ((new Finder ())->files ()->in ($ paths )->name ('*.twig ' ) as $ file ) {
75
+ yield (string ) $ file ;
68
76
}
69
77
}
70
78
71
79
if ($ loader instanceof ChainLoader) {
72
80
foreach ($ loader ->getLoaders () as $ subLoader ) {
73
- yield from $ this ->files ($ subLoader );
81
+ yield from $ this ->templateFiles ($ subLoader );
74
82
}
75
83
}
76
84
}
0 commit comments