Skip to content

Instantly share code, notes, and snippets.

@smithweb
Last active December 9, 2016 18:07
Show Gist options
  • Save smithweb/4746695 to your computer and use it in GitHub Desktop.
Save smithweb/4746695 to your computer and use it in GitHub Desktop.
Magento CSS Auto Versioning
<?xml version="1.0" encoding="UTF-8"?>
<!-- app/code/core/local/SW/etc/config.xml -->
<config>
<modules>
<SW_Core>
<version>0.1.1</version>
</SW_Core>
</modules>
<global>
<models>
<core>
<rewrite>
<design_package>SW_Core_Model_Design_Package</design_package>
</rewrite>
</core>
</models>
</global>
</config>
<?php
// app/code/local/SW/Core/Model/Design/Package.php
class SW_Core_Model_Design_Package extends Mage_Core_Model_Design_Package
{
/**
* Get the timestamp of the newest file
*
* @param array $files
* @return int $timeStamp
*/
protected function getNewestFileTimestamp($srcFiles) {
$timeStamp = null;
foreach ($srcFiles as $file) {
if(is_null($timeStamp)) {
//if is first file, set $timeStamp to filemtime of file
$timeStamp = filemtime($file);
} else {
//get max of current files filemtime and the max so far
$timeStamp = max($timeStamp, filemtime($file));
}
}
return $timeStamp;
}
/**
* Merge specified css files and return URL to the merged file on success
*
* @param $files
* @return string
*/
public function getMergedCssUrl($files)
{
// secure or unsecure
$isSecure = Mage::app()->getRequest()->isSecure();
$mergerDir = $isSecure ? 'css_secure' : 'css';
$targetDir = $this->_initMergerDir($mergerDir);
if (!$targetDir) {
return '';
}
// base hostname & port
$baseMediaUrl = Mage::getBaseUrl('media', $isSecure);
$hostname = parse_url($baseMediaUrl, PHP_URL_HOST);
$port = parse_url($baseMediaUrl, PHP_URL_PORT);
if (false === $port) {
$port = $isSecure ? 443 : 80;
}
//get timestamp of newest source file
$filesTimeStamp = $this->getNewestFileTimestamp($files);
// merge into target file
$targetFilename = md5(implode(',', $files) . "|{$hostname}|{$port}") . "_" . $filesTimeStamp . '.css';
//If the file with the proper timestamp as part of its filename already exists, there's no reason to check again to see if
//we need to remerge the css files
if(!file_exists($targetDir . DS . $targetFilename)) {
$mergeFilesResult = $this->_mergeFiles(
$files, $targetDir . DS . $targetFilename,
false,
array($this, 'beforeMergeCss'),
'css'
);
if ($mergeFilesResult) {
return $baseMediaUrl . $mergerDir . '/' . $targetFilename;
}
} else {
return $baseMediaUrl . $mergerDir . '/' . $targetFilename;
}
return '';
}
}
<?xml version="1.0"?>
<!-- app/etc/modules/SW_All.xml -->
<config>
<modules>
<SW_Core>
<active>true</active>
<codePool>local</codePool>
</SW_Core>
</modules>
</config>
@EricSeastrand
Copy link

Why create a gist and not just create a repo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment