Skip to content

Commit f1042f0

Browse files
committed
feat(Svg): add cache system
1 parent 4ee0928 commit f1042f0

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

inc/Services/Svg.php

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -111,26 +111,33 @@ public function allow_svg_tag( $tags ) {
111111
*
112112
* @param string $sprite_name
113113
*
114-
* @return string
114+
* @return string | null
115115
*/
116-
public function get_sprite_hash( $sprite_name ) {
117-
$sprite_hash_file = \get_theme_file_path( '/dist/sprite-hashes.json' );
116+
public function get_sprite_hash( string $sprite_name ): ?string {
117+
static $sprite_hashes = null;
118118

119-
if ( ! is_readable( $sprite_hash_file ) ) {
120-
return '';
121-
}
119+
if ( null === $sprite_hashes ) {
120+
$sprite_hash_file = \get_theme_file_path( '/dist/sprite-hashes.json' );
122121

123-
$sprite_hash = file_get_contents( $sprite_hash_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
124-
$sprite_hash = json_decode( $sprite_hash, true );
122+
if ( ! is_readable( $sprite_hash_file ) ) {
123+
$sprite_hashes = [];
125124

126-
if ( empty( $sprite_hash ) ) {
127-
return '';
128-
}
125+
return null;
126+
}
129127

130-
if ( ! isset( $sprite_hash[ sprintf( 'icons/%s.svg', $sprite_name ) ] ) ) {
131-
return '';
128+
$sprite_hash = file_get_contents( $sprite_hash_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
129+
130+
try {
131+
$sprite_hash = json_decode( $sprite_hash, true, 512, JSON_THROW_ON_ERROR );
132+
} catch ( \JsonException $e ) {
133+
$sprite_hashes = [];
134+
135+
return null;
136+
}
137+
138+
$sprite_hashes = $sprite_hash;
132139
}
133140

134-
return '?' . $sprite_hash[ sprintf( 'icons/%s.svg', $sprite_name ) ];
141+
return $sprite_hash[ sprintf( 'icons/%s.svg', $sprite_name ) ] ?? null;
135142
}
136143
}

0 commit comments

Comments
 (0)