Skip to content

Commit d72f966

Browse files
committed
perf(Icon): cache collection SVG file lists with transients
Avoid glob on every request by storing file paths in a transient keyed by directory mtime; bypass the cache when WP_DEBUG is enabled.
1 parent 479331e commit d72f966

1 file changed

Lines changed: 46 additions & 4 deletions

File tree

‎inc/Services/Icon.php‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,15 +110,57 @@ private function register_collection( string $collection_slug, array $collection
110110
return;
111111
}
112112

113+
$svg_files = $this->get_collection_svg_files( $icons_directory );
114+
115+
foreach ( $svg_files as $svg_file ) {
116+
$this->register_icon_file( $collection_slug, $svg_file );
117+
}
118+
}
119+
120+
/**
121+
* Returns SVG file paths for a collection directory, with transient caching in production.
122+
*
123+
* @param string $icons_directory Validated absolute path to a collection icons directory.
124+
*
125+
* @return list<string>
126+
*/
127+
private function get_collection_svg_files( string $icons_directory ): array {
128+
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
129+
return $this->glob_svg_files( $icons_directory );
130+
}
131+
132+
$directory_mtime = filemtime( $icons_directory );
133+
if ( false === $directory_mtime ) {
134+
$directory_mtime = 0;
135+
}
136+
137+
$cache_key = 'bff_icon_svg_files_' . md5( $icons_directory . ':' . (string) $directory_mtime );
138+
$cached = get_transient( $cache_key );
139+
140+
if ( is_array( $cached ) ) {
141+
return $cached;
142+
}
143+
144+
$svg_files = $this->glob_svg_files( $icons_directory );
145+
146+
set_transient( $cache_key, $svg_files, WEEK_IN_SECONDS );
147+
148+
return $svg_files;
149+
}
150+
151+
/**
152+
* @param string $icons_directory Validated absolute path to a collection icons directory.
153+
*
154+
* @return list<string>
155+
*/
156+
private function glob_svg_files( string $icons_directory ): array {
113157
$svg_files = glob( $icons_directory . '/*.svg' );
114158

115159
if ( false === $svg_files ) {
116-
return;
160+
return [];
117161
}
118162

119-
foreach ( $svg_files as $svg_file ) {
120-
$this->register_icon_file( $collection_slug, $svg_file );
121-
}
163+
return $svg_files;
122164
}
123165

124166
/**

0 commit comments

Comments
 (0)