Skip to content

Instantly share code, notes, and snippets.

@jcowher
Created February 27, 2019 14:54
Show Gist options
  • Save jcowher/1e4c9f45eb3ee313b4e2cf1427fa7e50 to your computer and use it in GitHub Desktop.
Save jcowher/1e4c9f45eb3ee313b4e2cf1427fa7e50 to your computer and use it in GitHub Desktop.
WordPress class for downloading missing assets from production to dev on the fly
<?php
if ( ! class_exists( 'WP_File_Proxy' ) ) :
class WP_File_Proxy {
/**
* @var string
*/
protected $proxy_domain;
/**
* WP_File_Proxy constructor.
*
* @param string $proxy_domain
*/
function __construct( string $proxy_domain ) {
$this->proxy_domain = trailingslashit( $proxy_domain );
add_action( 'template_redirect', [ $this, 'maybe_fetch_asset' ] );
}
/**
* Maybe fetch missing asset.
*/
function maybe_fetch_asset() {
global $wp;
if ( is_404() && 0 === strpos( $wp->request, 'wp-content/uploads/' ) ) {
$this->fetch_asset( $wp->request );
}
}
/**
* Fetch the given asset from the remote host.
*
* @param string $filepath
*/
protected function fetch_asset( string $filepath ) {
$filename = basename( $filepath );
$proxy_url = $this->proxy_domain . $filepath;
$response = wp_remote_get( $proxy_url, [ 'stream' => true, 'sslverify' => false ] );
if ( ! is_wp_error( $response ) && ! empty( $response['filename'] ) ) {
$time = null;
if ( 1 === preg_match( '~([0-9]{4}/[0-9]{2})~', $filepath, $matches ) ) {
$time = $matches[1];
}
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $response['filename'] ), $time );
if ( ! $upload_file['error'] ) {
$filetype = wp_check_filetype( $filename, null );
if ( ! empty( $filetype['type'] ) ) {
status_header( 200 );
header( 'Content-type: ' . $filetype['type'] );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
echo file_get_contents( $response['filename'] );
exit;
}
}
}
}
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment