~dvko/wp-cdn-loader

43b95f9415de727cb495fd4781e43a6350870b88 — Danny van Kooten 1 year, 11 months ago 240d619
simplify
2 files changed, 12 insertions(+), 56 deletions(-)

M cdn-loader.php
D src/UrlRewriter.php
M cdn-loader.php => cdn-loader.php +12 -8
@@ 21,8 21,6 @@ You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>. 
*/

namespace CDN_Loader;

if( ! defined( 'ABSPATH' ) ) {
	exit;
}


@@ 38,14 36,20 @@ add_action( 'template_redirect', function() {
		return;
	}

	// load class
	require_once __DIR__ . '/src/UrlRewriter.php';

	// get url of cdn & site
	$cdn_url = DVK_CDN_URL;
	$site_url = get_home_url();
    $url_replacer = function( $url ) use ( $cdn_url, $site_url ) {
        return str_replace( $site_url, $cdn_url, $url );
    };

	// add rewrite filters for plugin & theme assets
    add_filter( 'theme_root_uri', $url_replacer, 99, 1 );
    add_filter( 'plugins_url', $url_replacer, 99, 1 );

	// instantiate class
	$url_rewriter = new UrlRewriter( $cdn_url, $site_url );
	$url_rewriter->add_hooks();
    // add rewrite filters for misc scripts and styles
    add_filter( 'script_loader_src', $url_replacer, 99, 1 );
    add_filter( 'style_loader_src', $url_replacer, 99, 1 );
});



D src/UrlRewriter.php => src/UrlRewriter.php +0 -48
@@ 1,48 0,0 @@
<?php

namespace CDN_Loader;

class UrlRewriter {
	/**
	 * @var string
	 */
	private $cdn_url = '';

	/**
	 * @var string
	 */
	private $site_url = '';

	/**
	 * Constructor
	 *
	 * @param string $cdn_url
	 * @param string $site_url
	 */
	public function __construct( $cdn_url, $site_url ) {
		// Store cdn url & site url in property
		$this->site_url = $site_url;
		$this->cdn_url = $cdn_url;
	}

	public function add_hooks() {
		// add rewrite filters for plugin & theme assets
		add_filter( 'theme_root_uri', array( $this, 'rewrite' ), 99, 1 );
		add_filter( 'plugins_url', array( $this, 'rewrite' ), 99, 1 );

		// add rewrite filters for misc scripts and styles
		add_filter( 'script_loader_src', array( $this, 'rewrite' ), 99, 1 );
		add_filter( 'style_loader_src', array( $this, 'rewrite' ), 99, 1 );
		return true;
	}

	/**
	 * @param $url
	 *
	 * @return mixed
	 */
	public function rewrite( $url ) {
		$url = str_replace( $this->site_url, $this->cdn_url, $url );
		return $url;
	}
}
\ No newline at end of file