Skip to content

Instantly share code, notes, and snippets.

@rn0
Forked from timewasted/GzipFilter.php
Created August 7, 2011 20:50
Show Gist options
  • Save rn0/1130777 to your computer and use it in GitHub Desktop.
Save rn0/1130777 to your computer and use it in GitHub Desktop.
Assetic gzip filter
<?php
namespace Assetic\Filter;
use Assetic\Asset\AssetInterface;
use Assetic\Util\ProcessBuilder;
/**
* Runs assets through gzip.
*/
class GzipFilter implements FilterInterface
{
private $gzipBin;
private $compression;
/**
* Constructor.
*
* @param string $gzipBin Path to the gzip binary
*/
public function __construct($gzipBin = '/usr/local/bin')
{
$this->gzipBin = $gzipBin;
}
public function setCompression($compression)
{
if( !is_numeric($compression) || (int)$compression < 1 || (int)$compression > 9 )
throw new \RuntimeException('Compression must be an integer between 1 and 9, inclusive.');
$this->compression = $compression;
}
public function filterLoad(AssetInterface $asset)
{
}
public function filterDump(AssetInterface $asset)
{
$pb = new ProcessBuilder();
$pb
->inheritEnvironmentVariables()
->add($this->gzipBin);
;
if (null !== $this->compression) {
$pb->add('-' . $this->compression);
}
$pb->add('--no-name');
$pb->add($input = tempnam(sys_get_temp_dir(), 'assetic_gzip'));
file_put_contents($input, $asset->getContent());
$proc = $pb->getProcess();
$code = $proc->run();
if (0 < $code) {
unlink($input);
throw new \RuntimeException($proc->getErrorOutput());
}
$asset->setContent(file_get_contents($input . '.gz'));
unlink($input . '.gz');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment