diff --git a/bootstrap.php b/bootstrap.php
index 57fe576..8855821 100644
--- a/bootstrap.php
+++ b/bootstrap.php
@@ -2,7 +2,6 @@
/**
* Sets up autoloading and returns the Minify\App
*/
-
call_user_func(function () {
if (is_dir(__DIR__ . '/../../../vendor')) {
// Used as a composer library
@@ -13,9 +12,9 @@ call_user_func(function () {
$file = $vendorDir . '/autoload.php';
if (!is_file($file)) {
- echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
- 'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
- 'php composer.phar install'.PHP_EOL;
+ echo 'You must set up the project dependencies, run the following commands:' . PHP_EOL .
+ 'curl -sS https://getcomposer.org/installer | php' . PHP_EOL .
+ 'php composer.phar install' . PHP_EOL;
exit(1);
}
diff --git a/builder/index.php b/builder/index.php
index 9cb8c1a..f327fc4 100644
--- a/builder/index.php
+++ b/builder/index.php
@@ -1,4 +1,4 @@
-config;
// recommend $min_symlinks setting for Apache UserDir
$symlinkOption = '';
-if (0 === strpos($app->env->server("SERVER_SOFTWARE"), 'Apache/')
+if (strpos($app->env->server('SERVER_SOFTWARE'), 'Apache/') === 0
&& preg_match('@^/\\~(\\w+)/@', $app->env->server('REQUEST_URI'), $m)
) {
$userDir = DIRECTORY_SEPARATOR . $m[1] . DIRECTORY_SEPARATOR;
- if (false !== strpos(__FILE__, $userDir)) {
+ if (strpos(__FILE__, $userDir) !== false) {
$sm = array();
$sm["//~{$m[1]}"] = dirname(__DIR__);
$array = str_replace('array (', 'array(', var_export($sm, 1));
- $symlinkOption = "\$min_symlinks = $array;";
+ $symlinkOption = "\$min_symlinks = ${array};";
}
}
@@ -28,8 +28,8 @@ if ($config->builderPassword && $config->builderPassword !== '') {
$auth = new Intervention\Httpauth\Httpauth(array(
'username' => 'admin',
'password' => $config->builderPassword,
- 'type' => 'digest',
- 'realm' => 'Minify Builder',
+ 'type' => 'digest',
+ 'realm' => 'Minify Builder',
));
$auth->secure();
}
@@ -60,13 +60,13 @@ b {color:#c00}
#jsDidntLoad {display:none;}
-
+
Note: It looks like you're running Minify in a user
directory. You may need the following option in /min/config.php to have URIs
correctly rewritten in CSS output:
-
+
Uh Oh. Minify was unable to
serve Javascript for this app. To troubleshoot this,
@@ -209,8 +209,8 @@ $content = ob_get_clean();
$controller = new Minify_Controller_Page($app->env, $app->sourceFactory);
$minify = $app->minify->serve($controller, array(
- 'content' => $content,
- 'id' => __FILE__,
+ 'content' => $content,
+ 'id' => __FILE__,
'lastModifiedTime' => max(
// regenerate cache if any of these change
filemtime(__FILE__),
diff --git a/builder/ocCheck.php b/builder/ocCheck.php
index 9f8475c..4757e41 100644
--- a/builder/ocCheck.php
+++ b/builder/ocCheck.php
@@ -1,15 +1,12 @@
config->enableBuilder) {
header('Location: /');
@@ -18,20 +15,19 @@ if (!$app->config->enableBuilder) {
if ($app->env->get('hello')) {
// echo 'World!'
-
+
// try to prevent double encoding (may not have an effect)
ini_set('zlib.output_compression', '0');
-
- HTTP_Encoder::$encodeToIe6 = true; // just in case
+
+ HTTP_Encoder::$encodeToIe6 = true; // just in case
$he = new HTTP_Encoder(array(
'content' => str_repeat('0123456789', 500),
- 'method' => 'deflate',
+ 'method' => 'deflate',
));
$he->encode();
$he->sendAll();
-
} else {
// echo status "0" or "1"
header('Content-Type: text/plain');
- echo (int)$_oc;
+ echo (int) $_oc;
}
diff --git a/builder/test.php b/builder/test.php
index 88e8da0..c139ec6 100644
--- a/builder/test.php
+++ b/builder/test.php
@@ -37,7 +37,7 @@ if (isset($_GET['oc'])) {
echo "
\$_SERVER['SUBDOMAIN_DOCUMENT_ROOT'] is set. "
. "You may need to set \$min_documentRoot to this in config.php
";
}
-
+
}
-//*/
\ No newline at end of file
+//*/
diff --git a/config-test.php b/config-test.php
index 7524a3d..a6eb00a 100644
--- a/config-test.php
+++ b/config-test.php
@@ -4,7 +4,4 @@
*
* To test config options, place them in this file and add "&test" to your Minify URL.
* Note that if this is on a public server, anyone can execute your test.
- *
- * @package Minify
*/
-
diff --git a/config.php b/config.php
index 02f01ca..8cbe6e1 100644
--- a/config.php
+++ b/config.php
@@ -2,43 +2,35 @@
/**
* Configuration for "min", the default application built with the Minify
* library
- *
- * @package Minify
*/
-
/**
* Enable the static serving feature
*/
$min_enableStatic = false;
-
/**
* Allow use of the Minify URI Builder app. Only set this to true while you need it.
*/
$min_enableBuilder = false;
-
/**
* Concatenate but do not minify the files. This can be used for testing.
*/
$min_concatOnly = false;
-
/**
* If non-empty, the Builder will be protected with HTTP Digest auth.
* The username is "admin".
*/
$min_builderPassword = 'admin';
-
/**
* Set to true to log messages to FirePHP (Firefox Firebug addon) and PHP's error_log
* Set to false for no error logging (Minify may be slightly faster).
*/
$min_errorLogger = false;
-
/**
* To allow debug mode output, you must set this option to true.
*
@@ -47,13 +39,12 @@ $min_errorLogger = false;
* /min/f=file1.js send the cookie minDebug=file1.js
* You can manually enable debugging by appending "&debug" to a URI.
* E.g. /min/?f=script1.js,script2.js&debug
- *
+ *
* In 'debug' mode, Minify combines files with no minification and adds comments
* to indicate line #s of the original files.
*/
$min_allowDebugFlag = false;
-
/**
* For best performance, specify your temp directory here. Otherwise Minify
* will have to load extra code to guess. Some examples below:
@@ -62,22 +53,20 @@ $min_allowDebugFlag = false;
//$min_cachePath = '/tmp';
//$min_cachePath = preg_replace('/^\\d+;/', '', session_save_path());
-
/**
* To use APC/Memcache/ZendPlatform for cache storage, require the class and
* set $min_cachePath to an instance. Example below:
*/
//$min_cachePath = new Minify_Cache_APC();
-
/**
* Leave an empty string to use PHP's $_SERVER['DOCUMENT_ROOT'].
*
- * On some servers, this value may be misconfigured or missing. If so, set this
+ * On some servers, this value may be misconfigured or missing. If so, set this
* to your full document root path with no trailing slash.
* E.g. '/home/accountname/public_html' or 'c:\\xampp\\htdocs'
*
- * If /min/ is directly inside your document root, just uncomment the
+ * If /min/ is directly inside your document root, just uncomment the
* second line. The third line might work on some Apache servers.
*/
$min_documentRoot = '';
@@ -85,25 +74,22 @@ $min_documentRoot = '';
//$min_documentRoot = substr(__FILE__, 0, -15);
//$min_documentRoot = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT'];
-
/**
- * Cache file locking. Set to false if filesystem is NFS. On at least one
+ * Cache file locking. Set to false if filesystem is NFS. On at least one
* NFS system flock-ing attempts stalled PHP for 30 seconds!
*/
$min_cacheFileLocking = true;
-
/**
* Combining multiple CSS files can place @import declarations after rules, which
* is invalid. Minify will attempt to detect when this happens and place a
- * warning comment at the top of the CSS output. To resolve this you can either
- * move the @imports within your CSS files, or enable this option, which will
- * move all @imports to the top of the output. Note that moving @imports could
+ * warning comment at the top of the CSS output. To resolve this you can either
+ * move the @imports within your CSS files, or enable this option, which will
+ * move all @imports to the top of the output. Note that moving @imports could
* affect CSS values (which is why this option is disabled by default).
*/
$min_serveOptions['bubbleCssImports'] = false;
-
/**
* Cache-Control: max-age value sent to browser (in seconds). After this period,
* the browser will send another conditional GET. Use a longer period for lower
@@ -115,27 +101,24 @@ $min_serveOptions['bubbleCssImports'] = false;
*/
$min_serveOptions['maxAge'] = 1800;
-
/**
* To use the CSS compressor that shipped with 2.x, uncomment the following line:
*/
//$min_serveOptions['minifiers'][Minify::TYPE_CSS] = array('Minify_CSS', 'minify');
-
/**
* To use Google's Closure Compiler API to minify Javascript (falling back to JSMin
* on failure), uncomment the following line:
*/
//$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');
-
/**
* If you'd like to restrict the "f" option to files within/below
* particular directories below DOCUMENT_ROOT, set this here.
* You will still need to include the directory in the
* f or b GET parameters.
- *
- * // = shortcut for DOCUMENT_ROOT
+ *
+ * // = shortcut for DOCUMENT_ROOT
*/
//$min_serveOptions['minApp']['allowDirs'] = array('//js', '//css');
@@ -145,23 +128,21 @@ $min_serveOptions['maxAge'] = 1800;
*/
$min_serveOptions['minApp']['groupsOnly'] = false;
-
/**
* By default, Minify will not minify files with names containing .min or -min
* before the extension. E.g. myFile.min.js will not be processed by JSMin
- *
+ *
* To minify all files, set this option to null. You could also specify your
* own pattern that is matched against the filename.
*/
//$min_serveOptions['minApp']['noMinPattern'] = '@[-\\.]min\\.(?:js|css)$@i';
-
/**
* If you minify CSS files stored in symlink-ed directories, the URI rewriting
* algorithm can fail. To prevent this, provide an array of link paths to
* target paths, where the link paths are within the document root.
- *
- * Because paths need to be normalized for this to work, use "//" to substitute
+ *
+ * Because paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
*
* array('//symlink' => '/real/target/path') // unix
@@ -170,26 +151,25 @@ $min_serveOptions['minApp']['groupsOnly'] = false;
*/
$min_symlinks = array();
-
/**
* If you upload files from Windows to a non-Windows server, Windows may report
- * incorrect mtimes for the files. This may cause Minify to keep serving stale
+ * incorrect mtimes for the files. This may cause Minify to keep serving stale
* cache files when source file changes are made too frequently (e.g. more than
* once an hour).
- *
- * Immediately after modifying and uploading a file, use the touch command to
+ *
+ * Immediately after modifying and uploading a file, use the touch command to
* update the mtime on the server. If the mtime jumps ahead by a number of hours,
- * set this variable to that number. If the mtime moves back, this should not be
+ * set this variable to that number. If the mtime moves back, this should not be
* needed.
*
- * In the Windows SFTP client WinSCP, there's an option that may fix this
- * issue without changing the variable below. Under login > environment,
+ * In the Windows SFTP client WinSCP, there's an option that may fix this
+ * issue without changing the variable below. Under login > environment,
* select the option "Adjust remote timestamp with DST".
- * @link http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time
+ *
+ * @see http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time
*/
$min_uploaderHoursBehind = 0;
-
/**
* Advanced: you can replace some of the PHP classes Minify uses to serve requests.
* To do this, assign a callable to one of the elements of the $min_factories array.
@@ -198,4 +178,3 @@ $min_uploaderHoursBehind = 0;
*/
//$min_factories['minify'] = ... a callable accepting a Minify\App object
//$min_factories['controller'] = ... a callable accepting a Minify\App object
-
diff --git a/groupsConfig.php b/groupsConfig.php
index cc80538..ee686dc 100644
--- a/groupsConfig.php
+++ b/groupsConfig.php
@@ -1,7 +1,6 @@
array('//minify/quick-test.js'),
-// 'testCss' => array('//minify/quick-test.css'),
-// 'js' => array('//js/file1.js', '//js/file2.js'),
-// 'css' => array('//css/file1.css', '//css/file2.css'),
+ // 'testJs' => array('//minify/quick-test.js'),
+ // 'testCss' => array('//minify/quick-test.css'),
+ // 'js' => array('//js/file1.js', '//js/file2.js'),
+ // 'css' => array('//css/file1.css', '//css/file2.css'),
);
diff --git a/index.php b/index.php
index 7b58bcc..66d5421 100644
--- a/index.php
+++ b/index.php
@@ -1,12 +1,9 @@
- * @package Minify
- * @subpackage HTTP
- * @author Stephen Clay
*/
class HTTP_ConditionalGet
{
-
/**
* Does the client have a valid copy of the requested resource?
*
@@ -71,7 +65,7 @@ class HTTP_ConditionalGet
*
* @var bool
*/
- public $cacheIsValid = null;
+ public $cacheIsValid;
/**
* @param array $spec options
@@ -116,7 +110,7 @@ class HTTP_ConditionalGet
// backwards compatibility (can be removed later)
if (isset($spec['setExpires'])
&& is_numeric($spec['setExpires'])
- && ! isset($spec['maxAge'])) {
+ && !isset($spec['maxAge'])) {
$spec['maxAge'] = $spec['setExpires'] - $_SERVER['REQUEST_TIME'];
}
if (isset($spec['maxAge'])) {
@@ -128,9 +122,9 @@ class HTTP_ConditionalGet
$etagAppend = '';
if (isset($spec['encoding'])) {
$this->_stripEtag = true;
- if ('' !== $spec['encoding']) {
+ if ($spec['encoding'] !== '') {
$this->_headers['Vary'] = 'Accept-Encoding';
- if (0 === strpos($spec['encoding'], 'x-')) {
+ if (strpos($spec['encoding'], 'x-') === 0) {
$spec['encoding'] = substr($spec['encoding'], 2);
}
$etagAppend = ';' . substr($spec['encoding'], 0, 2);
@@ -227,19 +221,17 @@ class HTTP_ConditionalGet
*
* @param int $lastModifiedTime if given, both ETag AND Last-Modified headers
* will be sent with content. This is recommended.
- *
* @param bool $isPublic (default false) if true, the Cache-Control header
* will contain "public", allowing proxies to cache the content. Otherwise
* "private" will be sent, allowing only browser caching.
- *
* @param array $options (default empty) additional options for constructor
*/
public static function check($lastModifiedTime = null, $isPublic = false, $options = array())
{
- if (null !== $lastModifiedTime) {
- $options['lastModifiedTime'] = (int)$lastModifiedTime;
+ if ($lastModifiedTime !== null) {
+ $options['lastModifiedTime'] = (int) $lastModifiedTime;
}
- $options['isPublic'] = (bool)$isPublic;
+ $options['isPublic'] = (bool) $isPublic;
$cg = new HTTP_ConditionalGet($options);
$cg->sendHeaders();
if ($cg->cacheIsValid) {
@@ -264,13 +256,15 @@ class HTTP_ConditionalGet
}
protected $_headers = array();
- protected $_lmTime = null;
- protected $_etag = null;
+
+ protected $_lmTime;
+
+ protected $_etag;
+
protected $_stripEtag = false;
/**
* @param string $hash
- *
* @param string $scope
*/
protected function _setEtag($hash, $scope)
@@ -284,7 +278,7 @@ class HTTP_ConditionalGet
*/
protected function _setLastModified($time)
{
- $this->_lmTime = (int)$time;
+ $this->_lmTime = (int) $time;
$this->_headers['Last-Modified'] = self::gmtDate($time);
}
@@ -295,7 +289,7 @@ class HTTP_ConditionalGet
*/
protected function _isCacheValid()
{
- if (null === $this->_etag) {
+ if ($this->_etag === null) {
// lmTime is copied to ETag, so this condition implies that the
// server sent neither ETag nor Last-Modified, so the client can't
// possibly has a valid cache.
diff --git a/lib/HTTP/Encoder.php b/lib/HTTP/Encoder.php
index 3bd788c..d023764 100644
--- a/lib/HTTP/Encoder.php
+++ b/lib/HTTP/Encoder.php
@@ -1,8 +1,6 @@
*/
class HTTP_Encoder
{
-
/**
* Should the encoder allow HTTP encoding to IE6?
*
@@ -89,11 +82,11 @@ class HTTP_Encoder
{
$this->_useMbStrlen = (function_exists('mb_strlen')
&& (ini_get('mbstring.func_overload') !== '')
- && ((int)ini_get('mbstring.func_overload') & 2));
+ && ((int) ini_get('mbstring.func_overload') & 2));
$this->_content = $spec['content'];
$this->_headers['Content-Length'] = $this->_useMbStrlen
- ? (string)mb_strlen($this->_content, '8bit')
- : (string)strlen($this->_content);
+ ? (string) mb_strlen($this->_content, '8bit')
+ : (string) strlen($this->_content);
if (isset($spec['type'])) {
$this->_headers['Content-Type'] = $spec['type'];
}
@@ -180,7 +173,6 @@ class HTTP_Encoder
* rarely sent by servers, so client support could be buggier.
*
* @param bool $allowCompress allow the older compress encoding
- *
* @param bool $allowDeflate allow the more recent deflate encoding
*
* @return array two values, 1st is the actual encoding method, 2nd is the
@@ -191,40 +183,44 @@ class HTTP_Encoder
{
// @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
- if (! isset($_SERVER['HTTP_ACCEPT_ENCODING'])
+ if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])
|| self::isBuggyIe()) {
return array('', '');
}
$ae = $_SERVER['HTTP_ACCEPT_ENCODING'];
// gzip checks (quick)
- if (0 === strpos($ae, 'gzip,') // most browsers
- || 0 === strpos($ae, 'deflate, gzip,') // opera
+ if (strpos($ae, 'gzip,') === 0 // most browsers
+ || strpos($ae, 'deflate, gzip,') === 0 // opera
) {
return array('gzip', 'gzip');
}
// gzip checks (slow)
if (preg_match(
- '@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
- ,$ae
- ,$m)) {
+ '@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
+ $ae,
+ $m
+ )) {
return array('gzip', $m[1]);
}
if ($allowDeflate) {
// deflate checks
$aeRev = strrev($ae);
- if (0 === strpos($aeRev, 'etalfed ,') // ie, webkit
- || 0 === strpos($aeRev, 'etalfed,') // gecko
- || 0 === strpos($ae, 'deflate,') // opera
+ if (strpos($aeRev, 'etalfed ,') === 0 // ie, webkit
+ || strpos($aeRev, 'etalfed,') === 0 // gecko
+ || strpos($ae, 'deflate,') === 0 // opera
// slow parsing
|| preg_match(
- '@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@', $ae)) {
+ '@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
+ $ae
+ )) {
return array('deflate', 'deflate');
}
}
if ($allowCompress && preg_match(
- '@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
- ,$ae
- ,$m)) {
+ '@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
+ $ae,
+ $m
+ )) {
return array('compress', $m[1]);
}
@@ -250,13 +246,13 @@ class HTTP_Encoder
*/
public function encode($compressionLevel = null)
{
- if (! self::isBuggyIe()) {
+ if (!self::isBuggyIe()) {
$this->_headers['Vary'] = 'Accept-Encoding';
}
- if (null === $compressionLevel) {
+ if ($compressionLevel === null) {
$compressionLevel = self::$compressionLevel;
}
- if ('' === $this->_encodeMethod[0]
+ if ($this->_encodeMethod[0] === ''
|| ($compressionLevel == 0)
|| !extension_loaded('zlib')) {
return false;
@@ -268,12 +264,12 @@ class HTTP_Encoder
} else {
$encoded = gzcompress($this->_content, $compressionLevel);
}
- if (false === $encoded) {
+ if ($encoded === false) {
return false;
}
$this->_headers['Content-Length'] = $this->_useMbStrlen
- ? (string)mb_strlen($encoded, '8bit')
- : (string)strlen($encoded);
+ ? (string) mb_strlen($encoded, '8bit')
+ : (string) strlen($encoded);
$this->_headers['Content-Encoding'] = $this->_encodeMethod[1];
$this->_content = $encoded;
@@ -286,7 +282,6 @@ class HTTP_Encoder
* This is a convenience method for common use of the class
*
* @param string $content
- *
* @param int $compressionLevel given to zlib functions. If not given, the
* class default will be used.
*
@@ -294,7 +289,7 @@ class HTTP_Encoder
*/
public static function output($content, $compressionLevel = null)
{
- if (null === $compressionLevel) {
+ if ($compressionLevel === null) {
$compressionLevel = self::$compressionLevel;
}
$he = new HTTP_Encoder(array('content' => $content));
@@ -316,20 +311,23 @@ class HTTP_Encoder
}
$ua = $_SERVER['HTTP_USER_AGENT'];
// quick escape for non-IEs
- if (0 !== strpos($ua, 'Mozilla/4.0 (compatible; MSIE ')
- || false !== strpos($ua, 'Opera')) {
+ if (strpos($ua, 'Mozilla/4.0 (compatible; MSIE ') !== 0
+ || strpos($ua, 'Opera') !== false) {
return false;
}
// no regex = faaast
- $version = (float)substr($ua, 30);
+ $version = (float) substr($ua, 30);
return self::$encodeToIe6
- ? ($version < 6 || ($version == 6 && false === strpos($ua, 'SV1')))
+ ? ($version < 6 || ($version == 6 && strpos($ua, 'SV1') === false))
: ($version < 7);
}
protected $_content = '';
+
protected $_headers = array();
+
protected $_encodeMethod = array('', '');
+
protected $_useMbStrlen = false;
}
diff --git a/lib/Minify.php b/lib/Minify.php
index c41871d..b3c1cf7 100644
--- a/lib/Minify.php
+++ b/lib/Minify.php
@@ -1,9 +1,7 @@
- * @author Stephen Clay
* @copyright 2008 Ryan Grove, Stephen Clay. All rights reserved.
* @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @link https://github.com/mrclay/minify
+ *
+ * @see https://github.com/mrclay/minify
*/
class Minify
{
-
/**
* API version
*
@@ -34,10 +29,13 @@ class Minify
const VERSION = 3;
const TYPE_CSS = 'text/css';
+
const TYPE_HTML = 'text/html';
+
// there is some debate over the ideal JS Content-Type, but this is the
// Apache default and what Yahoo! uses..
const TYPE_JS = 'application/x-javascript';
+
const URL_DEBUG = 'https://github.com/mrclay/minify/blob/master/docs/Debugging.wiki.md';
/**
@@ -99,30 +97,30 @@ class Minify
public function getDefaultOptions()
{
return array(
- 'isPublic' => true,
+ 'isPublic' => true,
'encodeOutput' => function_exists('gzdeflate'),
'encodeMethod' => null, // determine later
- 'encodeLevel' => 9,
+ 'encodeLevel' => 9,
'minifiers' => array(
- Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
- Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
+ Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
+ Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
),
'minifierOptions' => array(), // no minifier options
'contentTypeCharset' => 'utf-8',
- 'maxAge' => 1800, // 30 minutes
- 'rewriteCssUris' => true,
- 'bubbleCssImports' => false,
- 'quiet' => false, // serve() will send headers and output
- 'debug' => false,
- 'concatOnly' => false,
+ 'maxAge' => 1800, // 30 minutes
+ 'rewriteCssUris' => true,
+ 'bubbleCssImports' => false,
+ 'quiet' => false, // serve() will send headers and output
+ 'debug' => false,
+ 'concatOnly' => false,
// if you override these, the response codes MUST be directly after
// the first space.
'badRequestHeader' => 'HTTP/1.0 400 Bad Request',
- 'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
+ 'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
// callback function to see/modify content of all sources
'postprocessor' => null,
@@ -135,7 +133,7 @@ class Minify
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning.
*/
- 'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n"
+ 'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n",
);
}
@@ -176,6 +174,7 @@ class Minify
*
* 'debug' : set to true to minify all sources with the 'Lines' controller, which
* eases the debugging of combined files. This also prevents 304 responses.
+ *
* @see Minify_Lines::minify()
*
* 'concatOnly' : set to true to disable minification and simply concatenate the files.
@@ -211,14 +210,13 @@ class Minify
* Any controller options are documented in that controller's createConfiguration() method.
*
* @param Minify_ControllerInterface $controller instance of subclass of Minify_Controller_Base
- *
* @param array $options controller/serve options
*
- * @return null|array if the 'quiet' option is set to true, an array
- * with keys "success" (bool), "statusCode" (int), "content" (string), and
- * "headers" (array).
- *
* @throws Exception
+ *
+ * @return array|null if the 'quiet' option is set to true, an array
+ * with keys "success" (bool), "statusCode" (int), "content" (string), and
+ * "headers" (array)
*/
public function serve(Minify_ControllerInterface $controller, $options = array())
{
@@ -239,16 +237,16 @@ class Minify
// check request validity
if (!$this->sources) {
// invalid request!
- if (! $this->options['quiet']) {
+ if (!$this->options['quiet']) {
$this->errorExit($this->options['badRequestHeader'], self::URL_DEBUG);
} else {
- list(,$statusCode) = explode(' ', $this->options['badRequestHeader']);
+ list(, $statusCode) = explode(' ', $this->options['badRequestHeader']);
return array(
- 'success' => false,
- 'statusCode' => (int)$statusCode,
- 'content' => '',
- 'headers' => array(),
+ 'success' => false,
+ 'statusCode' => (int) $statusCode,
+ 'content' => '',
+ 'headers' => array(),
);
}
}
@@ -273,7 +271,7 @@ class Minify
// getAcceptedEncoding(false, false) leaves out compress and deflate as options.
$list = HTTP_Encoder::getAcceptedEncoding(false, false);
list($this->options['encodeMethod'], $contentEncoding) = $list;
- $sendVary = ! HTTP_Encoder::isBuggyIe();
+ $sendVary = !HTTP_Encoder::isBuggyIe();
}
} else {
$this->options['encodeMethod'] = ''; // identity (no encoding)
@@ -282,8 +280,8 @@ class Minify
// check client cache
$cgOptions = array(
'lastModifiedTime' => $this->options['lastModifiedTime'],
- 'isPublic' => $this->options['isPublic'],
- 'encoding' => $this->options['encodeMethod'],
+ 'isPublic' => $this->options['isPublic'],
+ 'encoding' => $this->options['encodeMethod'],
);
if ($this->options['maxAge'] > 0) {
@@ -295,17 +293,17 @@ class Minify
$cg = new HTTP_ConditionalGet($cgOptions);
if ($cg->cacheIsValid) {
// client's cache is valid
- if (! $this->options['quiet']) {
+ if (!$this->options['quiet']) {
$cg->sendHeaders();
return;
}
return array(
- 'success' => true,
+ 'success' => true,
'statusCode' => 304,
- 'content' => '',
- 'headers' => $cg->getHeaders(),
+ 'content' => '',
+ 'headers' => $cg->getHeaders(),
);
}
@@ -332,7 +330,7 @@ class Minify
}
// check server cache
- if (! $this->options['debug']) {
+ if (!$this->options['debug']) {
// using cache
// the goal is to use only the cache methods to sniff the length and
// output the content, as they do not require ever loading the file into
@@ -350,9 +348,10 @@ class Minify
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
- if (! $this->options['quiet']) {
+ if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
+
throw $e;
}
$this->cache->store($cacheId, $content);
@@ -363,17 +362,19 @@ class Minify
} else {
// no cache
$cacheIsReady = false;
+
try {
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
- if (! $this->options['quiet']) {
+ if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
+
throw $e;
}
}
- if (! $cacheIsReady && $this->options['encodeMethod']) {
+ if (!$cacheIsReady && $this->options['encodeMethod']) {
// still need to encode
$content = gzencode($content, $this->options['encodeLevel']);
}
@@ -382,7 +383,7 @@ class Minify
if ($cacheIsReady) {
$headers['Content-Length'] = $cacheContentLength;
} else {
- if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
+ if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
$headers['Content-Length'] = mb_strlen($content, '8bit');
} else {
$headers['Content-Length'] = strlen($content);
@@ -401,7 +402,7 @@ class Minify
$headers['Vary'] = 'Accept-Encoding';
}
- if (! $this->options['quiet']) {
+ if (!$this->options['quiet']) {
// output headers & content
foreach ($headers as $name => $val) {
header($name . ': ' . $val);
@@ -413,10 +414,10 @@ class Minify
}
} else {
return array(
- 'success' => true,
+ 'success' => true,
'statusCode' => 200,
- 'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
- 'headers' => $headers,
+ 'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
+ 'headers' => $headers,
);
}
}
@@ -427,8 +428,7 @@ class Minify
* No internal caching will be used and the content will not be HTTP encoded.
*
* @param array $sources array of filepaths and/or Minify_Source objects
- *
- * @param array $options (optional) array of options for serve.
+ * @param array $options (optional) array of options for serve
*
* @return string
*/
@@ -444,9 +444,9 @@ class Minify
$controller = new Minify_Controller_Files($env, $sourceFactory, $this->logger);
$options = array_merge($options, array(
- 'files' => (array)$sources,
- 'quiet' => true,
- 'encodeMethod' => '',
+ 'files' => (array) $sources,
+ 'quiet' => true,
+ 'encodeMethod' => '',
'lastModifiedTime' => 0,
));
$out = $this->serve($controller, $options);
@@ -464,24 +464,24 @@ class Minify
* @param string $msgHtml HTML message for the client
*
* @return void
+ *
* @internal This is not part of the public API and is subject to change
- * @access private
*/
public function errorExit($header, $url = '', $msgHtml = '')
{
$url = htmlspecialchars($url, ENT_QUOTES);
- list(,$h1) = explode(' ', $header, 2);
+ list(, $h1) = explode(' ', $header, 2);
$h1 = htmlspecialchars($h1);
// FastCGI environments require 3rd arg to header() to be set
list(, $code) = explode(' ', $header, 3);
header($header, true, $code);
header('Content-Type: text/html; charset=utf-8');
- echo "$h1
";
+ echo "${h1}
";
if ($msgHtml) {
echo $msgHtml;
}
if ($url) {
- echo "Please see $url.
";
+ echo "Please see ${url}.
";
}
exit;
}
@@ -490,6 +490,7 @@ class Minify
* Default minifier for .min or -min JS files.
*
* @param string $content
+ *
* @return string
*/
public static function nullMinifier($content)
@@ -537,9 +538,9 @@ class Minify
/**
* Combines sources and minifies the result.
*
- * @return string
- *
* @throws Exception
+ *
+ * @return string
*/
protected function combineMinify()
{
@@ -590,10 +591,11 @@ class Minify
// do we need to process our group right now?
if ($i > 0 // yes, we have at least the first group populated
&& (
- ! $source // yes, we ran out of sources
+ !$source // yes, we ran out of sources
|| $type === self::TYPE_CSS // yes, to process CSS individually (avoiding PCRE bugs/limits)
|| $minifier !== $lastMinifier // yes, minifier changed
- || $options !== $lastOptions)) { // yes, options changed
+ || $options !== $lastOptions
+ )) { // yes, options changed
// minify previous sources with last settings
$imploded = implode($implodeSeparator, $groupToProcessTogether);
$groupToProcessTogether = array();
@@ -601,7 +603,7 @@ class Minify
try {
$content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
} catch (Exception $e) {
- throw new Exception("Exception in minifier: " . $e->getMessage());
+ throw new Exception('Exception in minifier: ' . $e->getMessage());
}
} else {
$content[] = $imploded;
@@ -618,7 +620,7 @@ class Minify
$content = implode($implodeSeparator, $content);
- if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
+ if ($type === self::TYPE_CSS && strpos($content, '@import') !== false) {
$content = $this->handleCssImports($content);
}
@@ -671,12 +673,11 @@ class Minify
if ($this->options['bubbleCssImports']) {
// bubble CSS imports
preg_match_all('/@import.*?;/', $css, $imports);
- $css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
- return $css;
+ return implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
}
- if ('' === $this->options['importWarning']) {
+ if ($this->options['importWarning'] === '') {
return $css;
}
@@ -684,8 +685,8 @@ class Minify
$noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
$lastImportPos = strrpos($noCommentCss, '@import');
$firstBlockPos = strpos($noCommentCss, '{');
- if (false !== $lastImportPos
- && false !== $firstBlockPos
+ if ($lastImportPos !== false
+ && $firstBlockPos !== false
&& $firstBlockPos < $lastImportPos
) {
// { appears before @import : prepend warning
@@ -738,7 +739,7 @@ class Minify
}
if (empty($options['contentType'])) {
- if (null === $type) {
+ if ($type === null) {
$type = 'text/plain';
}
$options['contentType'] = $type;
diff --git a/lib/Minify/App.php b/lib/Minify/App.php
index bc885b2..4f40d06 100644
--- a/lib/Minify/App.php
+++ b/lib/Minify/App.php
@@ -2,6 +2,7 @@
namespace Minify;
+use Minify;
use Minify_Cache_File;
use Minify_CacheInterface;
use Minify_Controller_MinApp;
@@ -9,11 +10,10 @@ use Minify_ControllerInterface;
use Minify_DebugDetector;
use Minify_Env;
use Minify_Source_Factory;
+use Monolog;
use Props\Container;
use Psr\Log\LoggerInterface;
use RuntimeException;
-use Monolog;
-use Minify;
/**
* @property Minify_CacheInterface $cache
@@ -34,7 +34,6 @@ use Minify;
*/
class App extends Container
{
-
/**
* Constructor
*
@@ -58,8 +57,9 @@ class App extends Container
}
$type = $that->typeOf($config->cachePath);
+
throw new RuntimeException('$min_cachePath must be a path or implement Minify_CacheInterface.'
- . " Given $type");
+ . " Given ${type}");
};
$this->config = function (App $app) {
@@ -76,14 +76,13 @@ class App extends Container
$propNames = array_keys(get_object_vars($config));
$prefixer = function ($name) {
- return "min_$name";
+ return "min_${name}";
};
$varNames = array_map($prefixer, $propNames);
$varDefined = get_defined_vars();
- $varNames = array_filter($varNames, function($name) use($varDefined)
- {
+ $varNames = array_filter($varNames, function ($name) use ($varDefined) {
return array_key_exists($name, $varDefined);
});
@@ -122,8 +121,9 @@ class App extends Container
}
$type = $that->typeOf($ctrl);
+
throw new RuntimeException('$min_factories["controller"] callable must return an implementation'
- ." of Minify_CacheInterface. Returned $type");
+ . " of Minify_CacheInterface. Returned ${type}");
};
$this->docRoot = function (App $app) {
@@ -140,7 +140,7 @@ class App extends Container
};
$this->errorLogHandler = function (App $app) {
- $format = "%channel%.%level_name%: %message% %context% %extra%";
+ $format = '%channel%.%level_name%: %message% %context% %extra%';
$handler = new Monolog\Handler\ErrorLogHandler();
$handler->setFormatter(new Monolog\Formatter\LineFormatter($format));
@@ -148,7 +148,7 @@ class App extends Container
};
$this->groupsConfig = function (App $app) {
- return (require $app->groupsConfigPath);
+ return require $app->groupsConfigPath;
};
$this->groupsConfigPath = "{$this->dir}/groupsConfig.php";
@@ -188,8 +188,9 @@ class App extends Container
}
$type = $that->typeOf($value);
+
throw new RuntimeException('If set, $min_errorLogger must be a PSR-3 logger or a Monolog handler.'
- ." Given $type");
+ . " Given ${type}");
};
$this->minify = function (App $app) use ($that) {
@@ -205,8 +206,9 @@ class App extends Container
}
$type = $that->typeOf($minify);
+
throw new RuntimeException('$min_factories["minify"] callable must return a Minify object.'
- ." Returned $type");
+ . " Returned ${type}");
};
$this->serveOptions = function (App $app) {
@@ -289,6 +291,7 @@ class App extends Container
/**
* @param mixed $var
+ *
* @return string
*/
private function typeOf($var)
diff --git a/lib/Minify/Build.php b/lib/Minify/Build.php
index d018d93..b6e7023 100644
--- a/lib/Minify/Build.php
+++ b/lib/Minify/Build.php
@@ -1,7 +1,6 @@
(time() + 86400 * 365)
* ));
*
- *
- * @package Minify
- * @author Stephen Clay
*/
class Minify_Build
{
-
/**
* Last modification time of all files in the build
*
@@ -64,8 +59,9 @@ class Minify_Build
*
*
* @param string $uri
- * @param boolean $forceAmpersand (default = false) Force the use of ampersand to
- * append the timestamp to the URI.
+ * @param bool $forceAmpersand (default = false) Force the use of ampersand to
+ * append the timestamp to the URI
+ *
* @return string
*/
public function uri($uri, $forceAmpersand = false)
@@ -79,16 +75,15 @@ class Minify_Build
* Create a build object
*
* @param array $sources array of Minify_Source objects and/or file paths
- *
*/
public function __construct($sources)
{
$max = 0;
- foreach ((array)$sources as $source) {
+ foreach ((array) $sources as $source) {
if ($source instanceof Minify_Source) {
$max = max($max, $source->getLastModified());
} elseif (is_string($source)) {
- if (0 === strpos($source, '//')) {
+ if (strpos($source, '//') === 0) {
$source = $_SERVER['DOCUMENT_ROOT'] . substr($source, 1);
}
if (is_file($source)) {
diff --git a/lib/Minify/CSS.php b/lib/Minify/CSS.php
index 22aaf2b..1e22e5e 100644
--- a/lib/Minify/CSS.php
+++ b/lib/Minify/CSS.php
@@ -1,7 +1,6 @@
- * @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
- *
* @deprecated Use Minify_CSSmin
*/
class Minify_CSS
{
-
/**
* Minify a CSS string
*
* @param string $css
- *
* @param array $options available options:
*
* 'preserveComments': (default true) multi-line comments that begin
@@ -59,13 +52,13 @@ class Minify_CSS
public static function minify($css, $options = array())
{
$options = array_merge(array(
- 'compress' => true,
- 'removeCharsets' => true,
- 'preserveComments' => true,
- 'currentDir' => null,
- 'docRoot' => $_SERVER['DOCUMENT_ROOT'],
+ 'compress' => true,
+ 'removeCharsets' => true,
+ 'preserveComments' => true,
+ 'currentDir' => null,
+ 'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
- 'symlinks' => array(),
+ 'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
@@ -73,7 +66,7 @@ class Minify_CSS
}
if ($options['compress']) {
- if (! $options['preserveComments']) {
+ if (!$options['preserveComments']) {
$css = Minify_CSS_Compressor::process($css, $options);
} else {
$processor = array('Minify_CSS_Compressor', 'process');
@@ -81,7 +74,7 @@ class Minify_CSS
}
}
- if (! $options['currentDir'] && ! $options['prependRelativePath']) {
+ if (!$options['currentDir'] && !$options['prependRelativePath']) {
return $css;
}
diff --git a/lib/Minify/CSS/Compressor.php b/lib/Minify/CSS/Compressor.php
index 3465061..a6eecb3 100644
--- a/lib/Minify/CSS/Compressor.php
+++ b/lib/Minify/CSS/Compressor.php
@@ -1,7 +1,6 @@
- * @author http://code.google.com/u/1stvamp/ (Issue 64 patch)
- *
* @deprecated Use CSSmin (tubalmartin/cssmin)
*/
class Minify_CSS_Compressor
{
-
/**
* Minify a CSS string
*
* @param string $css
- *
* @param array $options (currently ignored)
*
* @return string
@@ -48,7 +41,7 @@ class Minify_CSS_Compressor
/**
* @var array
*/
- protected $_options = null;
+ protected $_options;
/**
* Are we "in" a hack? I.e. are some browsers targetted until the next comment?
@@ -262,7 +255,7 @@ class Minify_CSS_Compressor
$pieces = preg_split('/(\'[^\']+\'|"[^"]+")/', $m[1], null, $flags);
$out = 'font-family:';
- while (null !== ($piece = array_shift($pieces))) {
+ while (($piece = array_shift($pieces)) !== null) {
if ($piece[0] !== '"' && $piece[0] !== "'") {
$piece = preg_replace('/\\s+/', ' ', $piece);
$piece = preg_replace('/\\s?,\\s?/', ',', $piece);
diff --git a/lib/Minify/CSS/UriRewriter.php b/lib/Minify/CSS/UriRewriter.php
index c3a63f0..cc69dfb 100644
--- a/lib/Minify/CSS/UriRewriter.php
+++ b/lib/Minify/CSS/UriRewriter.php
@@ -1,18 +1,13 @@
*/
class Minify_CSS_UriRewriter
{
-
/**
* rewrite() and rewriteRelative() append debugging information here
*
@@ -24,12 +19,9 @@ class Minify_CSS_UriRewriter
* In CSS content, rewrite file relative URIs as root relative
*
* @param string $css
- *
- * @param string $currentDir The directory of the current CSS file.
- *
- * @param string $docRoot The document root of the web site in which
- * the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
- *
+ * @param string $currentDir the directory of the current CSS file
+ * @param string $docRoot the document root of the web site in which
+ * the CSS file resides (default = $_SERVER['DOCUMENT_ROOT'])
* @param array $symlinks (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
@@ -58,10 +50,10 @@ class Minify_CSS_UriRewriter
self::$_symlinks[$link] = self::_realpath($target);
}
- self::$debugText .= "docRoot : " . self::$_docRoot . "\n"
- . "currentDir : " . self::$_currentDir . "\n";
+ self::$debugText .= 'docRoot : ' . self::$_docRoot . "\n"
+ . 'currentDir : ' . self::$_currentDir . "\n";
if (self::$_symlinks) {
- self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n";
+ self::$debugText .= 'symlinks : ' . var_export(self::$_symlinks, 1) . "\n";
}
self::$debugText .= "\n";
@@ -85,8 +77,7 @@ class Minify_CSS_UriRewriter
* In CSS content, prepend a path to relative URIs
*
* @param string $css
- *
- * @param string $path The path to prepend.
+ * @param string $path the path to prepend
*
* @return string
*/
@@ -97,7 +88,7 @@ class Minify_CSS_UriRewriter
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
-
+
// append
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
@@ -134,11 +125,8 @@ class Minify_CSS_UriRewriter
*
*
* @param string $uri file relative URI
- *
- * @param string $realCurrentDir realpath of the current file's directory.
- *
- * @param string $realDocRoot realpath of the site document root.
- *
+ * @param string $realCurrentDir realpath of the current file's directory
+ * @param string $realDocRoot realpath of the site document root
* @param array $symlinks (default = array()) If the file is stored in
* a symlink-ed directory, provide an array of link paths to
* real target paths, where the link paths "appear" to be within the document
@@ -161,7 +149,7 @@ class Minify_CSS_UriRewriter
// "unresolve" a symlink back to doc root
foreach ($symlinks as $link => $target) {
- if (0 === strpos($path, $target)) {
+ if (strpos($path, $target) === 0) {
// replace $target with $link
$path = $link . substr($path, strlen($target));
@@ -310,7 +298,7 @@ class Minify_CSS_UriRewriter
$root = '';
$rootRelative = $uri;
$uri = $root . self::removeDots($rootRelative);
- } elseif (preg_match('@^((https?\:)?//([^/]+))/@', $uri, $m) && (false !== strpos($m[3], '.'))) {
+ } elseif (preg_match('@^((https?\:)?//([^/]+))/@', $uri, $m) && (strpos($m[3], '.') !== false)) {
$root = $m[1];
$rootRelative = substr($uri, strlen($root));
$uri = $root . self::removeDots($rootRelative);
@@ -320,18 +308,19 @@ class Minify_CSS_UriRewriter
if ($isImport) {
return "@import {$quoteChar}{$uri}{$quoteChar}";
- } else {
- return "url({$quoteChar}{$uri}{$quoteChar})";
}
+
+ return "url({$quoteChar}{$uri}{$quoteChar})";
}
/**
* Mungs some inline SVG URL declarations so they won't be touched
*
- * @link https://github.com/mrclay/minify/issues/517
+ * @see https://github.com/mrclay/minify/issues/517
* @see _unOwlify
*
* @param string $css
+ *
* @return string
*/
private static function _owlifySvgPaths($css)
@@ -347,6 +336,7 @@ class Minify_CSS_UriRewriter
* @see _owlifySvgPaths
*
* @param string $css
+ *
* @return string
*/
private static function _unOwlify($css)
diff --git a/lib/Minify/CSSmin.php b/lib/Minify/CSSmin.php
index 753c510..aae26a2 100644
--- a/lib/Minify/CSSmin.php
+++ b/lib/Minify/CSSmin.php
@@ -1,27 +1,20 @@
*/
class Minify_CSSmin
{
-
/**
* Minify a CSS string
*
* @param string $css
- *
* @param array $options available options:
*
* 'removeCharsets': (default true) remove all @charset at-rules
@@ -53,12 +46,12 @@ class Minify_CSSmin
public static function minify($css, $options = array())
{
$options = array_merge(array(
- 'compress' => true,
- 'removeCharsets' => true,
- 'currentDir' => null,
- 'docRoot' => $_SERVER['DOCUMENT_ROOT'],
+ 'compress' => true,
+ 'removeCharsets' => true,
+ 'currentDir' => null,
+ 'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
- 'symlinks' => array(),
+ 'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
@@ -68,21 +61,21 @@ class Minify_CSSmin
$obj = new CSSmin();
$css = $obj->run($css);
}
- if (! $options['currentDir'] && ! $options['prependRelativePath']) {
+ if (!$options['currentDir'] && !$options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
return Minify_CSS_UriRewriter::rewrite(
- $css
- ,$options['currentDir']
- ,$options['docRoot']
- ,$options['symlinks']
+ $css,
+ $options['currentDir'],
+ $options['docRoot'],
+ $options['symlinks']
);
}
return Minify_CSS_UriRewriter::prepend(
- $css
- ,$options['prependRelativePath']
+ $css,
+ $options['prependRelativePath']
);
}
}
diff --git a/lib/Minify/Cache/APC.php b/lib/Minify/Cache/APC.php
index 85a0b49..e707e50 100644
--- a/lib/Minify/Cache/APC.php
+++ b/lib/Minify/Cache/APC.php
@@ -1,7 +1,6 @@
*
- * @package Minify
- * @author Chris Edwards
**/
class Minify_Cache_APC implements Minify_CacheInterface
{
-
/**
* Create a Minify_Cache_APC object, to be passed to
* Minify::setCache().
*
- *
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*
@@ -36,7 +31,6 @@ class Minify_Cache_APC implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id
- *
* @param string $data
*
* @return bool success
@@ -55,29 +49,28 @@ class Minify_Cache_APC implements Minify_CacheInterface
*/
public function getSize($id)
{
- if (! $this->_fetch($id)) {
+ if (!$this->_fetch($id)) {
return false;
}
- if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
+ if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
- } else {
- return strlen($this->_data);
}
+
+ return strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
- *
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
- return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
+ return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -102,12 +95,14 @@ class Minify_Cache_APC implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
- private $_exp = null;
+ private $_exp;
// cache of most recently fetched id
- private $_lm = null;
- private $_data = null;
- private $_id = null;
+ private $_lm;
+
+ private $_data;
+
+ private $_id;
/**
* Fetch data and timestamp from apc, store in instance
@@ -122,7 +117,7 @@ class Minify_Cache_APC implements Minify_CacheInterface
return true;
}
$ret = apc_fetch($id);
- if (false === $ret) {
+ if ($ret === false) {
$this->_id = null;
return false;
diff --git a/lib/Minify/Cache/File.php b/lib/Minify/Cache/File.php
index 8d56fc9..9132f7f 100644
--- a/lib/Minify/Cache/File.php
+++ b/lib/Minify/Cache/File.php
@@ -1,14 +1,11 @@
locking = $fileLocking;
@@ -47,7 +44,6 @@ class Minify_Cache_File implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
- *
* @param string $data
*
* @return bool success
@@ -57,14 +53,14 @@ class Minify_Cache_File implements Minify_CacheInterface
$flag = $this->locking ? LOCK_EX : null;
$file = $this->path . '/' . $id;
- if (! @file_put_contents($file, $data, $flag)) {
- $this->logger->warning("Minify_Cache_File: Write failed to '$file'");
+ if (!@file_put_contents($file, $data, $flag)) {
+ $this->logger->warning("Minify_Cache_File: Write failed to '${file}'");
}
// write control
if ($data !== $this->fetch($id)) {
@unlink($file);
- $this->logger->warning("Minify_Cache_File: Post-write read failed for '$file'");
+ $this->logger->warning("Minify_Cache_File: Post-write read failed for '${file}'");
return false;
}
@@ -88,7 +84,6 @@ class Minify_Cache_File implements Minify_CacheInterface
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
- *
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
@@ -97,7 +92,7 @@ class Minify_Cache_File implements Minify_CacheInterface
{
$file = $this->path . '/' . $id;
- return (is_file($file) && (filemtime($file) >= $srcMtime));
+ return is_file($file) && (filemtime($file) >= $srcMtime);
}
/**
@@ -160,6 +155,7 @@ class Minify_Cache_File implements Minify_CacheInterface
* Get a usable temp directory
*
* @return string
+ *
* @deprecated
*/
public static function tmp()
@@ -171,8 +167,11 @@ class Minify_Cache_File implements Minify_CacheInterface
/**
* Send message to the Minify logger
+ *
* @param string $msg
+ *
* @return null
+ *
* @deprecated Use $this->logger
*/
protected function _log($msg)
diff --git a/lib/Minify/Cache/Memcache.php b/lib/Minify/Cache/Memcache.php
index d70dd07..6de7502 100644
--- a/lib/Minify/Cache/Memcache.php
+++ b/lib/Minify/Cache/Memcache.php
@@ -1,7 +1,6 @@
_fetch($id)) {
+ if (!$this->_fetch($id)) {
return false;
}
- if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
+ if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
- } else {
- return strlen($this->_data);
}
+
+ return strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
- *
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
- return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
+ return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -105,13 +100,16 @@ class Minify_Cache_Memcache implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
- private $_mc = null;
- private $_exp = null;
+ private $_mc;
+
+ private $_exp;
// cache of most recently fetched id
- private $_lm = null;
- private $_data = null;
- private $_id = null;
+ private $_lm;
+
+ private $_data;
+
+ private $_id;
/**
* Fetch data and timestamp from memcache, store in instance
@@ -127,7 +125,7 @@ class Minify_Cache_Memcache implements Minify_CacheInterface
}
$ret = $this->_mc->get($id);
- if (false === $ret) {
+ if ($ret === false) {
$this->_id = null;
return false;
diff --git a/lib/Minify/Cache/Null.php b/lib/Minify/Cache/Null.php
index 4f654a6..ba9b42f 100644
--- a/lib/Minify/Cache/Null.php
+++ b/lib/Minify/Cache/Null.php
@@ -5,8 +5,6 @@
*
* If this is used, Minify will not use a cache and, for each 200 response, will
* need to recombine files, minify and encode the output.
- *
- * @package Minify
*/
class Minify_Cache_Null implements Minify_CacheInterface
{
@@ -64,4 +62,4 @@ class Minify_Cache_Null implements Minify_CacheInterface
public function fetch($id)
{
}
-}
\ No newline at end of file
+}
diff --git a/lib/Minify/Cache/WinCache.php b/lib/Minify/Cache/WinCache.php
index 46e285a..0da212a 100644
--- a/lib/Minify/Cache/WinCache.php
+++ b/lib/Minify/Cache/WinCache.php
@@ -1,7 +1,6 @@
*
- * @package Minify
- * @author Matthias Fax
**/
class Minify_Cache_WinCache implements Minify_CacheInterface
{
@@ -28,7 +25,7 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
public function __construct($expire = 0)
{
if (!function_exists('wincache_ucache_info')) {
- throw new Exception("WinCache for PHP is not installed to be able to use Minify_Cache_WinCache!");
+ throw new Exception('WinCache for PHP is not installed to be able to use Minify_Cache_WinCache!');
}
$this->_exp = $expire;
}
@@ -37,7 +34,6 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id
- *
* @param string $data
*
* @return bool success
@@ -62,23 +58,22 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
- } else {
- return strlen($this->_data);
}
+
+ return strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
- *
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
- return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
+ return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -103,12 +98,14 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
- private $_exp = null;
+ private $_exp;
// cache of most recently fetched id
- private $_lm = null;
- private $_data = null;
- private $_id = null;
+ private $_lm;
+
+ private $_data;
+
+ private $_id;
/**
* Fetch data and timestamp from WinCache, store in instance
@@ -136,4 +133,4 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
return true;
}
-}
\ No newline at end of file
+}
diff --git a/lib/Minify/Cache/XCache.php b/lib/Minify/Cache/XCache.php
index f293cb3..7c91c51 100644
--- a/lib/Minify/Cache/XCache.php
+++ b/lib/Minify/Cache/XCache.php
@@ -2,8 +2,7 @@
/**
* Class Minify_Cache_XCache
*
- * @link http://xcache.lighttpd.net/
- * @package Minify
+ * @see http://xcache.lighttpd.net/
*/
/**
@@ -14,12 +13,9 @@
* Minify::setCache(new Minify_Cache_XCache());
*
*
- * @package Minify
- * @author Elan Ruusamäe
**/
class Minify_Cache_XCache implements Minify_CacheInterface
{
-
/**
* Create a Minify_Cache_XCache object, to be passed to
* Minify::setCache().
@@ -37,6 +33,7 @@ class Minify_Cache_XCache implements Minify_CacheInterface
*
* @param string $id cache id
* @param string $data
+ *
* @return bool success
*/
public function store($id, $data)
@@ -48,19 +45,20 @@ class Minify_Cache_XCache implements Minify_CacheInterface
* Get the size of a cache entry
*
* @param string $id cache id
+ *
* @return int size in bytes
*/
public function getSize($id)
{
- if (! $this->_fetch($id)) {
+ if (!$this->_fetch($id)) {
return false;
}
- if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
+ if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
- } else {
- return strlen($this->_data);
}
+
+ return strlen($this->_data);
}
/**
@@ -68,11 +66,12 @@ class Minify_Cache_XCache implements Minify_CacheInterface
*
* @param string $id cache id
* @param int $srcMtime mtime of the original source file(s)
+ *
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
- return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
+ return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -89,6 +88,7 @@ class Minify_Cache_XCache implements Minify_CacheInterface
* Fetch the cached content
*
* @param string $id cache id
+ *
* @return string
*/
public function fetch($id)
@@ -96,17 +96,20 @@ class Minify_Cache_XCache implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
- private $_exp = null;
+ private $_exp;
// cache of most recently fetched id
- private $_lm = null;
- private $_data = null;
- private $_id = null;
+ private $_lm;
+
+ private $_data;
+
+ private $_id;
/**
* Fetch data and timestamp from xcache, store in instance
*
* @param string $id
+ *
* @return bool success
*/
private function _fetch($id)
@@ -116,7 +119,7 @@ class Minify_Cache_XCache implements Minify_CacheInterface
}
$ret = xcache_get($id);
- if (false === $ret) {
+ if ($ret === false) {
$this->_id = null;
return false;
diff --git a/lib/Minify/Cache/ZendPlatform.php b/lib/Minify/Cache/ZendPlatform.php
index 76e9920..5690c3d 100644
--- a/lib/Minify/Cache/ZendPlatform.php
+++ b/lib/Minify/Cache/ZendPlatform.php
@@ -1,7 +1,6 @@
* Minify::setCache(new Minify_Cache_ZendPlatform());
*
- *
- * @package Minify
- * @author Patrick van Dissel
*/
class Minify_Cache_ZendPlatform implements Minify_CacheInterface
{
-
/**
* Create a Minify_Cache_ZendPlatform object, to be passed to
* Minify::setCache().
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
- *
*/
public function __construct($expire = 0)
{
@@ -36,7 +30,6 @@ class Minify_Cache_ZendPlatform implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id
- *
* @param string $data
*
* @return bool success
@@ -62,14 +55,13 @@ class Minify_Cache_ZendPlatform implements Minify_CacheInterface
* Does a valid cache entry exist?
*
* @param string $id cache id
- *
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
- return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
+ return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -94,12 +86,14 @@ class Minify_Cache_ZendPlatform implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
- private $_exp = null;
+ private $_exp;
// cache of most recently fetched id
- private $_lm = null;
- private $_data = null;
- private $_id = null;
+ private $_lm;
+
+ private $_data;
+
+ private $_id;
/**
* Fetch data and timestamp from ZendPlatform, store in instance
@@ -115,7 +109,7 @@ class Minify_Cache_ZendPlatform implements Minify_CacheInterface
}
$ret = output_cache_get($id, $this->_exp);
- if (false === $ret) {
+ if ($ret === false) {
$this->_id = null;
return false;
diff --git a/lib/Minify/CacheInterface.php b/lib/Minify/CacheInterface.php
index 1b891b1..52389f2 100644
--- a/lib/Minify/CacheInterface.php
+++ b/lib/Minify/CacheInterface.php
@@ -1,13 +1,10 @@
- *
- * @package Minify
- * @author Stephen Clay
- * @author Elan Ruusamäe
*/
class Minify_ClosureCompiler
{
@@ -60,9 +55,9 @@ class Minify_ClosureCompiler
* @var array
*/
public static $defaultOptions = array(
- 'charset' => 'utf-8',
+ 'charset' => 'utf-8',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
- 'warning_level' => 'QUIET',
+ 'warning_level' => 'QUIET',
);
/**
@@ -70,9 +65,12 @@ class Minify_ClosureCompiler
*
* @param string $js
* @param array $options (verbose is ignored)
+ *
* @see https://code.google.com/p/closure-compiler/source/browse/trunk/README
- * @return string
+ *
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return string
*/
public static function minify($js, $options = array())
{
@@ -86,17 +84,21 @@ class Minify_ClosureCompiler
*
* @param string $js
* @param array $options
- * @return string
+ *
* @throws Exception
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return string
*/
public function process($js, $options)
{
$tmpFile = $this->dumpFile(self::$tempDir, $js);
+
try {
$result = $this->compile($tmpFile, $options);
} catch (Exception $e) {
unlink($tmpFile);
+
throw $e;
}
unlink($tmpFile);
@@ -107,8 +109,10 @@ class Minify_ClosureCompiler
/**
* @param string $tmpFile
* @param array $options
- * @return string
+ *
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return string
*/
protected function compile($tmpFile, $options)
{
@@ -120,6 +124,7 @@ class Minify_ClosureCompiler
/**
* @param array $userOptions
* @param string $tmpFile
+ *
* @return string
*/
protected function getCommand($userOptions, $tmpFile)
@@ -133,23 +138,24 @@ class Minify_ClosureCompiler
}
/**
- * @return array
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return array
*/
protected function getCompilerCommandLine()
{
$this->checkJar(self::$jarFile);
- $server = array(
+
+ return array(
self::$javaExecutable,
'-jar',
- escapeshellarg(self::$jarFile)
+ escapeshellarg(self::$jarFile),
);
-
- return $server;
}
/**
* @param array $userOptions
+ *
* @return array
*/
protected function getOptionsCommandLine($userOptions)
@@ -170,6 +176,7 @@ class Minify_ClosureCompiler
/**
* @param string $jarFile
+ *
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkJar($jarFile)
@@ -184,6 +191,7 @@ class Minify_ClosureCompiler
/**
* @param string $tempDir
+ *
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkTempdir($tempDir)
@@ -201,8 +209,10 @@ class Minify_ClosureCompiler
*
* @param string $dir
* @param string $content
- * @return string
+ *
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return string
*/
protected function dumpFile($dir, $content)
{
@@ -221,14 +231,16 @@ class Minify_ClosureCompiler
*
* @param string $command
* @param array $expectedCodes
- * @return mixed
+ *
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return mixed
*/
protected function shell($command, $expectedCodes = array(0))
{
exec($command, $output, $result_code);
if (!in_array($result_code, $expectedCodes)) {
- throw new Minify_ClosureCompiler_Exception("Unpexpected return code: $result_code");
+ throw new Minify_ClosureCompiler_Exception("Unpexpected return code: ${result_code}");
}
return $output;
diff --git a/lib/Minify/CommentPreserver.php b/lib/Minify/CommentPreserver.php
index 6bdb6f3..9c71f36 100644
--- a/lib/Minify/CommentPreserver.php
+++ b/lib/Minify/CommentPreserver.php
@@ -1,18 +1,13 @@
*/
class Minify_CommentPreserver
{
-
/**
* String to be prepended to each preserved comment
*
@@ -38,6 +33,7 @@ class Minify_CommentPreserver
* @param callback $processor function
* @param array $args array of extra arguments to pass to the processor
* function (default = array())
+ *
* @return string
*/
public static function process($content, $processor, $args = array())
@@ -45,12 +41,12 @@ class Minify_CommentPreserver
$ret = '';
while (true) {
list($beforeComment, $comment, $afterComment) = self::_nextComment($content);
- if ('' !== $beforeComment) {
+ if ($beforeComment !== '') {
$callArgs = $args;
array_unshift($callArgs, $beforeComment);
$ret .= call_user_func_array($processor, $callArgs);
}
- if (false === $comment) {
+ if ($comment === false) {
break;
}
$ret .= $comment;
@@ -72,7 +68,7 @@ class Minify_CommentPreserver
*/
private static function _nextComment($in)
{
- if (false === ($start = strpos($in, '/*!')) || false === ($end = strpos($in, '*/', $start + 3))) {
+ if (($start = strpos($in, '/*!')) === false || ($end = strpos($in, '*/', $start + 3)) === false) {
return array($in, false, false);
}
@@ -80,7 +76,7 @@ class Minify_CommentPreserver
$comment = self::$prepend . '/*!' . substr($in, $start + 3, $end - $start - 1) . self::$append;
$endChars = (strlen($in) - $end - 2);
- $afterComment = (0 === $endChars) ? '' : substr($in, -$endChars);
+ $afterComment = ($endChars === 0) ? '' : substr($in, -$endChars);
return array($beforeComment, $comment, $afterComment);
}
diff --git a/lib/Minify/Config.php b/lib/Minify/Config.php
index ae5b58c..ed3e6fb 100644
--- a/lib/Minify/Config.php
+++ b/lib/Minify/Config.php
@@ -37,7 +37,7 @@ class Config
public $allowDebugFlag = false;
/**
- * @var string|Minify_CacheInterface
+ * @var Minify_CacheInterface|string
*/
public $cachePath = '';
diff --git a/lib/Minify/Controller/Base.php b/lib/Minify/Controller/Base.php
index 54a60c9..aea4b86 100644
--- a/lib/Minify/Controller/Base.php
+++ b/lib/Minify/Controller/Base.php
@@ -1,23 +1,17 @@
*/
abstract class Minify_Controller_Base implements Minify_ControllerInterface
{
-
/**
* @var Minify_Env
*/
@@ -63,6 +57,7 @@ abstract class Minify_Controller_Base implements Minify_ControllerInterface
* @param string $msg
*
* @return null
+ *
* @deprecated use $this->logger
*/
public function log($msg)
diff --git a/lib/Minify/Controller/Files.php b/lib/Minify/Controller/Files.php
index 85a76d0..ae48cfb 100644
--- a/lib/Minify/Controller/Files.php
+++ b/lib/Minify/Controller/Files.php
@@ -1,11 +1,8 @@
- *
- * @package Minify
- * @author Stephen Clay
*/
class Minify_Controller_Files extends Minify_Controller_Base
{
-
/**
* Set up file sources
*
* @param array $options controller and Minify options
+ *
* @return Minify_ServeConfiguration
*
* Controller options:
@@ -49,8 +43,8 @@ class Minify_Controller_Files extends Minify_Controller_Base
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
- } elseif (! is_array($files)) {
- $files = (array)$files;
+ } elseif (!is_array($files)) {
+ $files = (array) $files;
}
unset($options['files']);
@@ -68,4 +62,3 @@ class Minify_Controller_Files extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources);
}
}
-
diff --git a/lib/Minify/Controller/Groups.php b/lib/Minify/Controller/Groups.php
index af8af33..348118e 100644
--- a/lib/Minify/Controller/Groups.php
+++ b/lib/Minify/Controller/Groups.php
@@ -1,7 +1,6 @@
*/
class Minify_Controller_Groups extends Minify_Controller_Files
{
-
/**
* Set up groups of files as sources
*
@@ -53,9 +48,9 @@ class Minify_Controller_Groups extends Minify_Controller_Files
$pathInfo = false;
}
- if (false === $pathInfo || ! isset($groups[$pathInfo])) {
+ if ($pathInfo === false || !isset($groups[$pathInfo])) {
// no PATH_INFO or not a valid group
- $this->logger->info("Missing PATH_INFO or no group set for \"$pathInfo\"");
+ $this->logger->info("Missing PATH_INFO or no group set for \"${pathInfo}\"");
return new Minify_ServeConfiguration($options);
}
@@ -64,8 +59,8 @@ class Minify_Controller_Groups extends Minify_Controller_Files
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
- } elseif (! is_array($files)) {
- $files = (array)$files;
+ } elseif (!is_array($files)) {
+ $files = (array) $files;
}
$options['files'] = $files;
@@ -73,4 +68,3 @@ class Minify_Controller_Groups extends Minify_Controller_Files
return parent::createConfiguration($options);
}
}
-
diff --git a/lib/Minify/Controller/MinApp.php b/lib/Minify/Controller/MinApp.php
index e8440fe..5d5f92a 100644
--- a/lib/Minify/Controller/MinApp.php
+++ b/lib/Minify/Controller/MinApp.php
@@ -1,18 +1,13 @@
*/
class Minify_Controller_MinApp extends Minify_Controller_Base
{
-
/**
* Set up groups of files as sources
*
@@ -26,15 +21,15 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$get = $this->env->get();
foreach (array('g', 'b', 'f') as $key) {
if (isset($get[$key])) {
- $get[$key] = str_replace("\x00", '', (string)$get[$key]);
+ $get[$key] = str_replace("\x00", '', (string) $get[$key]);
}
}
// filter controller options
$defaults = array(
'groupsOnly' => false,
- 'groups' => array(),
- 'symlinks' => array(),
+ 'groups' => array(),
+ 'symlinks' => array(),
);
$minApp = isset($options['minApp']) ? $options['minApp'] : array();
$localOptions = array_merge($defaults, $minApp);
@@ -44,7 +39,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// normalize $symlinks in order to map to target
$symlinks = array();
foreach ($localOptions['symlinks'] as $link => $target) {
- if (0 === strpos($link, '//')) {
+ if (strpos($link, '//') === 0) {
$link = rtrim(substr($link, 1), '/') . '/';
$target = rtrim($target, '/\\');
$symlinks[$link] = $target;
@@ -60,12 +55,12 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$selectionId .= 'g=' . $get['g'];
$keys = explode(',', $get['g']);
if ($keys != array_unique($keys)) {
- $this->logger->info("Duplicate group key found.");
+ $this->logger->info('Duplicate group key found.');
return new Minify_ServeConfiguration($options);
}
foreach ($keys as $key) {
- if (! isset($localOptions['groups'][$key])) {
+ if (!isset($localOptions['groups'][$key])) {
$this->logger->info("A group configuration for \"{$key}\" was not found");
return new Minify_ServeConfiguration($options);
@@ -74,8 +69,8 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
- } elseif (! is_array($files)) {
- $files = (array)$files;
+ } elseif (!is_array($files)) {
+ $files = (array) $files;
}
foreach ($files as $file) {
try {
@@ -83,20 +78,20 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$sources[] = $source;
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
- if (null === $firstMissing) {
+ if ($firstMissing === null) {
$firstMissing = basename($file);
- continue;
- } else {
- $secondMissing = basename($file);
- $this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing'");
- return new Minify_ServeConfiguration($options);
+ continue;
}
+ $secondMissing = basename($file);
+ $this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}'");
+
+ return new Minify_ServeConfiguration($options);
}
}
}
}
- if (! $localOptions['groupsOnly'] && isset($get['f'])) {
+ if (!$localOptions['groupsOnly'] && isset($get['f'])) {
// try user files
// The following restrictions are to limit the URLs that minify will
// respond to.
@@ -115,7 +110,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$ext = ".{$m[1]}";
$files = explode(',', $get['f']);
if ($files != array_unique($files)) {
- $this->logger->info("Duplicate files were specified");
+ $this->logger->info('Duplicate files were specified');
return new Minify_ServeConfiguration($options);
}
@@ -123,7 +118,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
if (isset($get['b'])) {
// check for validity
$isValidBase = preg_match('@^[^/]+(?:/[^/]+)*$@', $get['b']);
- $hasDots = false !== strpos($get['b'], '..');
+ $hasDots = strpos($get['b'], '..') !== false;
$isDot = $get['b'] === '.';
if ($isValidBase && !$hasDots && !$isDot) {
@@ -145,8 +140,9 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// try to rewrite path
foreach ($symlinks as $link => $target) {
- if (0 === strpos($uri, $link)) {
+ if (strpos($uri, $link) === 0) {
$path = $target . DIRECTORY_SEPARATOR . substr($uri, strlen($link));
+
break;
}
}
@@ -157,15 +153,15 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$basenames[] = basename($path, $ext);
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
- if (null === $firstMissing) {
+ if ($firstMissing === null) {
$firstMissing = $uri;
- continue;
- } else {
- $secondMissing = $uri;
- $this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing`'");
- return new Minify_ServeConfiguration($options);
+ continue;
}
+ $secondMissing = $uri;
+ $this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}`'");
+
+ return new Minify_ServeConfiguration($options);
}
}
if ($selectionId) {
@@ -175,18 +171,18 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
}
if (!$sources) {
- $this->logger->info("No sources to serve");
+ $this->logger->info('No sources to serve');
return new Minify_ServeConfiguration($options);
}
- if (null !== $firstMissing) {
+ if ($firstMissing !== null) {
array_unshift($sources, new Minify_Source(array(
'id' => 'missingFile',
// should not cause cache invalidation
'lastModified' => 0,
// due to caching, filename is unreliable.
- 'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n",
+ 'content' => '/* Minify: at least one missing file. See ' . Minify::URL_DEBUG . " */\n",
'minifier' => 'Minify::nullMinifier',
)));
}
diff --git a/lib/Minify/Controller/Page.php b/lib/Minify/Controller/Page.php
index 7001fe0..f571007 100644
--- a/lib/Minify/Controller/Page.php
+++ b/lib/Minify/Controller/Page.php
@@ -1,23 +1,20 @@
+ * @see http://code.google.com/p/minify/source/browse/trunk/web/examples/1/index.php#59
*/
class Minify_Controller_Page extends Minify_Controller_Base
{
-
/**
* Set up source of HTML content
*
* @param array $options controller and Minify options
+ *
* @return array Minify options
*
* Controller options:
@@ -36,14 +33,14 @@ class Minify_Controller_Page extends Minify_Controller_Base
{
if (isset($options['file'])) {
$sourceSpec = array(
- 'filepath' => $options['file']
+ 'filepath' => $options['file'],
);
$f = $options['file'];
} else {
// strip controller options
$sourceSpec = array(
'content' => $options['content'],
- 'id' => $options['id'],
+ 'id' => $options['id'],
);
$f = $options['id'];
unset($options['content'], $options['id']);
@@ -55,7 +52,7 @@ class Minify_Controller_Page extends Minify_Controller_Base
// this will be the 2nd argument passed to Minify_HTML::minify()
$sourceSpec['minifyOptions'] = array(
'cssMinifier' => array('Minify_CSSmin', 'minify'),
- 'jsMinifier' => array('JSMin\\JSMin', 'minify'),
+ 'jsMinifier' => array('JSMin\\JSMin', 'minify'),
);
unset($options['minifyAll']);
}
@@ -66,4 +63,3 @@ class Minify_Controller_Page extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}
-
diff --git a/lib/Minify/ControllerInterface.php b/lib/Minify/ControllerInterface.php
index 35b4de3..bfb8591 100644
--- a/lib/Minify/ControllerInterface.php
+++ b/lib/Minify/ControllerInterface.php
@@ -1,9 +1,7 @@
*/
class Minify_DebugDetector
{
diff --git a/lib/Minify/Env.php b/lib/Minify/Env.php
index 84e7a0e..14ddaa0 100644
--- a/lib/Minify/Env.php
+++ b/lib/Minify/Env.php
@@ -2,7 +2,6 @@
class Minify_Env
{
-
/**
* @return string
*/
@@ -23,8 +22,8 @@ class Minify_Env
{
$options = array_merge(array(
'server' => $_SERVER,
- 'get' => $_GET,
- 'post' => $_POST,
+ 'get' => $_GET,
+ 'post' => $_POST,
'cookie' => $_COOKIE,
), $options);
@@ -43,7 +42,7 @@ class Minify_Env
public function server($key = null)
{
- if (null === $key) {
+ if ($key === null) {
return $this->server;
}
@@ -52,7 +51,7 @@ class Minify_Env
public function cookie($key = null, $default = null)
{
- if (null === $key) {
+ if ($key === null) {
return $this->cookie;
}
@@ -61,7 +60,7 @@ class Minify_Env
public function get($key = null, $default = null)
{
- if (null === $key) {
+ if ($key === null) {
return $this->get;
}
@@ -70,7 +69,7 @@ class Minify_Env
public function post($key = null, $default = null)
{
- if (null === $key) {
+ if ($key === null) {
return $this->post;
}
@@ -103,19 +102,23 @@ class Minify_Env
}
protected $server;
+
protected $get;
+
protected $post;
+
protected $cookie;
/**
* Compute $_SERVER['DOCUMENT_ROOT'] for IIS using SCRIPT_FILENAME and SCRIPT_NAME.
*
* @param array $server
+ *
* @return string
*/
protected function computeDocRoot(array $server)
{
- if (isset($server['SERVER_SOFTWARE']) && 0 !== strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
+ if (isset($server['SERVER_SOFTWARE']) && strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/') !== 0) {
throw new InvalidArgumentException('DOCUMENT_ROOT is not provided and could not be computed');
}
diff --git a/lib/Minify/HTML.php b/lib/Minify/HTML.php
index df648e1..83bc59f 100644
--- a/lib/Minify/HTML.php
+++ b/lib/Minify/HTML.php
@@ -1,7 +1,6 @@
*/
class Minify_HTML
{
/**
- * @var boolean
+ * @var bool
*/
protected $_jsCleanComments = true;
@@ -27,7 +23,6 @@ class Minify_HTML
* "Minify" an HTML page
*
* @param string $html
- *
* @param array $options
*
* 'cssMinifier' : (optional) callback function to process content of STYLE
@@ -52,7 +47,6 @@ class Minify_HTML
* Create a minifier object
*
* @param string $html
- *
* @param array $options
*
* 'cssMinifier' : (optional) callback function to process content of STYLE
@@ -70,7 +64,7 @@ class Minify_HTML
{
$this->_html = str_replace("\r\n", "\n", trim($html));
if (isset($options['xhtml'])) {
- $this->_isXhtml = (bool)$options['xhtml'];
+ $this->_isXhtml = (bool) $options['xhtml'];
}
if (isset($options['cssMinifier'])) {
$this->_cssMinifier = $options['cssMinifier'];
@@ -79,7 +73,7 @@ class Minify_HTML
$this->_jsMinifier = $options['jsMinifier'];
}
if (isset($options['jsCleanComments'])) {
- $this->_jsCleanComments = (bool)$options['jsCleanComments'];
+ $this->_jsCleanComments = (bool) $options['jsCleanComments'];
}
}
@@ -91,7 +85,7 @@ class Minify_HTML
public function process()
{
if ($this->_isXhtml === null) {
- $this->_isXhtml = (false !== strpos($this->_html, '_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
@@ -99,32 +93,34 @@ class Minify_HTML
// replace SCRIPTs (and minify) with placeholders
$this->_html = preg_replace_callback(
- '/(\\s*){$ws2}"
: "{$ws1}{$openScript}{$js}{$ws2}"
);
@@ -246,13 +249,13 @@ class Minify_HTML
protected function _removeCdata($str)
{
- return (false !== strpos($str, ''), '', $str)
: $str;
}
protected function _needsCdata($str)
{
- return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/u', $str));
+ return $this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/u', $str);
}
}
diff --git a/lib/Minify/HTML/Helper.php b/lib/Minify/HTML/Helper.php
index bfded8b..28c67ca 100644
--- a/lib/Minify/HTML/Helper.php
+++ b/lib/Minify/HTML/Helper.php
@@ -1,25 +1,23 @@
*/
class Minify_HTML_Helper
{
public $rewriteWorks = true;
+
public $minAppUri = '/min';
+
public $groupsConfigFile = '';
/**
* Get an HTML-escaped Minify URI for a group or set of files
*
- * @param string|array $keyOrFiles a group key or array of filepaths/URIs
+ * @param array|string $keyOrFiles a group key or array of filepaths/URIs
* @param array $opts options:
* 'farExpires' : (default true) append a modified timestamp for cache revving
* 'debug' : (default false) append debug flag
@@ -27,20 +25,21 @@ class Minify_HTML_Helper
* 'minAppUri' : (default '/min') URI of min directory
* 'rewriteWorks' : (default true) does mod_rewrite work in min app?
* 'groupsConfigFile' : specify if different
+ *
* @return string
*/
public static function getUri($keyOrFiles, $opts = array())
{
$opts = array_merge(array( // default options
- 'farExpires' => true,
- 'debug' => false,
- 'charset' => 'UTF-8',
- 'minAppUri' => '/min',
- 'rewriteWorks' => true,
+ 'farExpires' => true,
+ 'debug' => false,
+ 'charset' => 'UTF-8',
+ 'minAppUri' => '/min',
+ 'rewriteWorks' => true,
'groupsConfigFile' => self::app()->groupsConfigPath,
), $opts);
- $h = new self;
+ $h = new self();
$h->minAppUri = $opts['minAppUri'];
$h->rewriteWorks = $opts['rewriteWorks'];
$h->groupsConfigFile = $opts['groupsConfigFile'];
@@ -60,24 +59,25 @@ class Minify_HTML_Helper
*
* @param bool $farExpires
* @param bool $debug
+ *
* @return string
*/
public function getRawUri($farExpires = true, $debug = false)
{
$path = rtrim($this->minAppUri, '/') . '/';
- if (! $this->rewriteWorks) {
+ if (!$this->rewriteWorks) {
$path .= '?';
}
- if (null === $this->_groupKey) {
+ if ($this->_groupKey === null) {
// @todo: implement shortest uri
$path = self::_getShortestUri($this->_filePaths, $path);
} else {
- $path .= "g=" . $this->_groupKey;
+ $path .= 'g=' . $this->_groupKey;
}
if ($debug) {
- $path .= "&debug";
+ $path .= '&debug';
} elseif ($farExpires && $this->_lastModified) {
- $path .= "&" . $this->_lastModified;
+ $path .= '&' . $this->_lastModified;
}
return $path;
@@ -97,9 +97,9 @@ class Minify_HTML_Helper
}
// normalize paths like in /min/f=
foreach ($files as $k => $file) {
- if (0 === strpos($file, '//')) {
+ if (strpos($file, '//') === 0) {
$file = substr($file, 2);
- } elseif (0 === strpos($file, '/') || 1 === strpos($file, ':\\')) {
+ } elseif (strpos($file, '/') === 0 || strpos($file, ':\\') === 1) {
$file = substr($file, strlen(self::app()->env->getDocRoot()) + 1);
}
$file = strtr($file, '\\', '/');
@@ -118,7 +118,7 @@ class Minify_HTML_Helper
{
$this->_groupKey = $key;
if ($checkLastModified) {
- if (! $this->groupsConfigFile) {
+ if (!$this->groupsConfigFile) {
$this->groupsConfigFile = self::app()->groupsConfigPath;
}
if (is_file($this->groupsConfigFile)) {
@@ -142,6 +142,7 @@ class Minify_HTML_Helper
*
* @param array|string $sources
* @param int $lastModified
+ *
* @return int
*/
public static function getLastModified($sources, $lastModified = 0)
@@ -150,7 +151,7 @@ class Minify_HTML_Helper
$factory = self::app()->sourceFactory;
/** @var Minify_Source $source */
- foreach ((array)$sources as $source) {
+ foreach ((array) $sources as $source) {
$source = $factory->makeSource($source);
$max = max($max, $source->getLastModified());
}
@@ -160,7 +161,9 @@ class Minify_HTML_Helper
/**
* @param \Minify\App $app
+ *
* @return \Minify\App
+ *
* @internal
*/
public static function app(\Minify\App $app = null)
@@ -178,9 +181,11 @@ class Minify_HTML_Helper
return $cached;
}
- protected $_groupKey = null; // if present, URI will be like g=...
+ protected $_groupKey; // if present, URI will be like g=...
+
protected $_filePaths = array();
- protected $_lastModified = null;
+
+ protected $_lastModified;
/**
* In a given array of strings, find the character they all have at
@@ -188,6 +193,7 @@ class Minify_HTML_Helper
*
* @param array $arr array of strings
* @param int $pos index to check
+ *
* @return mixed a common char or '' if any do not match
*/
protected static function _getCommonCharAtPos($arr, $pos)
@@ -214,6 +220,7 @@ class Minify_HTML_Helper
*
* @param array $paths root-relative URIs of files
* @param string $minRoot root-relative URI of the "min" application
+ *
* @return string
*/
protected static function _getShortestUri($paths, $minRoot = '/min/')
@@ -224,9 +231,9 @@ class Minify_HTML_Helper
$c = self::_getCommonCharAtPos($paths, $pos);
if ($c === '') {
break;
- } else {
- $base .= $c;
}
+ $base .= $c;
+
++$pos;
}
$base = preg_replace('@[^/]+$@', '', $base);
diff --git a/lib/Minify/ImportProcessor.php b/lib/Minify/ImportProcessor.php
index 85d9ff5..1f3e0dc 100644
--- a/lib/Minify/ImportProcessor.php
+++ b/lib/Minify/ImportProcessor.php
@@ -1,7 +1,6 @@
- * @author Simon Schick
*/
class Minify_ImportProcessor
{
@@ -43,10 +38,10 @@ class Minify_ImportProcessor
private static $_isCss;
/**
- * @param String $currentDir
- * @param String $previewsDir Is only used internally
+ * @param string $currentDir
+ * @param string $previewsDir Is only used internally
*/
- private function __construct($currentDir, $previewsDir = "")
+ private function __construct($currentDir, $previewsDir = '')
{
$this->_currentDir = $currentDir;
$this->_previewsDir = $previewsDir;
@@ -56,9 +51,9 @@ class Minify_ImportProcessor
{
$file = preg_replace('~\\?.*~', '', $file);
$file = realpath($file);
- if (! $file
+ if (!$file
|| in_array($file, self::$filesIncluded)
- || false === ($content = @file_get_contents($file))) {
+ || ($content = @file_get_contents($file)) === false) {
// file missing, already included, or failed read
return '';
}
@@ -66,7 +61,7 @@ class Minify_ImportProcessor
$this->_currentDir = dirname($file);
// remove UTF-8 BOM if present
- if (pack("CCC",0xef,0xbb,0xbf) === substr($content, 0, 3)) {
+ if (pack('CCC', 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
$content = substr($content, 3);
}
// ensure uniform EOLs
@@ -104,9 +99,9 @@ class Minify_ImportProcessor
// protocol, leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
- : "/* Minify_ImportProcessor will not include remote content */";
+ : '/* Minify_ImportProcessor will not include remote content */';
}
- if ('/' === $url[0]) {
+ if ($url[0] === '/') {
// protocol-relative or root path
$url = ltrim($url, '/');
$file = realpath($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR
@@ -118,7 +113,7 @@ class Minify_ImportProcessor
}
$obj = new Minify_ImportProcessor(dirname($file), $this->_currentDir);
$content = $obj->_getContent($file, true);
- if ('' === $content) {
+ if ($content === '') {
// failed. leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
@@ -137,7 +132,7 @@ class Minify_ImportProcessor
$url = ($quote === '') ? $m[1] : substr($m[1], 1, strlen($m[1]) - 2);
- if ('/' !== $url[0]) {
+ if ($url[0] !== '/') {
if (strpos($url, '//') > 0) {
// probably starts with protocol, do not alter
} else {
@@ -156,6 +151,7 @@ class Minify_ImportProcessor
* @param string $from
* @param string $to
* @param string $ps
+ *
* @return string
*/
private function getPathDiff($from, $to, $ps = DIRECTORY_SEPARATOR)
@@ -170,19 +166,22 @@ class Minify_ImportProcessor
array_shift($arTo);
}
- return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
+ return str_pad('', count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
}
/**
* This function is to replace PHP's extremely buggy realpath().
- * @param string $path The original path, can be relative etc.
- * @return string The resolved path, it might not exist.
+ *
+ * @param string $path the original path, can be relative etc
+ *
+ * @return string the resolved path, it might not exist
+ *
* @see http://stackoverflow.com/questions/4049856/replace-phps-realpath
*/
private function truepath($path)
{
// whether $path is unix or not
- $unipath = ('' === $path) || ($path{0} !== '/');
+ $unipath = ($path === '') || ($path[0] !== '/');
// attempts to detect if path is relative in which case, add cwd
if (strpos($path, ':') === false && $unipath) {
@@ -194,10 +193,10 @@ class Minify_ImportProcessor
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
- if ('.' === $part) {
+ if ($part === '.') {
continue;
}
- if ('..' === $part) {
+ if ($part === '..') {
array_pop($absolutes);
} else {
$absolutes[] = $part;
@@ -210,8 +209,6 @@ class Minify_ImportProcessor
$path = readlink($path);
}
// put initial separator that could have been lost
- $path = !$unipath ? '/' . $path : $path;
-
- return $path;
+ return !$unipath ? '/' . $path : $path;
}
}
diff --git a/lib/Minify/JS/ClosureCompiler.php b/lib/Minify/JS/ClosureCompiler.php
index b842622..6059268 100644
--- a/lib/Minify/JS/ClosureCompiler.php
+++ b/lib/Minify/JS/ClosureCompiler.php
@@ -1,21 +1,17 @@
+ * @see http://code.google.com/closure/compiler/
*
* @todo can use a stream wrapper to unit test this?
*/
class Minify_JS_ClosureCompiler
{
-
/**
* @var string The option key for the maximum POST byte size
*/
@@ -42,27 +38,27 @@ class Minify_JS_ClosureCompiler
const DEFAULT_MAX_BYTES = 200000;
/**
- * @var string[] $DEFAULT_OPTIONS The default options to pass to the compiler service
+ * @var string[] The default options to pass to the compiler service
*
* @note This would be a constant if PHP allowed it
*/
private static $DEFAULT_OPTIONS = array(
- 'output_format' => 'text',
- 'compilation_level' => 'SIMPLE_OPTIMIZATIONS'
+ 'output_format' => 'text',
+ 'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
);
/**
- * @var string $url URL of compiler server. defaults to Google's
+ * @var string URL of compiler server. defaults to Google's
*/
protected $serviceUrl = 'https://closure-compiler.appspot.com/compile';
/**
- * @var int $maxBytes The maximum JS size that can be sent to the compiler server in bytes
+ * @var int The maximum JS size that can be sent to the compiler server in bytes
*/
protected $maxBytes = self::DEFAULT_MAX_BYTES;
/**
- * @var string[] $additionalOptions Additional options to pass to the compiler service
+ * @var string[] Additional options to pass to the compiler service
*/
protected $additionalOptions = array();
@@ -120,15 +116,17 @@ class Minify_JS_ClosureCompiler
* Call the service to perform the minification
*
* @param string $js JavaScript code
- * @return string
+ *
* @throws Minify_JS_ClosureCompiler_Exception
+ *
+ * @return string
*/
public function min($js)
{
$postBody = $this->buildPostBody($js);
if ($this->maxBytes > 0) {
- $bytes = (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
+ $bytes = (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2))
? mb_strlen($postBody, '8bit')
: strlen($postBody);
if ($bytes > $this->maxBytes) {
@@ -143,7 +141,7 @@ class Minify_JS_ClosureCompiler
if (preg_match('/^Error\(\d\d?\):/', $response)) {
if (is_callable($this->fallbackMinifier)) {
// use fallback
- $response = "/* Received errors from Closure Compiler API:\n$response"
+ $response = "/* Received errors from Closure Compiler API:\n${response}"
. "\n(Using fallback minifier)\n*/\n";
$response .= call_user_func($this->fallbackMinifier, $js);
} else {
@@ -153,6 +151,7 @@ class Minify_JS_ClosureCompiler
if ($response === '') {
$errors = $this->getResponse($this->buildPostBody($js, true));
+
throw new Minify_JS_ClosureCompiler_Exception($errors);
}
@@ -163,8 +162,10 @@ class Minify_JS_ClosureCompiler
* Get the response for a given POST body
*
* @param string $postBody
- * @return string
+ *
* @throws Minify_JS_ClosureCompiler_Exception
+ *
+ * @return string
*/
protected function getResponse($postBody)
{
@@ -173,15 +174,15 @@ class Minify_JS_ClosureCompiler
if ($allowUrlFopen) {
$contents = file_get_contents($this->serviceUrl, false, stream_context_create(array(
'http' => array(
- 'method' => 'POST',
+ 'method' => 'POST',
'compilation_level' => 'SIMPLE',
- 'output_format' => 'text',
- 'output_info' => 'compiled_code',
- 'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
- 'content' => $postBody,
- 'max_redirects' => 0,
- 'timeout' => 15,
- )
+ 'output_format' => 'text',
+ 'output_info' => 'compiled_code',
+ 'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
+ 'content' => $postBody,
+ 'max_redirects' => 0,
+ 'timeout' => 15,
+ ),
)));
} elseif (defined('CURLOPT_POST')) {
$ch = curl_init($this->serviceUrl);
@@ -195,13 +196,13 @@ class Minify_JS_ClosureCompiler
curl_close($ch);
} else {
throw new Minify_JS_ClosureCompiler_Exception(
- "Could not make HTTP request: allow_url_open is false and cURL not available"
+ 'Could not make HTTP request: allow_url_open is false and cURL not available'
);
}
- if (false === $contents) {
+ if ($contents === false) {
throw new Minify_JS_ClosureCompiler_Exception(
- "No HTTP response from server"
+ 'No HTTP response from server'
);
}
@@ -213,6 +214,7 @@ class Minify_JS_ClosureCompiler
*
* @param string $js JavaScript code
* @param bool $returnErrors
+ *
* @return string
*/
protected function buildPostBody($js, $returnErrors = false)
@@ -222,8 +224,8 @@ class Minify_JS_ClosureCompiler
self::$DEFAULT_OPTIONS,
$this->additionalOptions,
array(
- 'js_code' => $js,
- 'output_info' => ($returnErrors ? 'errors' : 'compiled_code')
+ 'js_code' => $js,
+ 'output_info' => ($returnErrors ? 'errors' : 'compiled_code'),
)
),
null,
diff --git a/lib/Minify/JS/JShrink.php b/lib/Minify/JS/JShrink.php
index 70507a3..753e8ca 100644
--- a/lib/Minify/JS/JShrink.php
+++ b/lib/Minify/JS/JShrink.php
@@ -1,19 +1,13 @@
- * @link https://github.com/tedious/JShrink
- *
+ * @see https://github.com/tedious/JShrink
*/
class JShrink
{
@@ -34,6 +28,7 @@ class JShrink
* @param array $options Various runtime options in an associative array
*
* @see JShrink\Minifier::minify()
+ *
* @return string
*/
public static function minify($js, array $options = array())
diff --git a/lib/Minify/LessCssSource.php b/lib/Minify/LessCssSource.php
index 8fa2e63..4321b60 100644
--- a/lib/Minify/LessCssSource.php
+++ b/lib/Minify/LessCssSource.php
@@ -15,7 +15,7 @@ class Minify_LessCssSource extends Minify_Source
private $parsed;
/**
- * @inheritdoc
+ * {@inheritdoc}
*/
public function __construct(array $spec, Minify_CacheInterface $cache)
{
@@ -85,7 +85,11 @@ class Minify_LessCssSource extends Minify_Source
/**
* Calculate maximum last modified of all files,
* as the 'updated' timestamp in cache is not the same as file last modified timestamp:
- * @link https://github.com/leafo/lessphp/blob/v0.4.0/lessc.inc.php#L1904
+ *
+ * @see https://github.com/leafo/lessphp/blob/v0.4.0/lessc.inc.php#L1904
+ *
+ * @param mixed $cache
+ *
* @return int
*/
private function getMaxLastModified($cache)
diff --git a/lib/Minify/Lines.php b/lib/Minify/Lines.php
index 2024708..7db21f5 100644
--- a/lib/Minify/Lines.php
+++ b/lib/Minify/Lines.php
@@ -1,19 +1,13 @@
- * @author Adam Pedersen (Issue 55 fix)
*/
class Minify_Lines
{
-
/**
* Add line numbers in C-style comments
*
@@ -22,7 +16,6 @@ class Minify_Lines
* mangled. URI rewriting can also be performed.
*
* @param string $content
- *
* @param array $options available options:
*
* 'id': (optional) string to identify file. E.g. file name/path
@@ -48,8 +41,8 @@ class Minify_Lines
$i = 0;
$newLines = array();
- while (null !== ($line = array_shift($lines))) {
- if (('' !== $id) && (0 === $i % 50)) {
+ while (($line = array_shift($lines)) !== null) {
+ if (($id !== '') && ($i % 50 === 0)) {
if ($inComment) {
array_push($newLines, '', "/* {$id} *|", '');
} else {
@@ -84,7 +77,6 @@ class Minify_Lines
* Is the parser within a C-style comment at the end of this line?
*
* @param string $line current line of code
- *
* @param bool $inComment was the parser in a C-style comment at the
* beginning of the previous line?
*
@@ -102,7 +94,8 @@ class Minify_Lines
// stop comment and keep walking line
$inComment = false;
- @$line = (string)substr($line, $index + 2);
+ @$line = (string) substr($line, $index + 2);
+
continue;
}
@@ -116,7 +109,8 @@ class Minify_Lines
if ($single === false || $multi < $single) {
// start comment and keep walking line
$inComment = true;
- @$line = (string)substr($line, $multi + 2);
+ @$line = (string) substr($line, $multi + 2);
+
continue;
}
@@ -131,12 +125,9 @@ class Minify_Lines
* Prepend a comment (or note) to the given line
*
* @param string $line current line of code
- *
* @param string $note content of note/comment
- *
* @param bool $inComment was the parser in a comment at the
* beginning of the line?
- *
* @param int $padTo minimum width of comment
*
* @return string
@@ -157,6 +148,7 @@ class Minify_Lines
*
* @param string $str String containing the token
* @param string $token Token being checked
+ *
* @return bool
*/
private static function _find($str, $token)
@@ -164,24 +156,26 @@ class Minify_Lines
switch ($token) {
case '//':
$fakes = array(
- '://' => 1,
- '"//' => 1,
- '\'//' => 1,
- '".//' => 2,
+ '://' => 1,
+ '"//' => 1,
+ '\'//' => 1,
+ '".//' => 2,
'\'.//' => 2,
);
+
break;
case '/*':
$fakes = array(
- '"/*' => 1,
- '\'/*' => 1,
- '"//*' => 2,
- '\'//*' => 2,
- '".//*' => 3,
+ '"/*' => 1,
+ '\'/*' => 1,
+ '"//*' => 2,
+ '\'//*' => 2,
+ '".//*' => 3,
'\'.//*' => 3,
- '*/*' => 1,
- '\\/*' => 1,
+ '*/*' => 1,
+ '\\/*' => 1,
);
+
break;
default:
$fakes = array();
@@ -197,6 +191,7 @@ class Minify_Lines
// move offset and scan again
$offset += $index + strlen($token);
$index = strpos($str, $token, $offset);
+
break;
}
}
diff --git a/lib/Minify/Logger/LegacyHandler.php b/lib/Minify/Logger/LegacyHandler.php
index 273413c..89b2346 100644
--- a/lib/Minify/Logger/LegacyHandler.php
+++ b/lib/Minify/Logger/LegacyHandler.php
@@ -19,6 +19,6 @@ class LegacyHandler extends AbstractProcessingHandler
protected function write(array $record)
{
- $this->obj->log((string)$record['formatted']);
+ $this->obj->log((string) $record['formatted']);
}
}
diff --git a/lib/Minify/NailgunClosureCompiler.php b/lib/Minify/NailgunClosureCompiler.php
index bdc49da..62daf19 100644
--- a/lib/Minify/NailgunClosureCompiler.php
+++ b/lib/Minify/NailgunClosureCompiler.php
@@ -2,19 +2,17 @@
/**
* Class Minify_ClosureCompiler
- * @package Minify
*/
/**
* Run Closure Compiler via NailGun
*
- * @package Minify
- * @author Elan Ruusamäe
- * @link https://github.com/martylamb/nailgun
+ * @see https://github.com/martylamb/nailgun
*/
class Minify_NailgunClosureCompiler extends Minify_ClosureCompiler
{
const NG_SERVER = 'com.martiansoftware.nailgun.NGServer';
+
const CC_MAIN = 'com.google.javascript.jscomp.CommandLineRunner';
/**
@@ -26,6 +24,7 @@ class Minify_NailgunClosureCompiler extends Minify_ClosureCompiler
* It also sometimes breaks on 229 on the devbox.
* To complete this whole madness and made future
* 'fixes' easier I added this nice little array...
+ *
* @var array
*/
private static $NG_EXIT_CODES = array(0, 227, 229);
@@ -60,35 +59,34 @@ class Minify_NailgunClosureCompiler extends Minify_ClosureCompiler
);
// The command for the server that should show up in the process list
- $server = array(
+ return array(
self::$javaExecutable,
'-server',
'-cp', implode(':', $classPath),
self::NG_SERVER,
);
-
- return $server;
}
/**
- * @return array
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return array
*/
protected function getCompilerCommandLine()
{
- $server = array(
+ return array(
self::$ngExecutable,
- escapeshellarg(self::CC_MAIN)
+ escapeshellarg(self::CC_MAIN),
);
-
- return $server;
}
/**
* @param string $tmpFile
* @param array $options
- * @return string
+ *
* @throws Minify_ClosureCompiler_Exception
+ *
+ * @return string
*/
protected function compile($tmpFile, $options)
{
@@ -102,12 +100,12 @@ class Minify_NailgunClosureCompiler extends Minify_ClosureCompiler
private function startServer()
{
$serverCommand = implode(' ', $this->getServerCommandLine());
- $psCommand = $this->shell("ps -o cmd= -C " . self::$javaExecutable);
+ $psCommand = $this->shell('ps -o cmd= -C ' . self::$javaExecutable);
if (in_array($serverCommand, $psCommand, true)) {
// already started!
return;
}
- $this->shell("$serverCommand /dev/null 2>/dev/null & sleep 10");
+ $this->shell("${serverCommand} /dev/null 2>/dev/null & sleep 10");
}
-}
\ No newline at end of file
+}
diff --git a/lib/Minify/Packer.php b/lib/Minify/Packer.php
index 7ddca79..6a72735 100644
--- a/lib/Minify/Packer.php
+++ b/lib/Minify/Packer.php
@@ -5,19 +5,16 @@
* To use this class you must first download the PHP port of Packer
* and place the file "class.JavaScriptPacker.php" in /lib (or your
* include_path).
- * @link http://joliclic.free.fr/php/javascript-packer/en/
+ *
+ * @see http://joliclic.free.fr/php/javascript-packer/en/
*
* Be aware that, as long as HTTP encoding is used, scripts minified with JSMin
* will provide better client-side performance, as they need not be unpacked in
* client-side code.
- *
- * @package Minify
*/
/**
* Minify Javascript using Dean Edward's Packer
- *
- * @package Minify
*/
class Minify_Packer
{
diff --git a/lib/Minify/ScssCssSource.php b/lib/Minify/ScssCssSource.php
index 9aa58f0..48961e6 100644
--- a/lib/Minify/ScssCssSource.php
+++ b/lib/Minify/ScssCssSource.php
@@ -6,7 +6,7 @@ use Leafo\ScssPhp\Version;
/**
* Class for using SCSS files
*
- * @link https://github.com/leafo/scssphp/
+ * @see https://github.com/leafo/scssphp/
*/
class Minify_ScssCssSource extends Minify_Source
{
@@ -23,7 +23,7 @@ class Minify_ScssCssSource extends Minify_Source
private $parsed;
/**
- * @inheritdoc
+ * {@inheritdoc}
*/
public function __construct(array $spec, Minify_CacheInterface $cache)
{
@@ -114,7 +114,7 @@ class Minify_ScssCssSource extends Minify_Source
*
* @param array $cache Cache object
*
- * @return boolean True if compile required.
+ * @return bool true if compile required
*/
private function cacheIsStale($cache)
{
@@ -140,6 +140,7 @@ class Minify_ScssCssSource extends Minify_Source
* @param string $filename Input path (.scss)
*
* @see Server::compile()
+ *
* @return array meta data result of the compile
*/
private function compile($filename)
@@ -157,7 +158,7 @@ class Minify_ScssCssSource extends Minify_Source
$v = Version::VERSION;
$ts = date('r', $start);
- $css = "/* compiled by scssphp $v on $ts (${elapsed}s) */\n\n" . $css;
+ $css = "/* compiled by scssphp ${v} on ${ts} (${elapsed}s) */\n\n" . $css;
$imports = $scss->getParsedFiles();
@@ -170,7 +171,7 @@ class Minify_ScssCssSource extends Minify_Source
'elapsed' => $elapsed, // statistic, can be dropped
'updated' => $updated,
'content' => $css,
- 'files' => $imports,
+ 'files' => $imports,
);
}
}
diff --git a/lib/Minify/ServeConfiguration.php b/lib/Minify/ServeConfiguration.php
index 12d9d2f..57dc197 100644
--- a/lib/Minify/ServeConfiguration.php
+++ b/lib/Minify/ServeConfiguration.php
@@ -1,17 +1,13 @@
*/
class Minify_Source implements Minify_SourceInterface
{
-
/**
* @var int time of last modification
*/
protected $lastModified;
/**
- * @var callback minifier function specifically for this source.
+ * @var callback minifier function specifically for this source
*/
protected $minifier;
/**
- * @var array minification options specific to this source.
+ * @var array minification options specific to this source
*/
protected $minifyOptions = array();
@@ -72,13 +67,16 @@ class Minify_Source implements Minify_SourceInterface
$ext = pathinfo($spec['filepath'], PATHINFO_EXTENSION);
switch ($ext) {
case 'js': $this->contentType = Minify::TYPE_JS;
+
break;
case 'less': // fallthrough
case 'scss': // fallthrough
case 'css': $this->contentType = Minify::TYPE_CSS;
+
break;
case 'htm': // fallthrough
case 'html': $this->contentType = Minify::TYPE_HTML;
+
break;
}
$this->filepath = $spec['filepath'];
@@ -171,8 +169,8 @@ class Minify_Source implements Minify_SourceInterface
*/
public function getContent()
{
- if (null === $this->filepath) {
- if (null === $this->content) {
+ if ($this->filepath === null) {
+ if ($this->content === null) {
$content = call_user_func($this->getContentFunc, $this->id);
} else {
$content = $this->content;
diff --git a/lib/Minify/Source/Factory.php b/lib/Minify/Source/Factory.php
index f36d1b2..127340b 100644
--- a/lib/Minify/Source/Factory.php
+++ b/lib/Minify/Source/Factory.php
@@ -2,7 +2,6 @@
class Minify_Source_Factory
{
-
/**
* @var array
*/
@@ -40,32 +39,30 @@ class Minify_Source_Factory
* file, use the touch command to update the mtime on the server. If the mtime
* jumps ahead by a number of hours, set this variable to that number. If the mtime
* moves back, this should not be needed.
- *
* @param Minify_CacheInterface $cache Optional cache for handling .less files.
- *
*/
public function __construct(Minify_Env $env, array $options = array(), Minify_CacheInterface $cache = null)
{
$this->env = $env;
$this->options = array_merge(array(
- 'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
- 'fileChecker' => array($this, 'checkIsFile'),
- 'resolveDocRoot' => true,
- 'checkAllowDirs' => true,
- 'allowDirs' => array('//'),
+ 'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
+ 'fileChecker' => array($this, 'checkIsFile'),
+ 'resolveDocRoot' => true,
+ 'checkAllowDirs' => true,
+ 'allowDirs' => array('//'),
'uploaderHoursBehind' => 0,
), $options);
// resolve // in allowDirs
$docRoot = $env->getDocRoot();
foreach ($this->options['allowDirs'] as $i => $dir) {
- if (0 === strpos($dir, '//')) {
+ if (strpos($dir, '//') === 0) {
$this->options['allowDirs'][$i] = $docRoot . substr($dir, 1);
}
}
if ($this->options['fileChecker'] && !is_callable($this->options['fileChecker'])) {
- throw new InvalidArgumentException("fileChecker option is not callable");
+ throw new InvalidArgumentException('fileChecker option is not callable');
}
$this->setHandler('~\.less$~i', function ($spec) use ($cache) {
@@ -92,24 +89,25 @@ class Minify_Source_Factory
/**
* @param string $file
- * @return string
*
* @throws Minify_Source_FactoryException
+ *
+ * @return string
*/
public function checkIsFile($file)
{
$realpath = realpath($file);
if (!$realpath) {
- throw new Minify_Source_FactoryException("File failed realpath(): $file");
+ throw new Minify_Source_FactoryException("File failed realpath(): ${file}");
}
$basename = basename($file);
- if (0 === strpos($basename, '.')) {
- throw new Minify_Source_FactoryException("Filename starts with period (may be hidden): $basename");
+ if (strpos($basename, '.') === 0) {
+ throw new Minify_Source_FactoryException("Filename starts with period (may be hidden): ${basename}");
}
if (!is_file($realpath) || !is_readable($realpath)) {
- throw new Minify_Source_FactoryException("Not a file or isn't readable: $file");
+ throw new Minify_Source_FactoryException("Not a file or isn't readable: ${file}");
}
return $realpath;
@@ -118,9 +116,9 @@ class Minify_Source_Factory
/**
* @param mixed $spec
*
- * @return Minify_SourceInterface
- *
* @throws Minify_Source_FactoryException
+ *
+ * @return Minify_SourceInterface
*/
public function makeSource($spec)
{
@@ -139,7 +137,7 @@ class Minify_Source_Factory
return new Minify_Source($spec);
}
- if ($this->options['resolveDocRoot'] && 0 === strpos($spec['filepath'], '//')) {
+ if ($this->options['resolveDocRoot'] && strpos($spec['filepath'], '//') === 0) {
$spec['filepath'] = $this->env->getDocRoot() . substr($spec['filepath'], 1);
}
@@ -148,7 +146,7 @@ class Minify_Source_Factory
}
if ($this->options['checkAllowDirs']) {
- $allowDirs = (array)$this->options['allowDirs'];
+ $allowDirs = (array) $this->options['allowDirs'];
$inAllowedDir = false;
$filePath = $this->env->normalizePath($spec['filepath']);
foreach ($allowDirs as $allowDir) {
@@ -159,9 +157,10 @@ class Minify_Source_Factory
if (!$inAllowedDir) {
$allowDirsStr = implode(';', $allowDirs);
+
throw new Minify_Source_FactoryException("File '{$spec['filepath']}' is outside \$allowDirs "
- . "($allowDirsStr). If the path is resolved via an alias/symlink, look into the "
- . "\$min_symlinks option.");
+ . "(${allowDirsStr}). If the path is resolved via an alias/symlink, look into the "
+ . '$min_symlinks option.');
}
}
@@ -170,7 +169,7 @@ class Minify_Source_Factory
if ($this->options['noMinPattern'] && preg_match($this->options['noMinPattern'], $basename)) {
if (preg_match('~\.(css|less)$~i', $basename)) {
$spec['minifyOptions']['compress'] = false;
- // we still want URI rewriting to work for CSS
+ // we still want URI rewriting to work for CSS
} else {
$spec['minifier'] = 'Minify::nullMinifier';
}
@@ -184,12 +183,13 @@ class Minify_Source_Factory
foreach ($this->handlers as $basenamePattern => $handler) {
if (preg_match($basenamePattern, $basename)) {
$source = call_user_func($handler, $spec);
+
break;
}
}
if (!$source) {
- throw new Minify_Source_FactoryException("Handler not found for file: $basename");
+ throw new Minify_Source_FactoryException("Handler not found for file: ${basename}");
}
return $source;
diff --git a/lib/Minify/SourceInterface.php b/lib/Minify/SourceInterface.php
index 26afc5f..af1261f 100644
--- a/lib/Minify/SourceInterface.php
+++ b/lib/Minify/SourceInterface.php
@@ -1,7 +1,6 @@
getId(), $source->getMinifier(), $source->getMinifierOptions()
+ $source->getId(), $source->getMinifier(), $source->getMinifierOptions(),
);
}
diff --git a/lib/Minify/YUICompressor.php b/lib/Minify/YUICompressor.php
index a45f572..a6fdea2 100644
--- a/lib/Minify/YUICompressor.php
+++ b/lib/Minify/YUICompressor.php
@@ -1,7 +1,6 @@
'2048k')
*
* @todo unit tests, $options docs
- *
- * @package Minify
- * @author Stephen Clay
*/
class Minify_YUICompressor
{
-
/**
* Filepath of the YUI Compressor jar file. This must be set before
* calling minifyJs() or minifyCss().
@@ -59,7 +54,6 @@ class Minify_YUICompressor
* Minify a Javascript string
*
* @param string $js
- *
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
@@ -75,7 +69,6 @@ class Minify_YUICompressor
* Minify a CSS string
*
* @param string $css
- *
* @param array $options (verbose is ignored)
*
* @see http://www.julienlecomte.net/yuicompressor/README
@@ -90,8 +83,8 @@ class Minify_YUICompressor
private static function _minify($type, $content, $options)
{
self::_prepare();
- if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
- throw new Exception('Minify_YUICompressor : could not create temp file in "'.self::$tempDir.'".');
+ if (!($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
+ throw new Exception('Minify_YUICompressor : could not create temp file in "' . self::$tempDir . '".');
}
file_put_contents($tmpFile, $content);
@@ -107,13 +100,13 @@ class Minify_YUICompressor
private static function _getCmd($userOptions, $type, $tmpFile)
{
$defaults = array(
- 'charset' => '',
- 'line-break' => 5000,
- 'type' => $type,
- 'nomunge' => false,
- 'preserve-semi' => false,
+ 'charset' => '',
+ 'line-break' => 5000,
+ 'type' => $type,
+ 'nomunge' => false,
+ 'preserve-semi' => false,
'disable-optimizations' => false,
- 'stack-size' => '',
+ 'stack-size' => '',
);
$o = array_merge($defaults, $userOptions);
@@ -125,7 +118,7 @@ class Minify_YUICompressor
? " --charset {$o['charset']}"
: '')
. (is_numeric($o['line-break']) && $o['line-break'] >= 0
- ? ' --line-break ' . (int)$o['line-break']
+ ? ' --line-break ' . (int) $o['line-break']
: '');
if ($type === 'js') {
foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) {
@@ -140,18 +133,17 @@ class Minify_YUICompressor
private static function _prepare()
{
- if (! is_file(self::$jarFile)) {
- throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not a valid file.');
+ if (!is_file(self::$jarFile)) {
+ throw new Exception('Minify_YUICompressor : $jarFile(' . self::$jarFile . ') is not a valid file.');
}
- if (! is_readable(self::$jarFile)) {
- throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not readable.');
+ if (!is_readable(self::$jarFile)) {
+ throw new Exception('Minify_YUICompressor : $jarFile(' . self::$jarFile . ') is not readable.');
}
- if (! is_dir(self::$tempDir)) {
- throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not a valid direcotry.');
+ if (!is_dir(self::$tempDir)) {
+ throw new Exception('Minify_YUICompressor : $tempDir(' . self::$tempDir . ') is not a valid direcotry.');
}
- if (! is_writable(self::$tempDir)) {
- throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not writable.');
+ if (!is_writable(self::$tempDir)) {
+ throw new Exception('Minify_YUICompressor : $tempDir(' . self::$tempDir . ') is not writable.');
}
}
}
-
diff --git a/lib/MrClay/Cli.php b/lib/MrClay/Cli.php
index e9ef3b3..a0652f2 100644
--- a/lib/MrClay/Cli.php
+++ b/lib/MrClay/Cli.php
@@ -2,8 +2,8 @@
namespace MrClay;
-use MrClay\Cli\Arg;
use InvalidArgumentException;
+use MrClay\Cli\Arg;
/**
* Forms a front controller for a console app, handling and validating arguments (options)
@@ -15,12 +15,10 @@ use InvalidArgumentException;
* solely through the file pointers provided by openInput()/openOutput(), you can make your
* app more flexible to end users.
*
- * @author Steve Clay
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Cli
{
-
/**
* @var array validation errors
*/
@@ -62,19 +60,19 @@ class Cli
/**
* @var resource
*/
- protected $_stdin = null;
+ protected $_stdin;
/**
* @var resource
*/
- protected $_stdout = null;
+ protected $_stdout;
/**
* @param bool $exitIfNoStdin (default true) Exit() if STDIN is not defined
*/
public function __construct($exitIfNoStdin = true)
{
- if ($exitIfNoStdin && ! defined('STDIN')) {
+ if ($exitIfNoStdin && !defined('STDIN')) {
exit('This script is for command-line use only.');
}
if (isset($GLOBALS['argv'][1])
@@ -85,6 +83,7 @@ class Cli
/**
* @param Arg|string $letter
+ *
* @return Arg
*/
public function addOptionalArg($letter)
@@ -94,6 +93,7 @@ class Cli
/**
* @param Arg|string $letter
+ *
* @return Arg
*/
public function addRequiredArg($letter)
@@ -105,15 +105,17 @@ class Cli
* @param string $letter
* @param bool $required
* @param Arg|null $arg
- * @return Arg
+ *
* @throws InvalidArgumentException
+ *
+ * @return Arg
*/
public function addArgument($letter, $required, Arg $arg = null)
{
- if (! preg_match('/^[a-zA-Z]$/', $letter)) {
+ if (!preg_match('/^[a-zA-Z]$/', $letter)) {
throw new InvalidArgumentException('$letter must be in [a-zA-Z]');
}
- if (! $arg) {
+ if (!$arg) {
$arg = new Arg($required);
}
$this->_args[$letter] = $arg;
@@ -123,6 +125,7 @@ class Cli
/**
* @param string $letter
+ *
* @return Arg|null
*/
public function getArgument($letter)
@@ -170,35 +173,36 @@ class Cli
if (is_bool($o[$letter])) {
// remove from argv copy
- $k = array_search("-$letter", $argvCopy);
+ $k = array_search("-${letter}", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 1);
}
if ($arg->mustHaveValue) {
- $this->addError($letter, "Missing value");
+ $this->addError($letter, 'Missing value');
} else {
$this->values[$letter] = true;
}
} else {
// string
$this->values[$letter] = $o[$letter];
- $v =& $this->values[$letter];
+ $v = &$this->values[$letter];
// remove from argv copy
// first look for -ovalue or -o=value
- $pattern = "/^-{$letter}=?" . preg_quote($v, '/') . "$/";
+ $pattern = "/^-{$letter}=?" . preg_quote($v, '/') . '$/';
$foundInArgv = false;
foreach ($argvCopy as $k => $argV) {
if (preg_match($pattern, $argV)) {
array_splice($argvCopy, $k, 1);
$foundInArgv = true;
+
break;
}
}
- if (! $foundInArgv) {
+ if (!$foundInArgv) {
// space separated
- $k = array_search("-$letter", $argvCopy);
+ $k = array_search("-${letter}", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 2);
}
@@ -206,17 +210,17 @@ class Cli
// check that value isn't really another option
if (strlen($lettersUsed) > 1) {
- $pattern = "/^-[" . str_replace($letter, '', $lettersUsed) . "]/i";
+ $pattern = '/^-[' . str_replace($letter, '', $lettersUsed) . ']/i';
if (preg_match($pattern, $v)) {
- $this->addError($letter, "Value was read as another option: %s", $v);
+ $this->addError($letter, 'Value was read as another option: %s', $v);
return false;
}
}
if ($arg->assertFile || $arg->assertDir) {
if ($v[0] !== '/' && $v[0] !== '~') {
- $this->values["$letter.raw"] = $v;
- $v = getcwd() . "/$v";
+ $this->values["${letter}.raw"] = $v;
+ $v = getcwd() . "/${v}";
}
}
if ($arg->assertFile) {
@@ -225,28 +229,29 @@ class Cli
} elseif ($arg->useAsOutfile) {
$this->_stdout = $v;
}
- if ($arg->assertReadable && ! is_readable($v)) {
- $this->addError($letter, "File not readable: %s", $v);
+ if ($arg->assertReadable && !is_readable($v)) {
+ $this->addError($letter, 'File not readable: %s', $v);
+
continue;
}
if ($arg->assertWritable) {
if (is_file($v)) {
- if (! is_writable($v)) {
- $this->addError($letter, "File not writable: %s", $v);
+ if (!is_writable($v)) {
+ $this->addError($letter, 'File not writable: %s', $v);
}
} else {
- if (! is_writable(dirname($v))) {
- $this->addError($letter, "Directory not writable: %s", dirname($v));
+ if (!is_writable(dirname($v))) {
+ $this->addError($letter, 'Directory not writable: %s', dirname($v));
}
}
}
- } elseif ($arg->assertDir && $arg->assertWritable && ! is_writable($v)) {
- $this->addError($letter, "Directory not readable: %s", $v);
+ } elseif ($arg->assertDir && $arg->assertWritable && !is_writable($v)) {
+ $this->addError($letter, 'Directory not readable: %s', $v);
}
}
} else {
if ($arg->isRequired()) {
- $this->addError($letter, "Missing");
+ $this->addError($letter, 'Missing');
}
}
}
@@ -266,7 +271,7 @@ class Cli
$r = $this->moreArgs;
foreach ($r as $k => $v) {
if ($v[0] !== '/' && $v[0] !== '~') {
- $v = getcwd() . "/$v";
+ $v = getcwd() . "/${v}";
$v = str_replace('/./', '/', $v);
do {
$v = preg_replace('@/[^/]+/\\.\\./@', '/', $v, 1, $changed);
@@ -290,7 +295,7 @@ class Cli
}
$r = "Some arguments did not pass validation:\n";
foreach ($this->errors as $letter => $arr) {
- $r .= " $letter : " . implode(', ', $arr) . "\n";
+ $r .= " ${letter} : " . implode(', ', $arr) . "\n";
}
$r .= "\n";
@@ -306,11 +311,11 @@ class Cli
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$desc = $arg->getDescription();
- $flag = " -$letter ";
+ $flag = " -${letter} ";
if ($arg->mayHaveValue) {
- $flag .= "[VAL]";
+ $flag .= '[VAL]';
} elseif ($arg->mustHaveValue) {
- $flag .= "VAL";
+ $flag .= 'VAL';
}
if ($arg->assertFile) {
$flag = str_replace('VAL', 'FILE', $flag);
@@ -318,9 +323,9 @@ class Cli
$flag = str_replace('VAL', 'DIR', $flag);
}
if ($arg->isRequired()) {
- $desc = "(required) $desc";
+ $desc = "(required) ${desc}";
}
- $flag = str_pad($flag, 12, " ", STR_PAD_RIGHT);
+ $flag = str_pad($flag, 12, ' ', STR_PAD_RIGHT);
$desc = wordwrap($desc, 70);
$r .= $flag . str_replace("\n", "\n ", $desc) . "\n\n";
}
@@ -336,18 +341,17 @@ class Cli
*/
public function openInput()
{
- if (null === $this->_stdin) {
+ if ($this->_stdin === null) {
return STDIN;
- } else {
- $this->_stdin = fopen($this->_stdin, 'rb');
-
- return $this->_stdin;
}
+ $this->_stdin = fopen($this->_stdin, 'rb');
+
+ return $this->_stdin;
}
public function closeInput()
{
- if (null !== $this->_stdin) {
+ if ($this->_stdin !== null) {
fclose($this->_stdin);
}
}
@@ -361,18 +365,17 @@ class Cli
*/
public function openOutput()
{
- if (null === $this->_stdout) {
+ if ($this->_stdout === null) {
return STDOUT;
- } else {
- $this->_stdout = fopen($this->_stdout, 'wb');
-
- return $this->_stdout;
}
+ $this->_stdout = fopen($this->_stdout, 'wb');
+
+ return $this->_stdout;
}
public function closeOutput()
{
- if (null !== $this->_stdout) {
+ if ($this->_stdout !== null) {
fclose($this->_stdout);
}
}
@@ -390,4 +393,3 @@ class Cli
$this->errors[$letter][] = sprintf($msg, $value);
}
}
-
diff --git a/lib/MrClay/Cli/Arg.php b/lib/MrClay/Cli/Arg.php
index b7a46e9..323160b 100644
--- a/lib/MrClay/Cli/Arg.php
+++ b/lib/MrClay/Cli/Arg.php
@@ -31,16 +31,15 @@ use BadMethodCallException;
* @method \MrClay\Cli\Arg assertReadable() Assert that the specified file/dir must be readable
* @method \MrClay\Cli\Arg assertWritable() Assert that the specified file/dir must be writable
*
- * @property-read bool mayHaveValue
- * @property-read bool mustHaveValue
- * @property-read bool assertFile
- * @property-read bool assertDir
- * @property-read bool assertReadable
- * @property-read bool assertWritable
- * @property-read bool useAsInfile
- * @property-read bool useAsOutfile
+ * @property bool mayHaveValue
+ * @property bool mustHaveValue
+ * @property bool assertFile
+ * @property bool assertDir
+ * @property bool assertReadable
+ * @property bool assertWritable
+ * @property bool useAsInfile
+ * @property bool useAsOutfile
*
- * @author Steve Clay
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Arg
@@ -51,14 +50,14 @@ class Arg
public function getDefaultSpec()
{
return array(
- 'mayHaveValue' => false,
- 'mustHaveValue' => false,
- 'assertFile' => false,
- 'assertDir' => false,
+ 'mayHaveValue' => false,
+ 'mustHaveValue' => false,
+ 'assertFile' => false,
+ 'assertDir' => false,
'assertReadable' => false,
'assertWritable' => false,
- 'useAsInfile' => false,
- 'useAsOutfile' => false,
+ 'useAsInfile' => false,
+ 'useAsOutfile' => false,
);
}
@@ -93,6 +92,7 @@ class Arg
* Assert that the argument's value points to a writable file. When
* Cli::openOutput() is called, a write pointer to this file will
* be provided.
+ *
* @return Arg
*/
public function useAsOutfile()
@@ -106,6 +106,7 @@ class Arg
* Assert that the argument's value points to a readable file. When
* Cli::openInput() is called, a read pointer to this file will
* be provided.
+ *
* @return Arg
*/
public function useAsInfile()
@@ -125,6 +126,7 @@ class Arg
/**
* @param string $desc
+ *
* @return Arg
*/
public function setDescription($desc)
@@ -155,8 +157,10 @@ class Arg
*
* @param string $name
* @param array $args
- * @return Arg
+ *
* @throws BadMethodCallException
+ *
+ * @return Arg
*/
public function __call($name, array $args = array())
{
@@ -176,6 +180,7 @@ class Arg
* Note: magic properties declared in class PHPDOC
*
* @param string $name
+ *
* @return bool|null
*/
public function __get($name)
diff --git a/min_extras/cli/minify.php b/min_extras/cli/minify.php
index 407685b..ea4378f 100755
--- a/min_extras/cli/minify.php
+++ b/min_extras/cli/minify.php
@@ -5,7 +5,7 @@ die('Must be rewritten for new API');
require __DIR__ . '/../../bootstrap.php';
-$cli = new MrClay\Cli;
+$cli = new MrClay\Cli();
$cli->addOptionalArg('d')->assertDir()->setDescription('Your webserver\'s DOCUMENT_ROOT: Relative paths will be rewritten relative to this path. This is required if you\'re passing in CSS.');
@@ -13,7 +13,7 @@ $cli->addOptionalArg('o')->useAsOutfile()->setDescription('Outfile: If given, ou
$cli->addOptionalArg('t')->mustHaveValue()->setDescription('Type: must be "css", "js", or "html". This must be provided if passing content via STDIN.');
-if (! $cli->validate()) {
+if (!$cli->validate()) {
if ($cli->isHelpRequest) {
echo "The Minify CLI tool!\n\n";
}
@@ -34,7 +34,7 @@ $docRoot = $cli->values['d'];
$type = $cli->values['t'];
if (is_string($type)) {
- if (! in_array($type, array('js', 'css', 'html'))) {
+ if (!in_array($type, array('js', 'css', 'html'))) {
echo "Type argument invalid\n";
exit(1);
}
@@ -48,27 +48,27 @@ if ($paths) {
foreach ($paths as $path) {
if (is_file($path)) {
$sources[] = new Minify_Source(array(
- 'filepath' => $path,
+ 'filepath' => $path,
'minifyOptions' => array('docRoot' => $docRoot),
));
} else {
$sources[] = new Minify_Source(array(
- 'id' => $path,
- 'content' => "/*** $path not found ***/\n",
+ 'id' => $path,
+ 'content' => "/*** ${path} not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}
}
} else {
// not paths input, expect STDIN
- if (! $type) {
+ if (!$type) {
echo "Type must be specified to use STDIN\n";
exit(1);
}
$in = $cli->openInput();
$sources[] = new Minify_Source(array(
- 'id' => 'one',
- 'content' => stream_get_contents($in),
+ 'id' => 'one',
+ 'content' => stream_get_contents($in),
'contentType' => $type,
));
$cli->closeInput();
diff --git a/min_extras/cli/rewrite-uris.php b/min_extras/cli/rewrite-uris.php
index 0ca560f..25669f4 100755
--- a/min_extras/cli/rewrite-uris.php
+++ b/min_extras/cli/rewrite-uris.php
@@ -5,7 +5,7 @@ die('Must be rewritten for new API');
require __DIR__ . '/../../bootstrap.php';
-$cli = new MrClay\Cli;
+$cli = new MrClay\Cli();
$cli->addRequiredArg('d')->assertDir()->setDescription('Your webserver\'s DOCUMENT_ROOT: Relative paths will be rewritten relative to this path.');
@@ -13,7 +13,7 @@ $cli->addOptionalArg('o')->useAsOutfile()->setDescription('Outfile: If given, ou
$cli->addOptionalArg('t')->setDescription('Test run: Return output followed by rewriting algorithm.');
-if (! $cli->validate()) {
+if (!$cli->validate()) {
echo "USAGE: ./rewrite-uris.php [-t] -d DOC_ROOT [-o OUTFILE] file ...\n";
if ($cli->isHelpRequest) {
echo $cli->getArgumentsListing();
@@ -27,7 +27,7 @@ $outfile = $cli->values['o'];
$testRun = $cli->values['t'];
$docRoot = $cli->values['d'];
-$pathRewriter = function($css, $options) {
+$pathRewriter = function ($css, $options) {
return Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $options['docRoot']);
};
@@ -37,14 +37,14 @@ $sources = array();
foreach ($paths as $path) {
if (is_file($path)) {
$sources[] = new Minify_Source(array(
- 'filepath' => $path,
- 'minifier' => $pathRewriter,
+ 'filepath' => $path,
+ 'minifier' => $pathRewriter,
'minifyOptions' => array('docRoot' => $docRoot),
));
} else {
$sources[] = new Minify_Source(array(
- 'id' => $path,
- 'content' => "/*** $path not found ***/\n",
+ 'id' => $path,
+ 'content' => "/*** ${path} not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}
@@ -54,9 +54,8 @@ $combined = Minify::combine($sources) . "\n";
if ($testRun) {
echo $combined;
echo Minify_CSS_UriRewriter::$debugText . "\n";
-} else {
+} else {
$fp = $cli->openOutput();
fwrite($fp, $combined);
$cli->closeOutput();
}
-
diff --git a/min_extras/config.php b/min_extras/config.php
index cb33edd..c7143b6 100644
--- a/min_extras/config.php
+++ b/min_extras/config.php
@@ -4,6 +4,6 @@
require __DIR__ . '/../config.php';
-$minifyCachePath = isset($min_cachePath)
- ? $min_cachePath
+$minifyCachePath = isset($min_cachePath)
+ ? $min_cachePath
: '';
diff --git a/min_extras/tools/minifyTextarea.php b/min_extras/tools/minifyTextarea.php
index a5b5926..fc30246 100644
--- a/min_extras/tools/minifyTextarea.php
+++ b/min_extras/tools/minifyTextarea.php
@@ -13,7 +13,8 @@ $app->cache = new Minify_Cache_Null();
$env = $app->env;
-function h($txt) {
+function h($txt)
+{
return htmlspecialchars($txt, ENT_QUOTES, 'UTF-8');
}
@@ -22,16 +23,15 @@ if ($env->post('textIn')) {
}
if ($env->post('method') === 'Minify and serve') {
-
$base = trim($env->post('base'));
if ($base) {
$textIn = preg_replace(
- '@(]*>)@i'
- ,'$1'
- ,$textIn
+ '@(]*>)@i',
+ '$1',
+ $textIn
);
}
-
+
$sourceSpec['content'] = $textIn;
$sourceSpec['id'] = 'foo';
if (isset($_POST['minJs'])) {
@@ -43,9 +43,10 @@ if ($env->post('method') === 'Minify and serve') {
$source = new Minify_Source($sourceSpec);
$controller = new Minify_Controller_Files($env, $app->sourceFactory, $app->logger);
+
try {
$app->minify->serve($controller, array(
- 'files' => $source,
+ 'files' => $source,
'contentType' => Minify::TYPE_HTML,
));
} catch (Exception $e) {
@@ -58,17 +59,16 @@ $tpl = array();
$tpl['classes'] = array('Minify_HTML', 'JSMin\\JSMin', 'Minify_CSS', 'Minify_Lines');
if (in_array($env->post('method'), $tpl['classes'])) {
-
$args = array($textIn);
if ($env->post('method') === 'Minify_HTML') {
$args[] = array(
- 'cssMinifier' => array('Minify_CSSmin', 'minify')
- ,'jsMinifier' => array('JSMin\\JSMin', 'minify')
+ 'cssMinifier' => array('Minify_CSSmin', 'minify'), 'jsMinifier' => array('JSMin\\JSMin', 'minify'),
);
}
$func = array($env->post('method'), 'minify');
$tpl['inBytes'] = strlen($textIn);
$startTime = microtime(true);
+
try {
$tpl['output'] = call_user_func_array($func, $args);
} catch (Exception $e) {
@@ -82,17 +82,18 @@ if (in_array($env->post('method'), $tpl['classes'])) {
sendPage($tpl);
-
/**
* @param Exception $e
* @param string $input
+ *
* @return string HTML
*/
-function getExceptionMsg(Exception $e, $input) {
- $msg = "" . h($e->getMessage()) . "
";
- if (0 === strpos(get_class($e), 'JSMin_Unterminated')
+function getExceptionMsg(Exception $e, $input)
+{
+ $msg = '' . h($e->getMessage()) . '
';
+ if (strpos(get_class($e), 'JSMin_Unterminated') === 0
&& preg_match('~byte (\d+)~', $e->getMessage(), $m)) {
- $msg .= "";
+ $msg .= '';
if ($m[1] > 200) {
$msg .= h(substr($input, ($m[1] - 200), 200));
} else {
@@ -102,9 +103,10 @@ function getExceptionMsg(Exception $e, $input) {
if ($highlighted === "\n") {
$highlighted = "⏎\n";
}
- $msg .= "$highlighted";
- $msg .= h(substr($input, $m[1] + 1, 200)) . "
";
+ $msg .= "${highlighted}";
+ $msg .= h(substr($input, $m[1] + 1, 200)) . '
';
}
+
return $msg;
}
@@ -113,37 +115,35 @@ function getExceptionMsg(Exception $e, $input) {
*
* @param array $vars
*/
-function sendPage($vars) {
- header('Content-Type: text/html; charset=utf-8');
-?>
+function sendPage($vars)
+{
+ header('Content-Type: text/html; charset=utf-8'); ?>
minifyTextarea
Warning! Please do not place this application on a public site. This should be used only for testing.
Bytes in | {$vars['inBytes']} (after line endings normalized to \\n ) |
- Bytes out | {$vars['outBytes']} (reduced " . round(100 - (100 * $vars['outBytes'] / $vars['inBytes'])) . "%) |
- Time (s) | " . round($vars['time'], 5) . " |
+ Bytes out | {$vars['outBytes']} (reduced " . round(100 - (100 * $vars['outBytes'] / $vars['inBytes'])) . '%) |
+ Time (s) | ' . round($vars['time'], 5) . ' |
- ";
-}
-?>
+ ';
+ } ?>