Skip to content

Instantly share code, notes, and snippets.

@MichaelThessel
Last active August 25, 2017 20:54
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 MichaelThessel/3d9503eb197d780e4db67305af100707 to your computer and use it in GitHub Desktop.
Save MichaelThessel/3d9503eb197d780e4db67305af100707 to your computer and use it in GitHub Desktop.
Simple Magento asset minifier
<?php
require_once 'abstract.php';
/**
* Minifies Magento JS and CSS file
*/
class Ac_Asset_Minify extends Mage_Shell_Abstract
{
// https://github.com/yui/yuicompressor/releases
protected $compressorCommand = 'java -jar shell/yuicompressor-2.4.8.jar %s -o %s';
// Don't compress files if first line is longer than $compressCutoff
// Prevent re-compression of already compressed files
protected $compressCutoff = 300;
// Paths to check for JS and CSS files for
protected $paths = [
'media/css',
'media/css_secure',
'media/js',
'media/js_secure',
];
/**
* Run script
*/
public function run()
{
$this->minify();
}
/**
* Walk through asset directories and minify files
*/
protected function minify()
{
foreach ($this->paths as $path) {
if (!is_dir($path)) continue;
foreach (new DirectoryIterator($path) as $fileInfo) {
if (!$fileInfo->isFile()) continue;
if (!in_array($fileInfo->getExtension(), ['js', 'css'])) continue;
$file = $path . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
if (!is_readable($file)) {
throw new Exception(sprintf('Couldn\'t read %s', $file));
}
if (!is_writeable($file)) {
throw new Exception(sprintf('%s is not writable', $file));
}
$this->compress($file);
}
}
}
/**
* Compress file
*/
protected function compress($file)
{
$line = fgets(fopen($file, 'r'));
if (strlen($line) > $this->compressCutoff) {
printf("File %s is already compressed skipping\n", $file);
return;
}
printf("Compressing %s \n", $file);
exec(sprintf($this->compressorCommand, $file, $file));
}
/**
* Retrieve Usage Help Message
*
*/
public function usageHelp()
{
return <<<USAGE
Usage: php assetMinify.php
USAGE;
}
}
$shell = new Ac_Asset_Minify();
$shell->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment