Skip to content

Instantly share code, notes, and snippets.

@shupp
Created March 21, 2011 18:40
Show Gist options
  • Save shupp/879949 to your computer and use it in GitHub Desktop.
Save shupp/879949 to your computer and use it in GitHub Desktop.
Example view helper for media urls
<?php
class Zend_View_Helper_MediaURL extends Zend_View_Helper_Abstract
{
/**
* Retrieves the full URL for a static media element, based on the path
*
* @param string $path The path of the file, including the '/' prefix
*
* @return string
*/
public function mediaURL($path)
{
$name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
// In produciton, use the minified JS version
if (substr($path, -3) == '.js'
&& substr($path, -6) !== 'min.js'
&& APPLICATION_ENV == 'production') {
$path = substr($path, 0, -3) . '.min.js';
}
// In production, use the minified CSS version
if (substr($path, -4) == '.css' && substr($path, -7) !== 'min.css'
&& APPLICATION_ENV == 'production') {
$path = substr($path, 0, -4) . '.min.css';
}
$hash = $this->_getCRC32($path);
if (!preg_match('/^media./', $name)) {
$name = 'media.' . $name;
}
$schemeHelper = new Zend_View_Helper_GetCurrentScheme();
// Set the scheme the same as the current request
$scheme = $schemeHelper->getCurrentScheme();
$url = $scheme . '://' . $name;
if (strlen($hash)) {
$url .= '/v/' . $hash;
}
$url .= $path;
return $url;
}
/**
* Calculates the CRC32 hash of a given static file
*
* @param string $path The path name to the file
*
* @return string
*/
protected function _getCRC32($path)
{
$filename = BASE_PATH . '/public/media' . $path;
if (!is_readable($filename)) {
$log = EC_Log::getInstance();
$log->crit('media file does not exist: ' . $filename);
return;
}
$key = md5('media_url' . $filename);
$apc = EC_Cache::singleton('apc');
$hash = $apc->load($key);
// If the hash was not found in APC, calculate it and store it for later
if ($hash === false || APPLICATION_ENV == 'development') {
$contents = file_get_contents($filename);
// zero pad to 8 characters if necessary for our mod_rewrite regex
$hash = sprintf('%08x', crc32($contents));
if (APPLICATION_ENV == 'production') {
$apc->save($hash, $key);
}
}
return $hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment