/** * serve. The main entry point for this class * * Check the filename map, and get the files to be processed. * Write the file to the webroot so that this script is one-time-only * * This script is intended to be used either in development; with the files generated added * to the project repository. * * The following locations need to be writable to the php user: * config/mi_compressor.php * webroot/css * webroot/js * * @param string $request * @param mixed $type * @static * @return contents to be served up * @access public */ public static function serve($request = '', $type = null) { self::$loadedFiles = array(); self::log('Request String: ' . $request); $start = microtime(true); if ($type === null) { $type = array_pop(explode('.', $_GET['url'])); } $requests = self::listFiles($request, $type); if (!$requests) { return false; } $fingerprint = self::_fingerprint($request); $_request = str_replace($fingerprint, '', $request); $_request = preg_replace('@\\.min$@', '', $_request); if (count($requests) > 1 && $request != $_request) { if ($_request[0] === '/') { $path = WWW_ROOT . $_request . '.' . $type; } else { $path = WWW_ROOT . $type . DS . $_request . '.' . $type; } if (file_exists($path)) { self::log("Uncompressed file exists ({$path})"); self::log("\tbypassing process method and using this file as input"); $oString = file_get_contents($path); $return = self::minify($oString, $path); } } if (empty($return)) { self::$requestStack = array(); $return = self::process($requests, $type); if (!isset(self::$requestMap[$type][$_request]['all'])) { self::$requestMap[$type][$_request]['all'] = self::$requestStack; self::_populateRequestMap(true); } } if (self::cRead('store')) { if ($request[0] === '/') { $path = WWW_ROOT . ltrim($request, '/') . '.' . $type; } else { $path = WWW_ROOT . $type . DS . $request . '.' . $type; } if (count($requests) > 1 && strpos($path, '.min.')) { $test = str_replace('.min.', '.', $path); if (file_exists($test)) { if (self::$__NumberHelper === null) { App::import('Core', 'Helper'); App::import('Helper', 'App'); App::import('Helper', 'Number'); self::$__NumberHelper = new NumberHelper(); } $oString = file_get_contents($test); $oLength = strlen($oString); $fLength = strlen($return); $percent = round((1 - $fLength / $oLength) * 100); $oSize = self::$__NumberHelper->toReadableSize($oLength); $fSize = self::$__NumberHelper->toReadableSize($fLength); self::log("Overall Reduction: {$percent}% ({$oSize} to {$fSize})"); } } $File = new File($path, true); if (!$File->writable()) { self::log("PROBLEM: Couldn't open {$path} for writing"); } else { $File->delete(); $bytes = strlen($return); self::log("Writing {$path} {$bytes} bytes"); $File->write($return); } } if (self::cRead('debug')) { $return = self::log() . $return; } return $return; }