Adding an http filter to test media uploads
Work in Progress
The following code snippet is a function to use in WordPress tests that require uploading images to the media library.
Because of how tests work, you may need to mock a network request.
Be sure to tear_down this filter!
/**
* Simulate HTTP requests for images in the theme's img/default-event-thumbnails folder.
*
* @see https://developer.wordpress.org/reference/hooks/pre_http_request/
* @param mixed $preempt Whether to preempt an HTTP request. Default false.
* @param array $args HTTP request arguments.
* @param string $url The request URL.
* @return array|false HTTP response or false to continue with the request.
*/
public function simulate_http_request( $preempt, $args, $url ) {
$img_folder = 'img/default-event-thumbnails/';
$img_name = basename( $url );
// Check if the URL contains the image folder path (works for both file and URI).
if ( str_contains( $url, $img_folder ) ) {
$theme_img_dir = get_theme_file_path( $img_folder );
$path = $theme_img_dir . $img_name;
if ( file_exists( $path ) ) {
$bytes = file_get_contents( $path );
if ( ! empty( $args['stream'] ) ) {
$filename = ! empty( $args['filename'] ) ? $args['filename'] : wp_tempnam( $url );
// Ensure directory exists (rare, but avoids edge failures).
wp_mkdir_p( dirname( $filename ) );
file_put_contents( $filename, $bytes );
return array(
'headers' => array( 'content-type' => 'image/jpeg' ),
'body' => '', // streamed to file
'response' => array(
'code' => 200,
'message' => 'OK',
),
'cookies' => array(),
'filename' => $filename,
);
}
return array(
'headers' => array( 'content-type' => mime_content_type( $path ) ),
'body' => $bytes,
'response' => array(
'code' => 200,
'message' => 'OK',
),
'cookies' => array(),
'filename' => $img_name,
);
}
}
return $preempt;
}