14
14
use Symfony \Component \HttpClient \Exception \JsonException ;
15
15
use Symfony \Component \HttpClient \HttpClient ;
16
16
use Symfony \Component \HttpClient \ScopingHttpClient ;
17
+ use Symfony \Contracts \Cache \CacheInterface ;
17
18
use Symfony \Contracts \HttpClient \HttpClientInterface ;
18
19
use Symfony \UX \Icons \Exception \IconNotFoundException ;
19
20
use Symfony \UX \Icons \Svg \Icon ;
26
27
final class Iconify
27
28
{
28
29
private HttpClientInterface $ http ;
30
+ private \ArrayObject $ sets ;
29
31
30
32
public function __construct (
33
+ private CacheInterface $ cache ,
31
34
string $ endpoint = 'https://api.iconify.design ' ,
32
35
?HttpClientInterface $ http = null ,
33
36
) {
@@ -40,13 +43,15 @@ public function __construct(
40
43
41
44
public function metadataFor (string $ prefix ): array
42
45
{
43
- $ response = $ this ->http ->request ('GET ' , sprintf ('/collections?prefix=%s ' , $ prefix ));
44
-
45
- return $ response ->toArray ()[$ prefix ] ?? throw new \RuntimeException (sprintf ('The icon prefix "%s" does not exist on iconify.design. ' , $ prefix ));
46
+ return $ this ->sets ()[$ prefix ] ?? throw new \RuntimeException (sprintf ('The icon prefix "%s" does not exist on iconify.design. ' , $ prefix ));
46
47
}
47
48
48
49
public function fetchIcon (string $ prefix , string $ name ): Icon
49
50
{
51
+ if (!isset ($ this ->sets ()[$ prefix ])) {
52
+ throw new IconNotFoundException (sprintf ('The icon "%s:%s" does not exist on iconify.design. ' , $ prefix , $ name ));
53
+ }
54
+
50
55
$ response = $ this ->http ->request ('GET ' , sprintf ('/%s.json?icons=%s ' , $ prefix , $ name ));
51
56
52
57
try {
@@ -66,6 +71,10 @@ public function fetchIcon(string $prefix, string $name): Icon
66
71
67
72
public function fetchSvg (string $ prefix , string $ name ): string
68
73
{
74
+ if (!isset ($ this ->sets ()[$ prefix ])) {
75
+ throw new IconNotFoundException (sprintf ('The icon "%s:%s" does not exist on iconify.design. ' , $ prefix , $ name ));
76
+ }
77
+
69
78
$ content = $ this ->http
70
79
->request ('GET ' , sprintf ('/%s/%s.svg ' , $ prefix , $ name ))
71
80
->getContent ()
@@ -77,4 +86,13 @@ public function fetchSvg(string $prefix, string $name): string
77
86
78
87
return $ content ;
79
88
}
89
+
90
+ private function sets (): \ArrayObject
91
+ {
92
+ return $ this ->sets ??= $ this ->cache ->get ('ux-iconify-sets ' , function () {
93
+ $ response = $ this ->http ->request ('GET ' , '/collections ' );
94
+
95
+ return new \ArrayObject ($ response ->toArray ());
96
+ });
97
+ }
80
98
}
0 commit comments