Skip to content

Instantly share code, notes, and snippets.

@merk
Created July 3, 2013 06:07
Show Gist options
  • Save merk/5915779 to your computer and use it in GitHub Desktop.
Save merk/5915779 to your computer and use it in GitHub Desktop.
CacheBustingWorker for Assetic 1.1.1
<?php
/**
* This file is part of IBMS
*
* (c) Infinite Networks Pty Ltd <http://www.infinite.net.au>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ibms\Helper;
use Assetic\Asset\AssetCollectionInterface;
use Assetic\Asset\AssetInterface;
use Assetic\Factory\Worker\CacheBustingWorker as BaseCacheBustingWorker;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Copied from Assetic due to limitations of its design which are not
* fixed until Assetic 1.2
*/
class CacheBustingWorker extends BaseCacheBustingWorker
{
private $container;
private $separator;
public function __construct(ContainerInterface $container, $separator = '-')
{
$this->container = $container;
$this->separator = $separator;
}
public function process(AssetInterface $asset)
{
if (!$path = $asset->getTargetPath()) {
// no path to work with
return;
}
if (!$search = pathinfo($path, PATHINFO_EXTENSION)) {
// nothing to replace
return;
}
$replace = $this->separator.$this->getHash($asset).'.'.$search;
if (preg_match('/'.preg_quote($replace, '/').'$/', $path)) {
// already replaced
return;
}
$asset->setTargetPath(
preg_replace('/\.'.preg_quote($search, '/').'$/', $replace, $path)
);
}
protected function getHash(AssetInterface $asset)
{
$hash = hash_init('sha1');
hash_update($hash, $this->getAm()->getLastModified($asset));
if ($asset instanceof AssetCollectionInterface) {
foreach ($asset as $i => $leaf) {
$sourcePath = $leaf->getSourcePath();
hash_update($hash, $sourcePath ?: $i);
}
}
return substr(hash_final($hash), 0, 7);
}
private function getAm()
{
return $this->container->get('assetic.asset_manager');
}
}
services:
assetic.factory_worker.cache_buster:
class: Ibms\Helper\CacheBustingWorker
arguments:
- @service_container
tags:
- { name: assetic.factory_worker }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment