Skip to content

Instantly share code, notes, and snippets.

@rmccullagh
Last active May 24, 2019 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmccullagh/c2c03978dc0c7de031108347f4bd1cc5 to your computer and use it in GitHub Desktop.
Save rmccullagh/c2c03978dc0c7de031108347f4bd1cc5 to your computer and use it in GitHub Desktop.
<?php
namespace App\Asset;
use App\Asset\AssetManagerInterface;
class AssetManager implements AssetManagerInterface
{
/** @var string */
private $webpackAssetHash;
/**
* The assest that were compiled via Amezmo's custom generator
* @var string
*/
private $amezmoAssetHash;
/** @var bool */
private $debug;
/** @var string */
private $cdn;
public function __construct($basePath, $debug, $cdn)
{
$this->webpackAssetHash = file_get_contents($basePath . '/webpack-hash.txt');
$this->amezmoAssetHash = AMEZMO_ASSET_VERSION_HASH;
$this->debug = $debug;
$this->cdn = $cdn;
}
/**
* Return the versioned javascript asset
*
* @return string
*/
public function js()
{
return $this->cdn . '/dist/app.'.$this->webpackAssetHash.'.js';
}
/**
* Return a versioned compiled css file
*
* @return string
*/
public function css()
{
return $this->cdn . '/dist/app.'.$this->webpackAssetHash.'.css';
}
/**
* Return fully qualified asset URL, using the CDN_ENDPOINT
*
* @param string $assetPath
* @return void
*/
public function url($assetPath)
{
if ($assetPath[0] === '/') {
$assetPath = substr($assetPath, 1);
}
// With debug, we will not insert the hash, but a timestamp in order to prevent the browser
// from caching it
if ($this->debug) {
return $this->cdn . '/' . $assetPath . '?t=' . time();
}
/** @var \SplFileInfo $fileInfo **/
$fileInfo = new \SplFileInfo($assetPath);
if (in_array($fileInfo->getExtension(), ['js', 'css'])) {
return $this->cdn . '/' . $this->versionedAsset($assetPath);
}
return $this->cdn . '/' . $assetPath;
}
/**
* Return the asset path for the Stripe integration
*
* @return string
*/
public function stripe()
{
if ($this->$debug) {
return $this->cdn . '/js/stripe.js?t=' . time();
}
return $this->cdn . '/js/stripe.'.$this->amezmoAssetHash.'.js';
}
/**
* This function splits the path name in order to insert an amezmo version hash between the filename
* and the file extension
*
* x.js => x.$AMEZMO_VERSION.js
*
* @param string $asset
* @return string
*/
public function versionedAsset($asset)
{
$components = explode('.', $asset);
$componentsCount = count($components);
$buffer = '';
foreach ($components as $index => $component) {
if ($index === $componentsCount - 2) {
if ($index != 0) {
$buffer .= '.';
}
$buffer .= $component . '.' . $this->amezmoAssetHash;
} else {
if ($index != 0) {
$buffer .= '.';
}
$buffer .= $component;
}
}
return $buffer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment