cache_dir = $cache_dir; } /** * Returns the server path to the cache directory. * * @example /app/wp-content/cache * * @return string */ public function get_cache_dir(): string { return $this->cache_dir; } /** * Get the path to where pages are cached. * * @example /app/wp-content/cache/page * * @return string */ public function get_page_cache_dir(): string { return $this->get_cache_dir() . '/page'; } /** * Get the host site cache directory. * * @example /app/wp-content/cache/page/www.wordpress.test * * @return string */ public function get_site_cache_dir(): string { $path = $this->get_page_cache_dir(); $site_host = wp_parse_url( get_site_url(), PHP_URL_HOST ); return $path . DIRECTORY_SEPARATOR . $site_host; } /** * Converts a URL into a directory structure. * * All cached requests will be saved to a directory structure that matches * the relative URL. This provides a way to consistently get the cached * resource from the URL. * * @example /app/wp-content/cache/page/local.test.com/test-post * * @throws RuntimeException When URL does not have valid host. * * @param string $url The full URL of the request (e.g. https://solidwp.com/about). * * @return string */ public function get_path_from_url( string $url ): string { $url_parts = parse_url( $url ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url if ( ! isset( $url_parts['host'] ) || $url_parts['host'] === '' ) { throw new RuntimeException( 'URL needs a valid host.' ); } $host = trim( $url_parts['host'], '/' ); $path = trim( $url_parts['path'] ?? '', '/' ); if ( $path === '' ) { $path = 'index'; } return "{$this->get_page_cache_dir()}/$host/$path"; } /** * Recursively count how many cache files we have. * * @note Keep in mind one URL can generate multiple cache files, depending on the * compression strategies available on the server and what different browsers * ask for. * * @param string $path The optional path. * * @return int */ public function count( string $path = '' ): int { $count = 0; if ( ! $path ) { $path = $this->get_site_cache_dir(); } if ( ! file_exists( $path ) ) { return $count; } $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ) ); // Exclude the .meta.php files. $filtered = new RegexIterator( $iterator, '/^(?!.*\.php$).*$/i', RegexIterator::MATCH ); foreach ( $filtered as $file ) { if ( $file->isFile() && $file->getFilename()[0] !== '.' ) { ++$count; } } return $count; } }