Automattic\WooCommerce\Internal\TransientFiles

TransientFilesEngine::delete_expired_files()publicWC 1.0

Delete expired transient files from the filesystem.

Method of the class: TransientFilesEngine{}

No Hooks.

Return

Array. "deleted_count" with the number of files actually deleted, "files_remain" that will be true if there are still files left to delete.

Usage

$TransientFilesEngine = new TransientFilesEngine();
$TransientFilesEngine->delete_expired_files( $limit ): array;
$limit(int)
Maximum number of files to delete.
Default: 1000

TransientFilesEngine::delete_expired_files() code WC 9.6.0

public function delete_expired_files( int $limit = 1000 ): array {
	$expiration_date_gmt = $this->legacy_proxy->call_function( 'gmdate', 'Y-m-d' );
	$base_dir            = $this->get_transient_files_directory();
	$subdirs             = glob( $base_dir . '/[2-9][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]', GLOB_ONLYDIR );
	if ( false === $subdirs ) {
		throw new Exception( "Error when getting the list of subdirectories of $base_dir" );
	}

	$subdirs         = array_map( fn( $name ) => substr( $name, strlen( $name ) - 10, 10 ), $subdirs );
	$expired_subdirs = array_filter( $subdirs, fn( $name ) => $name < $expiration_date_gmt );
	asort( $subdirs ); // We want to delete files starting with the oldest expiration month.

	$remaining_limit = $limit;
	$limit_reached   = false;
	foreach ( $expired_subdirs as $subdir ) {
		$full_dir_path   = $base_dir . '/' . $subdir;
		$files_to_delete = glob( $full_dir_path . '/*' );
		if ( count( $files_to_delete ) > $remaining_limit ) {
			$limit_reached   = true;
			$files_to_delete = array_slice( $files_to_delete, 0, $remaining_limit );
		}
		array_map( 'wp_delete_file', $files_to_delete );
		$remaining_limit -= count( $files_to_delete );
		$this->delete_directory_if_not_empty( $full_dir_path );

		if ( $limit_reached ) {
			break;
		}
	}

	return array(
		'deleted_count' => $limit - $remaining_limit,
		'files_remain'  => $limit_reached,
	);
}