Automattic\WooCommerce\Internal\TransientFiles
TransientFilesEngine::serve_file_contents
Core method to serve the contents of a transient file.
Method of the class: TransientFilesEngine{}
Hooks from the method
Returns
null. Nothing (null).
Usage
// private - for code of main (parent) class only $result = $this->serve_file_contents( $file_name );
- $file_name(string) (required)
- Transient file id or filename.
TransientFilesEngine::serve_file_contents() TransientFilesEngine::serve file contents code WC 10.4.3
private function serve_file_contents( string $file_name ) {
$legacy_proxy = wc_get_container()->get( LegacyProxy::class );
try {
$file_path = $this->get_transient_file_path( $file_name );
if ( is_null( $file_path ) ) {
$legacy_proxy->call_function( 'status_header', 404 );
$legacy_proxy->exit();
}
if ( $this->file_has_expired( $file_path ) ) {
$legacy_proxy->call_function( 'status_header', 404 );
$legacy_proxy->exit();
}
$file_length = filesize( $file_path );
if ( false === $file_length ) {
throw new Exception( "Can't retrieve file size: $file_path" );
}
$file_handle = fopen( $file_path, 'r' );
} catch ( Exception $ex ) {
$error_message = "Error serving transient file $file_name: {$ex->getMessage()}";
wc_get_logger()->error( $error_message );
$legacy_proxy->call_function( 'status_header', 500 );
$legacy_proxy->exit();
}
$legacy_proxy->call_function( 'status_header', 200 );
$legacy_proxy->call_function( 'header', 'Content-Type: text/html' );
$legacy_proxy->call_function( 'header', "Content-Length: $file_length" );
try {
while ( ! feof( $file_handle ) ) {
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo fread( $file_handle, 1024 );
}
/**
* Action that fires after a transient file has been successfully served, right before terminating the request.
*
* @param array $transient_file_info Information about the served file, as returned by get_file_by_name.
* @param bool $is_json_rest_api_request True if the request came from the JSON API endpoint, false if it came from the authenticated endpoint.
*
* @since 8.5.0
*/
do_action( 'woocommerce_transient_file_contents_served', $file_name );
} catch ( Exception $e ) {
wc_get_logger()->error( "Error serving transient file $file_name: {$e->getMessage()}" );
// We can't change the response status code at this point.
} finally {
fclose( $file_handle );
$legacy_proxy->exit();
}
}