1
0
mirror of https://github.com/mrclay/minify.git synced 2025-08-11 16:44:44 +02:00

Apply php-cs-fixer new rules

This commit is contained in:
Elan Ruusamäe
2019-12-11 17:00:16 +02:00
parent f9d3d54e62
commit eff278193b
88 changed files with 1225 additions and 1213 deletions

View File

@@ -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

View File

@@ -7,15 +7,15 @@ $config = $app->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};";
}
}
@@ -60,13 +60,13 @@ b {color:#c00}
#jsDidntLoad {display:none;}
</style>
<body>
<?php if ($symlinkOption): ?>
<?php if ($symlinkOption) { ?>
<div class=topNote><strong>Note:</strong> 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:
<br><textarea id=symlinkOpt rows=3 cols=80 readonly><?php echo htmlspecialchars($symlinkOption); ?></textarea>
</div>
<?php endif; ?>
<?php } ?>
<p class=topWarning id=jsDidntLoad><strong>Uh Oh.</strong> Minify was unable to
serve Javascript for this app. To troubleshoot this,

View File

@@ -1,10 +1,7 @@
<?php
/**
* AJAX checks for zlib.output_compression
*
* @package Minify
*/
$app = (require __DIR__ . '/../bootstrap.php');
/* @var \Minify\App $app */
@@ -29,7 +26,6 @@ if ($app->env->get('hello')) {
));
$he->encode();
$he->sendAll();
} else {
// echo status "0" or "1"
header('Content-Type: text/plain');

View File

@@ -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
*/

View File

@@ -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.
*
@@ -53,7 +45,6 @@ $min_errorLogger = false;
*/
$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,14 +53,12 @@ $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'].
*
@@ -85,14 +74,12 @@ $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
* 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
@@ -103,7 +90,6 @@ $min_cacheFileLocking = true;
*/
$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,20 +101,17 @@ $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.
@@ -145,7 +128,6 @@ $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
@@ -155,7 +137,6 @@ $min_serveOptions['minApp']['groupsOnly'] = false;
*/
//$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
@@ -170,7 +151,6 @@ $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
@@ -185,11 +165,11 @@ $min_symlinks = array();
* 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

View File

@@ -1,7 +1,6 @@
<?php
/**
* Groups configuration for default Minify implementation
* @package Minify
*/
/**

View File

@@ -3,10 +3,7 @@
* Sets up MinApp controller and serves files
*
* DO NOT EDIT! Configure this utility via config.php and groupsConfig.php
*
* @package Minify
*/
$app = (require __DIR__ . '/bootstrap.php');
/* @var \Minify\App $app */

View File

@@ -1,8 +1,6 @@
<?php
/**
* Class HTTP_ConditionalGet
* @package Minify
* @subpackage HTTP
*/
/**
@@ -56,13 +54,9 @@
* exit();
* }
* </code>
* @package Minify
* @subpackage HTTP
* @author Stephen Clay <steve@mrclay.org>
*/
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
@@ -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,16 +221,14 @@ 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) {
if ($lastModifiedTime !== null) {
$options['lastModifiedTime'] = (int) $lastModifiedTime;
}
$options['isPublic'] = (bool) $isPublic;
@@ -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)
@@ -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.

View File

@@ -1,8 +1,6 @@
<?php
/**
* Class HTTP_Encoder
* @package Minify
* @subpackage HTTP
*/
/**
@@ -38,14 +36,9 @@
* Note: If you don't need header mgmt, use PHP's native gzencode, gzdeflate,
* and gzcompress functions for gzip, deflate, and compress-encoding
* respectively.
*
* @package Minify
* @subpackage HTTP
* @author Stephen Clay <steve@mrclay.org>
*/
class HTTP_Encoder
{
/**
* Should the encoder allow HTTP encoding to IE6?
*
@@ -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
@@ -197,34 +189,38 @@ class HTTP_Encoder
}
$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]);
}
@@ -253,10 +249,10 @@ class HTTP_Encoder
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,7 +264,7 @@ class HTTP_Encoder
} else {
$encoded = gzcompress($this->_content, $compressionLevel);
}
if (false === $encoded) {
if ($encoded === false) {
return false;
}
$this->_headers['Content-Length'] = $this->_useMbStrlen
@@ -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);
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;
}

View File

@@ -1,9 +1,7 @@
<?php
/**
* Class Minify
* @package Minify
*/
use Psr\Log\LoggerInterface;
/**
@@ -14,16 +12,13 @@ use Psr\Log\LoggerInterface;
* This library was inspired by {@link mailto:flashkot@mail.ru jscsscomp by Maxim Martynyuk}
* and by the article {@link http://www.hunlock.com/blogs/Supercharged_Javascript "Supercharged JavaScript" by Patrick Hunlock}.
*
* @package Minify
* @author Ryan Grove <ryan@wonko.com>
* @author Stephen Clay <steve@mrclay.org>
* @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';
/**
@@ -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())
{
@@ -353,6 +351,7 @@ class Minify
if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
$this->cache->store($cacheId, $content);
@@ -363,6 +362,7 @@ class Minify
} else {
// no cache
$cacheIsReady = false;
try {
$content = $this->combineMinify();
} catch (Exception $e) {
@@ -370,6 +370,7 @@ class Minify
if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
}
@@ -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
*/
@@ -464,8 +464,8 @@ 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 = '')
{
@@ -476,12 +476,12 @@ class Minify
list(, $code) = explode(' ', $header, 3);
header($header, true, $code);
header('Content-Type: text/html; charset=utf-8');
echo "<h1>$h1</h1>";
echo "<h1>${h1}</h1>";
if ($msgHtml) {
echo $msgHtml;
}
if ($url) {
echo "<p>Please see <a href='$url'>$url</a>.</p>";
echo "<p>Please see <a href='${url}'>${url}</a>.</p>";
}
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()
{
@@ -593,7 +594,8 @@ class Minify
!$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;

View File

@@ -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)

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Build
* @package Minify
*/
/**
@@ -30,13 +29,9 @@
* ,'setExpires' => (time() + 86400 * 365)
* ));
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Build
{
/**
* Last modification time of all files in the build
*
@@ -64,8 +59,9 @@ class Minify_Build
* </code>
*
* @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,7 +75,6 @@ class Minify_Build
* Create a build object
*
* @param array $sources array of Minify_Source objects and/or file paths
*
*/
public function __construct($sources)
{
@@ -88,7 +83,7 @@ class Minify_Build
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)) {

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_CSS
* @package Minify
*/
/**
@@ -10,20 +9,14 @@
* This class uses Minify_CSS_Compressor and Minify_CSS_UriRewriter to
* minify CSS and rewrite relative URIs.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @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

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_CSS_Compressor
* @package Minify
*/
/**
@@ -20,20 +19,14 @@
* Compressed files with shorter lines are also easier to diff. If this is
* unacceptable please use CSSmin instead.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @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);

View File

@@ -1,18 +1,13 @@
<?php
/**
* Class Minify_CSS_UriRewriter
* @package Minify
*/
/**
* Rewrite file-relative URIs as root-relative in CSS files
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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
*/
@@ -134,11 +125,8 @@ class Minify_CSS_UriRewriter
* </code>
*
* @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)

View File

@@ -1,27 +1,20 @@
<?php
/**
* Class Minify_CSSmin
* @package Minify
*/
use tubalmartin\CssMin\Minifier as CSSmin;
/**
* Wrapper for CSSmin
*
* This class uses CSSmin and Minify_CSS_UriRewriter to minify CSS and rewrite relative URIs.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_CSSmin
{
/**
* Minify a CSS string
*
* @param string $css
*
* @param array $options available options:
*
* 'removeCharsets': (default true) remove all @charset at-rules
@@ -73,16 +66,16 @@ class Minify_CSSmin
}
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']
);
}
}

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Cache_APC
* @package Minify
*/
/**
@@ -11,17 +10,13 @@
* Minify::setCache(new Minify_Cache_APC());
* </code>
*
* @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
@@ -61,23 +55,22 @@ class Minify_Cache_APC 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);
}
/**
@@ -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;

View File

@@ -1,14 +1,11 @@
<?php
/**
* Class Minify_Cache_File
* @package Minify
*/
use Psr\Log\LoggerInterface;
class Minify_Cache_File implements Minify_CacheInterface
{
/**
* @var string
*/
@@ -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
@@ -58,13 +54,13 @@ class Minify_Cache_File implements Minify_CacheInterface
$file = $this->path . '/' . $id;
if (!@file_put_contents($file, $data, $flag)) {
$this->logger->warning("Minify_Cache_File: Write failed to '$file'");
$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)

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Cache_Memcache
* @package Minify
*/
/**
@@ -19,13 +18,11 @@
**/
class Minify_Cache_Memcache implements Minify_CacheInterface
{
/**
* Create a Minify_Cache_Memcache object, to be passed to
* Minify::setCache().
*
* @param Memcache $memcache already-connected instance
*
* @param int $expire seconds until expiration (default = 0
* meaning the item will not get an expiration date)
*/
@@ -39,7 +36,6 @@ class Minify_Cache_Memcache implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id
*
* @param string $data
*
* @return bool success
@@ -64,23 +60,22 @@ class Minify_Cache_Memcache 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);
}
/**
@@ -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;

View File

@@ -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
{

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Cache_Wincache
* @package Minify
*/
/**
@@ -11,8 +10,6 @@
* Minify::setCache(new Minify_Cache_WinCache());
* </code>
*
* @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

View File

@@ -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());
* </code>
*
* @package Minify
* @author Elan Ruusamäe <glen@delfi.ee>
**/
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,6 +45,7 @@ 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)
@@ -58,9 +56,9 @@ class Minify_Cache_XCache 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);
}
/**
@@ -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;

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Cache_ZendPlatform
* @package Minify
*/
/**
@@ -12,20 +11,15 @@
* <code>
* Minify::setCache(new Minify_Cache_ZendPlatform());
* </code>
*
* @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;

View File

@@ -1,13 +1,10 @@
<?php
/**
* Interface Minify_CacheInterface
* @package Minify
*/
/**
* Interface for Minify cache adapters
*
* @package Minify
*/
interface Minify_CacheInterface
{

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_ClosureCompiler
* @package Minify
*/
/**
@@ -23,10 +22,6 @@
* --compilation_level WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS
*
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author Elan Ruusamäe <glen@delfi.ee>
*/
class Minify_ClosureCompiler
{
@@ -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;

View File

@@ -1,18 +1,13 @@
<?php
/**
* Class Minify_CommentPreserver
* @package Minify
*/
/**
* Process a string in pieces preserving C-style comments that begin with "/*!"
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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);
}

View File

@@ -37,7 +37,7 @@ class Config
public $allowDebugFlag = false;
/**
* @var string|Minify_CacheInterface
* @var Minify_CacheInterface|string
*/
public $cachePath = '';

View File

@@ -1,23 +1,17 @@
<?php
/**
* Class Minify_Controller_Base
* @package Minify
*/
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
/**
* Base class for Minify controller
*
* The controller class validates a request and uses it to create a configuration for Minify::serve().
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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)

View File

@@ -1,11 +1,8 @@
<?php
/**
* Class Minify_Controller_Files
* @package Minify
*/
use Monolog\Logger;
/**
* Controller class for minifying a set of files
*
@@ -24,17 +21,14 @@ use Monolog\Logger;
* ],
* ]);
* </code>
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_Files extends Minify_Controller_Base
{
/**
* Set up file sources
*
* @param array $options controller and Minify options
*
* @return Minify_ServeConfiguration
*
* Controller options:
@@ -68,4 +62,3 @@ class Minify_Controller_Files extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources);
}
}

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Controller_Groups
* @package Minify
*/
/**
@@ -19,13 +18,9 @@
*
* If the above code were placed in /serve.php, it would enable the URLs
* /serve.php/js and /serve.php/css
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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);
}
@@ -73,4 +68,3 @@ class Minify_Controller_Groups extends Minify_Controller_Files
return parent::createConfiguration($options);
}
}

View File

@@ -1,18 +1,13 @@
<?php
/**
* Class Minify_Controller_MinApp
* @package Minify
*/
/**
* Controller class for requests to /min/index.php
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_Controller_MinApp extends Minify_Controller_Base
{
/**
* Set up groups of files as sources
*
@@ -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,7 +55,7 @@ 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);
}
@@ -83,19 +78,19 @@ 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'");
$this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}'");
return new Minify_ServeConfiguration($options);
}
}
}
}
}
if (!$localOptions['groupsOnly'] && isset($get['f'])) {
// try user files
// The following restrictions are to limit the URLs that minify will
@@ -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,17 +153,17 @@ 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`'");
$this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}`'");
return new Minify_ServeConfiguration($options);
}
}
}
if ($selectionId) {
$selectionId .= '_f=';
}
@@ -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',
)));
}

View File

@@ -1,23 +1,20 @@
<?php
/**
* Class Minify_Controller_Page
* @package Minify
*/
/**
* Controller class for serving a single HTML page
*
* @link http://code.google.com/p/minify/source/browse/trunk/web/examples/1/index.php#59
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @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,7 +33,7 @@ class Minify_Controller_Page extends Minify_Controller_Base
{
if (isset($options['file'])) {
$sourceSpec = array(
'filepath' => $options['file']
'filepath' => $options['file'],
);
$f = $options['file'];
} else {
@@ -66,4 +63,3 @@ class Minify_Controller_Page extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}

View File

@@ -1,9 +1,7 @@
<?php
interface Minify_ControllerInterface
{
/**
* Create controller sources and options for Minify::serve()
*

View File

@@ -2,9 +2,6 @@
/**
* Detect whether request should be debugged
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
class Minify_DebugDetector
{

View File

@@ -2,7 +2,6 @@
class Minify_Env
{
/**
* @return string
*/
@@ -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');
}

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_HTML
* @package Minify
*/
/**
@@ -12,14 +11,11 @@
* STYLE and SCRIPT blocks compressed by callback functions.
*
* A test suite is available.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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
@@ -91,7 +85,7 @@ class Minify_HTML
public function process()
{
if ($this->_isXhtml === null) {
$this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
$this->_isXhtml = (strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML') !== false);
}
$this->_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*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/iu'
,array($this, '_removeScriptCB')
,$this->_html);
'/(\\s*)<script(\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/iu',
array($this, '_removeScriptCB'),
$this->_html
);
// replace STYLEs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/iu'
,array($this, '_removeStyleCB')
,$this->_html);
'/\\s*<style(\\b[^>]*>)([\\s\\S]*?)<\\/style>\\s*/iu',
array($this, '_removeStyleCB'),
$this->_html
);
// remove HTML comments (not containing IE conditional comments).
$this->_html = preg_replace_callback(
'/<!--([\\s\\S]*?)-->/u'
,array($this, '_commentCB')
,$this->_html);
'/<!--([\\s\\S]*?)-->/u',
array($this, '_commentCB'),
$this->_html
);
// replace PREs with placeholders
$this->_html = preg_replace_callback('/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/iu'
,array($this, '_removePreCB')
,$this->_html);
$this->_html = preg_replace_callback('/\\s*<pre(\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/iu', array($this, '_removePreCB'), $this->_html);
// replace TEXTAREAs with placeholders
$this->_html = preg_replace_callback(
'/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/iu'
,array($this, '_removeTextareaCB')
,$this->_html);
'/\\s*<textarea(\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/iu',
array($this, '_removeTextareaCB'),
$this->_html
);
// trim each line.
// @todo take into account attribute values that span multiple lines.
@@ -139,24 +135,25 @@ class Minify_HTML
// remove ws outside of all elements
$this->_html = preg_replace(
'/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</u'
,'>$1$2$3<'
,$this->_html);
'/>(\\s(?:\\s*))?([^<]+)(\\s(?:\s*))?</u',
'>$1$2$3<',
$this->_html
);
// use newlines before 1st attribute in open tags (to limit line lengths)
$this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/iu', "$1\n$2", $this->_html);
// fill placeholders
$this->_html = str_replace(
array_keys($this->_placeholders)
,array_values($this->_placeholders)
,$this->_html
array_keys($this->_placeholders),
array_values($this->_placeholders),
$this->_html
);
// issue 229: multi-pass to catch scripts that didn't get replaced in textareas
$this->_html = str_replace(
array_keys($this->_placeholders)
,array_values($this->_placeholders)
,$this->_html
array_keys($this->_placeholders),
array_values($this->_placeholders),
$this->_html
);
return $this->_html;
@@ -164,7 +161,7 @@ class Minify_HTML
protected function _commentCB($m)
{
return (0 === strpos($m[1], '[') || false !== strpos($m[1], '<!['))
return (strpos($m[1], '[') === 0 || strpos($m[1], '<![') !== false)
? $m[0]
: '';
}
@@ -178,9 +175,13 @@ class Minify_HTML
}
protected $_isXhtml;
protected $_replacementHash;
protected $_placeholders = array();
protected $_cssMinifier;
protected $_jsMinifier;
protected function _removePreCB($m)
@@ -209,7 +210,8 @@ class Minify_HTML
: 'trim';
$css = call_user_func($minifier, $css);
return $this->_reservePlace($this->_needsCdata($css)
return $this->_reservePlace(
$this->_needsCdata($css)
? "{$openStyle}/*<![CDATA[*/{$css}/*]]>*/</style>"
: "{$openStyle}{$css}</style>"
);
@@ -238,7 +240,8 @@ class Minify_HTML
: 'trim';
$js = call_user_func($minifier, $js);
return $this->_reservePlace($this->_needsCdata($js)
return $this->_reservePlace(
$this->_needsCdata($js)
? "{$ws1}{$openScript}/*<![CDATA[*/{$js}/*]]>*/</script>{$ws2}"
: "{$ws1}{$openScript}{$js}</script>{$ws2}"
);
@@ -246,13 +249,13 @@ class Minify_HTML
protected function _removeCdata($str)
{
return (false !== strpos($str, '<![CDATA['))
return (strpos($str, '<![CDATA[') !== false)
? str_replace(array('<![CDATA[', ']]>'), '', $str)
: $str;
}
protected function _needsCdata($str)
{
return ($this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/u', $str));
return $this->_isXhtml && preg_match('/(?:[<&]|\\-\\-|\\]\\]>)/u', $str);
}
}

View File

@@ -1,25 +1,23 @@
<?php
/**
* Class Minify_HTML_Helper
* @package Minify
*/
/**
* Helpers for writing Minify URIs into HTML
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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,6 +25,7 @@ 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())
@@ -40,7 +39,7 @@ class Minify_HTML_Helper
'groupsConfigFile' => self::app()->groupsConfigPath,
), $opts);
$h = new self;
$h = new self();
$h->minAppUri = $opts['minAppUri'];
$h->rewriteWorks = $opts['rewriteWorks'];
$h->groupsConfigFile = $opts['groupsConfigFile'];
@@ -60,6 +59,7 @@ class Minify_HTML_Helper
*
* @param bool $farExpires
* @param bool $debug
*
* @return string
*/
public function getRawUri($farExpires = true, $debug = false)
@@ -68,16 +68,16 @@ class Minify_HTML_Helper
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=<paths>
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, '\\', '/');
@@ -142,6 +142,7 @@ class Minify_HTML_Helper
*
* @param array|string $sources
* @param int $lastModified
*
* @return int
*/
public static function getLastModified($sources, $lastModified = 0)
@@ -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);

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_ImportProcessor
* @package Minify
*/
/**
@@ -13,10 +12,6 @@
* processed!
*
* This has a unit test but should be considered "experimental".
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @author Simon Schick <simonsimcity@gmail.com>
*/
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;
@@ -58,7 +53,7 @@ class Minify_ImportProcessor
$file = realpath($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;
}
}

View File

@@ -1,21 +1,17 @@
<?php
/**
* Class Minify_JS_ClosureCompiler
* @package Minify
*/
/**
* Minify Javascript using Google's Closure Compiler API
*
* @link http://code.google.com/closure/compiler/
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @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'
'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,8 +116,10 @@ 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)
{
@@ -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)
{
@@ -181,7 +182,7 @@ class Minify_JS_ClosureCompiler
'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)
@@ -223,7 +225,7 @@ class Minify_JS_ClosureCompiler
$this->additionalOptions,
array(
'js_code' => $js,
'output_info' => ($returnErrors ? 'errors' : 'compiled_code')
'output_info' => ($returnErrors ? 'errors' : 'compiled_code'),
)
),
null,

View File

@@ -1,19 +1,13 @@
<?php
/**
* Class Minify\JS\JShrink
*
* @package Minify
*/
namespace Minify\JS;
/**
* Wrapper to Javascript Minifier built in PHP http://www.tedivm.com
*
* @package Minify
* @author Elan Ruusamäe <glen@pld-linux.org>
* @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())

View File

@@ -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)

View File

@@ -1,19 +1,13 @@
<?php
/**
* Class Minify_Lines
* @package Minify
*/
/**
* Add line numbers in C-style comments for easier debugging of combined content
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
* @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?
*
@@ -103,6 +95,7 @@ class Minify_Lines
// stop comment and keep walking line
$inComment = false;
@$line = (string) substr($line, $index + 2);
continue;
}
@@ -117,6 +110,7 @@ class Minify_Lines
// start comment and keep walking line
$inComment = true;
@$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)
@@ -170,6 +162,7 @@ class Minify_Lines
'".//' => 2,
'\'.//' => 2,
);
break;
case '/*':
$fakes = array(
@@ -182,6 +175,7 @@ class Minify_Lines
'*/*' => 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;
}
}

View File

@@ -2,19 +2,17 @@
/**
* Class Minify_ClosureCompiler
* @package Minify
*/
/**
* Run Closure Compiler via NailGun
*
* @package Minify
* @author Elan Ruusamäe <glen@delfi.ee>
* @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 >/dev/null 2>/dev/null & sleep 10");
$this->shell("${serverCommand} </dev/null >/dev/null 2>/dev/null & sleep 10");
}
}

View File

@@ -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
{

View File

@@ -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();

View File

@@ -1,17 +1,13 @@
<?php
/**
* Class Minify_ServeConfiguration
* @package Minify
*/
/**
* A configuration for Minify::serve() determined by a controller
*
* @package Minify
*/
class Minify_ServeConfiguration
{
/**
* @var Minify_SourceInterface[]
*/

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_Source
* @package Minify
*/
/**
@@ -9,25 +8,21 @@
*
* This allows per-source minification options and the mixing of files with
* content from other sources.
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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;

View File

@@ -2,7 +2,6 @@
class Minify_Source_Factory
{
/**
* @var array
*/
@@ -40,9 +39,7 @@ 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)
{
@@ -59,13 +56,13 @@ class Minify_Source_Factory
// 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);
}
@@ -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.');
}
}
@@ -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;

View File

@@ -1,7 +1,6 @@
<?php
/**
* Interface Minify_SourceInterface
* @package Minify
*/
/**
@@ -9,12 +8,9 @@
*
* This allows per-source minification options and the mixing of files with
* content from other sources.
*
* @package Minify
*/
interface Minify_SourceInterface
{
/**
* Get the minifier
*
@@ -26,6 +22,7 @@ interface Minify_SourceInterface
* Set the minifier
*
* @param callable $minifier
*
* @return void
*/
public function setMinifier($minifier = null);
@@ -41,6 +38,7 @@ interface Minify_SourceInterface
* Set options for the minifier
*
* @param array $options
*
* @return void
*/
public function setMinifierOptions(array $options);

View File

@@ -1,15 +1,9 @@
<?php
/**
* Class Minify_SourceSet
* @package Minify
*/
/**
* @package Minify
*/
class Minify_SourceSet
{
/**
* Get unique string for a set of sources
*
@@ -22,7 +16,7 @@ class Minify_SourceSet
$info = array();
foreach ($sources as $source) {
$info[] = array(
$source->getId(), $source->getMinifier(), $source->getMinifierOptions()
$source->getId(), $source->getMinifier(), $source->getMinifierOptions(),
);
}

View File

@@ -1,7 +1,6 @@
<?php
/**
* Class Minify_YUICompressor
* @package Minify
*/
/**
@@ -25,13 +24,9 @@
* array('stack-size' => '2048k')
*
* @todo unit tests, $options docs
*
* @package Minify
* @author Stephen Clay <steve@mrclay.org>
*/
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
@@ -154,4 +147,3 @@ class Minify_YUICompressor
}
}
}

View File

@@ -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 <steve@mrclay.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Cli
{
/**
* @var array validation errors
*/
@@ -62,12 +60,12 @@ 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
@@ -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,8 +105,10 @@ 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)
{
@@ -123,6 +125,7 @@ class Cli
/**
* @param string $letter
*
* @return Arg|null
*/
public function getArgument($letter)
@@ -170,13 +173,13 @@ 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;
}
@@ -187,18 +190,19 @@ class Cli
// 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) {
// 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) {
@@ -226,27 +230,28 @@ class Cli
$this->_stdout = $v;
}
if ($arg->assertReadable && !is_readable($v)) {
$this->addError($letter, "File not readable: %s", $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);
$this->addError($letter, 'File not writable: %s', $v);
}
} else {
if (!is_writable(dirname($v))) {
$this->addError($letter, "Directory not writable: %s", 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);
$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;
}
}
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;
}
}
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);
}
}

View File

@@ -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 <steve@mrclay.org>
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
class Arg
@@ -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)

View File

@@ -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.');
@@ -54,7 +54,7 @@ if ($paths) {
} else {
$sources[] = new Minify_Source(array(
'id' => $path,
'content' => "/*** $path not found ***/\n",
'content' => "/*** ${path} not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}

View File

@@ -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.');
@@ -44,7 +44,7 @@ foreach ($paths as $path) {
} else {
$sources[] = new Minify_Source(array(
'id' => $path,
'content' => "/*** $path not found ***/\n",
'content' => "/*** ${path} not found ***/\n",
'minifier' => 'Minify::nullMinifier',
));
}
@@ -59,4 +59,3 @@ if ($testRun) {
fwrite($fp, $combined);
$cli->closeOutput();
}

View File

@@ -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,13 +23,12 @@ if ($env->post('textIn')) {
}
if ($env->post('method') === 'Minify and serve') {
$base = trim($env->post('base'));
if ($base) {
$textIn = preg_replace(
'@(<head\\b[^>]*>)@i'
,'$1<base href="' . h($base) . '" />'
,$textIn
'@(<head\\b[^>]*>)@i',
'$1<base href="' . h($base) . '" />',
$textIn
);
}
@@ -43,6 +43,7 @@ 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,
@@ -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 = "<p>" . h($e->getMessage()) . "</p>";
if (0 === strpos(get_class($e), 'JSMin_Unterminated')
function getExceptionMsg(Exception $e, $input)
{
$msg = '<p>' . h($e->getMessage()) . '</p>';
if (strpos(get_class($e), 'JSMin_Unterminated') === 0
&& preg_match('~byte (\d+)~', $e->getMessage(), $m)) {
$msg .= "<pre>";
$msg .= '<pre>';
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 = "&#9166;\n";
}
$msg .= "<span style='background:#c00;color:#fff'>$highlighted</span>";
$msg .= h(substr($input, $m[1] + 1, 200)) . "</span></pre>";
$msg .= "<span style='background:#c00;color:#fff'>${highlighted}</span>";
$msg .= h(substr($input, $m[1] + 1, 200)) . '</span></pre>';
}
return $msg;
}
@@ -113,9 +115,9 @@ 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'); ?>
<!DOCTYPE html><head><title>minifyTextarea</title></head>
<p><strong>Warning! Please do not place this application on a public site.</strong> This should be used only for testing.</p>
@@ -128,22 +130,20 @@ if (isset($vars['time'])) {
echo "
<table>
<tr><th>Bytes in</th><td>{$vars['inBytes']} (after line endings normalized to <code>\\n</code>)</td></tr>
<tr><th>Bytes out</th><td>{$vars['outBytes']} (reduced " . round(100 - (100 * $vars['outBytes'] / $vars['inBytes'])) . "%)</td></tr>
<tr><th>Time (s)</th><td>" . round($vars['time'], 5) . "</td></tr>
<tr><th>Bytes out</th><td>{$vars['outBytes']} (reduced " . round(100 - (100 * $vars['outBytes'] / $vars['inBytes'])) . '%)</td></tr>
<tr><th>Time (s)</th><td>' . round($vars['time'], 5) . '</td></tr>
</table>
";
}
?>
';
} ?>
<form action="?2" method="post">
<p><label>Content<br><textarea name="textIn" cols="80" rows="35" style="width:99%"><?php
if (isset($vars['output'])) {
echo h($vars['output']);
}
?></textarea></label></p>
} ?></textarea></label></p>
<p>Minify with:
<?php foreach ($vars['classes'] as $minClass): ?>
<?php foreach ($vars['classes'] as $minClass) { ?>
<input type="submit" name="method" value="<?php echo $minClass; ?>">
<?php endForEach; ?>
<?php } ?>
</p>
<p>...or <input type="submit" name="method" value="Minify and serve"> this HTML to the browser. Also minify:
<label>CSS <input type="checkbox" name="minCss" checked></label> :
@@ -177,7 +177,7 @@ function selectText(el, begin, end) {
}
window.onload = function () {
var ta = document.querySelector('textarea[name="textIn"]');
selectText(ta, <?= $vars['selectByte'] ?>, <?= ($vars['selectByte'] + 1) ?>);
selectText(ta, <?php echo $vars['selectByte']; ?>, <?php echo $vars['selectByte'] + 1; ?>);
};
</script>
<?php }

View File

@@ -4,7 +4,6 @@ die('Disabled: use this only for testing');
/**
* Fetch and minify a URL (auto-detect HTML/JS/CSS)
*/
$app = (require __DIR__ . '/../../bootstrap.php');
/* @var \Minify\App $app */
@@ -12,23 +11,27 @@ $app->cache = new Minify_Cache_Null();
$env = $app->env;
function getPost($key) {
function getPost($key)
{
if (!isset($_POST[$key])) {
return null;
}
return get_magic_quotes_gpc()
? stripslashes($_POST[$key])
: $_POST[$key];
}
function sniffType($headers) {
function sniffType($headers)
{
$charset = 'utf-8';
$type = null;
$headers = "\n\n" . implode("\n\n", $headers) . "\n\n";
if (preg_match(
'@\\n\\nContent-Type: *([\\w/\\+-]+)( *; *charset *= *([\\w-]+))? *\\n\\n@i'
,$headers
,$m)) {
'@\\n\\nContent-Type: *([\\w/\\+-]+)( *; *charset *= *([\\w-]+))? *\\n\\n@i',
$headers,
$m
)) {
$sentType = $m[1];
if (isset($m[3])) {
$charset = $m[3];
@@ -41,15 +44,13 @@ function sniffType($headers) {
$type = $sentType;
}
}
return array(
'minify' => $type
,'sent' => $sentType
,'charset' => $charset
'minify' => $type, 'sent' => $sentType, 'charset' => $charset,
);
}
if (isset($_POST['url'])) {
require '../config.php';
$url = trim($env->post('url'));
@@ -61,8 +62,7 @@ if (isset($_POST['url'])) {
}
$httpOpts = array(
'max_redirects' => 0
,'timeout' => 3
'max_redirects' => 0, 'timeout' => 3,
);
if ($ua !== '') {
$httpOpts['user_agent'] = $ua;
@@ -71,7 +71,7 @@ if (isset($_POST['url'])) {
$httpOpts['header'] = "Cookie: {$cook}\r\n";
}
$ctx = stream_context_create(array(
'http' => $httpOpts
'http' => $httpOpts,
));
// fetch
@@ -92,9 +92,9 @@ if (isset($_POST['url'])) {
&& isset($_POST['addBase'])
&& !preg_match('@<base\\b@i', $content)) {
$content = preg_replace(
'@(<head\\b[^>]*>)@i'
,'$1<base href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" />'
,$content
'@(<head\\b[^>]*>)@i',
'$1<base href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" />',
$content
);
}

View File

@@ -8,11 +8,16 @@ $env = $app->env;
header('Content-Type: text/html;charset=utf-8');
function h($str) { return htmlspecialchars($str, ENT_QUOTES); }
function h($str)
{
return htmlspecialchars($str, ENT_QUOTES);
}
function getInput($name, $default = '', $size = 50) {
function getInput($name, $default = '', $size = 50)
{
global $env;
$val = $env->post($name, $default);
return "<input type='text' name='{$name}' value='" . h($val) . "' size='{$size}' />";
}
@@ -26,7 +31,7 @@ $out = '';
if ($env->post('css')) {
$symlinks = array();
if ('' !== ($target = $env->post('symTarget'))) {
if (($target = $env->post('symTarget')) !== '') {
$symlinks[$env->post('symLink')] = $target;
}
$css = Minify_CSS_UriRewriter::rewrite(
@@ -35,7 +40,7 @@ if ($env->post('css')) {
$env->post('docRoot'),
$symlinks
);
$out = "<hr /><pre><code>" . h($css) . '</code></pre>';
$out = '<hr /><pre><code>' . h($css) . '</code></pre>';
}
?>

View File

@@ -13,10 +13,12 @@ if (!$enabled) {
die('Set $enabled to true to see server info.');
}
function assertTrue($test, $message) {
function assertTrue($test, $message)
{
if (!$test) {
echo "Warning: $message\n";
echo "Warning: ${message}\n";
}
return (bool) $test;
}
@@ -26,8 +28,8 @@ $file = __FILE__;
$tmp = sys_get_temp_dir();
echo <<<EOD
Cache directory : $tmp
__FILE__ : $file
Cache directory : ${tmp}
__FILE__ : ${file}
SCRIPT_FILENAME : {$_SERVER['SCRIPT_FILENAME']}
DOCUMENT_ROOT : {$_SERVER['DOCUMENT_ROOT']}
SCRIPT_NAME : {$_SERVER['SCRIPT_NAME']}
@@ -37,17 +39,17 @@ REQUEST_URI : {$_SERVER['REQUEST_URI']}
EOD;
$noSlash = assertTrue(
0 === preg_match('@[\\\\/]$@', $_SERVER['DOCUMENT_ROOT']),
preg_match('@[\\\\/]$@', $_SERVER['DOCUMENT_ROOT']) === 0,
'DOCUMENT_ROOT ends in trailing slash'
);
$isRealPath = assertTrue(
false !== realpath($_SERVER['DOCUMENT_ROOT']),
realpath($_SERVER['DOCUMENT_ROOT']) !== false,
'DOCUMENT_ROOT fails realpath()'
);
$containsThisFile = assertTrue(
0 === strpos(realpath(__FILE__), realpath($_SERVER['DOCUMENT_ROOT'])),
strpos(realpath(__FILE__), realpath($_SERVER['DOCUMENT_ROOT'])) === 0,
'DOCUMENT_ROOT contains this test file'
);
@@ -62,7 +64,7 @@ assertTrue(
assertTrue(
realpath(__FILE__) === realpath($_SERVER['DOCUMENT_ROOT'] . '/min/server-info.php'),
"/min/ is not directly inside DOCUMENT_ROOT."
'/min/ is not directly inside DOCUMENT_ROOT.'
);
// TODO: rework this

View File

@@ -14,8 +14,8 @@ $send_400 = function($content = 'Bad URL') {
$send_301 = function ($url) {
http_response_code(301);
header("Cache-Control: max-age=31536000");
header("Location: $url");
header('Cache-Control: max-age=31536000');
header("Location: ${url}");
exit;
};
@@ -59,7 +59,7 @@ $query = $m[2];
// these parameters anyway.
$get_params = array();
foreach (explode('&', $query) as $piece) {
if (false === strpos($piece, '=')) {
if (strpos($piece, '=') === false) {
$send_400();
}
@@ -97,31 +97,31 @@ if (!$sources) {
die('File not found');
}
if ($sources[0]->getId() === 'id::missingFile') {
$send_400("Bad URL: missing file");
$send_400('Bad URL: missing file');
}
// we need URL to end in appropriate extension
$type = $sources[0]->getContentType();
$ext = ($type === Minify::TYPE_JS) ? '.js' : '.css';
if (substr($query, -strlen($ext)) !== $ext) {
$send_301("$root_uri/$cache_time/{$query}&z=$ext");
$send_301("${root_uri}/${cache_time}/{$query}&z=${ext}");
}
// fix the cache dir in the URL
if ($cache_time !== $requested_cache_dir) {
$send_301("$root_uri/$cache_time/$query");
$send_301("${root_uri}/${cache_time}/${query}");
}
$content = $app->minify->combine($sources);
// save and send file
$file = __DIR__ . "/$cache_time/$query";
$file = __DIR__ . "/${cache_time}/${query}";
if (!is_dir(dirname($file))) {
mkdir(dirname($file), 0777, true);
}
file_put_contents($file, $content);
header("Content-Type: $type;charset=utf-8");
header("Cache-Control: max-age=31536000");
header("Content-Type: ${type};charset=utf-8");
header('Cache-Control: max-age=31536000');
echo $content;

View File

@@ -8,32 +8,37 @@ namespace Minify\StaticService;
* @param string $static_uri E.g. "/min/static"
* @param string $query E.g. "b=scripts&f=1.js,2.js"
* @param string $type "css" or "js"
*
* @return string
*/
function build_uri($static_uri, $query, $type) {
function build_uri($static_uri, $query, $type)
{
$static_uri = rtrim($static_uri, '/');
$query = ltrim($query, '?');
$ext = ".$type";
$ext = ".${type}";
if (substr($query, -strlen($ext)) !== $ext) {
$query .= "&z=$ext";
$query .= "&z=${ext}";
}
$cache_time = get_cache_time();
return "$static_uri/$cache_time/$query";
return "${static_uri}/${cache_time}/${query}";
}
/**
* Get the name of the current cache directory within static/. E.g. "1467089473"
*
* @param bool $auto_create Automatically create the directory if missing?
* @return null|string null if missing or can't create
*
* @return string|null null if missing or can't create
*/
function get_cache_time($auto_create = true) {
function get_cache_time($auto_create = true)
{
foreach (scandir(__DIR__) as $entry) {
if (ctype_digit($entry)) {
return $entry;
break;
}
}
@@ -43,25 +48,27 @@ function get_cache_time($auto_create = true) {
}
$time = (string) time();
if (!mkdir(__DIR__ . "/$time")) {
if (!mkdir(__DIR__ . "/${time}")) {
return null;
}
return $time;
}
function flush_cache() {
function flush_cache()
{
$time = get_cache_time(false);
if ($time) {
remove_tree(__DIR__ . "/$time");
remove_tree(__DIR__ . "/${time}");
}
}
function remove_tree($dir) {
function remove_tree($dir)
{
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
is_dir("$dir/$file") ? remove_tree("$dir/$file") : unlink("$dir/$file");
is_dir("${dir}/${file}") ? remove_tree("${dir}/${file}") : unlink("${dir}/${file}");
}
return rmdir($dir);

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use HTTP_ConditionalGet;
/**
* @internal
*/
class HTTPConditionalGetTest extends TestCase
{
public function TestData()
@@ -18,7 +21,7 @@ class HTTPConditionalGetTest extends TestCase
$lmTime = time() - 900;
$gmtTime = gmdate('D, d M Y H:i:s \G\M\T', $lmTime);
$tests = array(
return array(
array(
'lm' => $lmTime,
'desc' => 'client has valid If-Modified-Since',
@@ -31,7 +34,7 @@ class HTTPConditionalGetTest extends TestCase
'Cache-Control' => 'max-age=0, private',
'_responseCode' => 'HTTP/1.0 304 Not Modified',
'isValid' => true,
)
),
),
array(
'lm' => $lmTime,
@@ -115,16 +118,21 @@ class HTTPConditionalGetTest extends TestCase
),
),
);
return $tests;
}
/**
* @dataProvider TestData
*
* @param mixed $lmTime
* @param mixed $desc
* @param mixed $inm
* @param mixed $ims
* @param mixed $exp
*/
public function test_HTTP_ConditionalGet($lmTime, $desc, $inm, $ims, $exp)
public function testHTTPConditionalGet($lmTime, $desc, $inm, $ims, $exp)
{
// setup env
if (null === $inm) {
if ($inm === null) {
unset($_SERVER['HTTP_IF_NONE_MATCH']);
} else {
$_SERVER['HTTP_IF_NONE_MATCH'] = get_magic_quotes_gpc()
@@ -132,7 +140,7 @@ class HTTPConditionalGetTest extends TestCase
$inm;
}
if (null === $ims) {
if ($ims === null) {
unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
} else {
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = $ims;

View File

@@ -4,11 +4,19 @@ namespace Minify\Test;
use HTTP_Encoder;
/**
* @internal
*/
class HTTPEncoderTest extends TestCase
{
/**
* @dataProvider ToIe6DataProvider
* @preserveGlobals
*
* @param mixed $ua
* @param mixed $ae
* @param mixed $exp
* @param mixed $desc
*/
public function testToIe6($ua, $ae, $exp, $desc)
{
@@ -70,6 +78,11 @@ class HTTPEncoderTest extends TestCase
/**
* @dataProvider EncodeNonIeDataProvider
*
* @param mixed $ua
* @param mixed $ae
* @param mixed $exp
* @param mixed $desc
*/
public function testEncodeNonIe($ua, $ae, $exp, $desc)
{
@@ -89,7 +102,7 @@ class HTTPEncoderTest extends TestCase
'ae' => 'gzip, deflate',
'exp' => array('', ''),
'desc' => 'IE6 w/ "enhanced security"',
)
),
);
}
@@ -149,6 +162,7 @@ class HTTPEncoderTest extends TestCase
function _gzdecode($data)
{
$filename = $error = '';
return _phpman_gzdecode($data, $filename, $error);
}
@@ -164,59 +178,63 @@ function _phpman_gzdecode($data, &$filename='', &$error='', $maxlength=null)
mb_internal_encoding('8bit');
}
$len = strlen($data);
if ($len < 18 || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
$error = "Not in GZIP format.";
$error = 'Not in GZIP format.';
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return null; // Not GZIP format (See RFC 1952)
}
$method = ord(substr($data, 2, 1)); // Compression method
$flags = ord(substr($data, 3, 1)); // Flags
if ($flags & 31 != $flags) {
$error = "Reserved bits not allowed.";
if ($flags & $flags != 31) {
$error = 'Reserved bits not allowed.';
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return null;
}
// NOTE: $mtime may be negative (PHP integer limitations)
$mtime = unpack("V", substr($data,4,4));
$mtime = unpack('V', substr($data, 4, 4));
$mtime = $mtime[1];
$xfl = substr($data, 8, 1);
$os = substr($data, 8, 1);
$headerlen = 10;
$extralen = 0;
$extra = "";
$extra = '';
if ($flags & 4) {
// 2-byte length prefixed EXTRA data in header
if ($len - $headerlen - 2 < 8) {
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$extralen = unpack("v",substr($data,8,2));
$extralen = unpack('v', substr($data, 8, 2));
$extralen = $extralen[1];
if ($len - $headerlen - 2 - $extralen < 8) {
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$extra = substr($data, 10, $extralen);
$headerlen += 2 + $extralen;
}
$filenamelen = 0;
$filename = "";
$filename = '';
if ($flags & 8) {
// C-style string
if ($len - $headerlen - 1 < 8) {
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$filenamelen = strpos(substr($data, $headerlen), chr(0));
@@ -224,19 +242,21 @@ function _phpman_gzdecode($data, &$filename='', &$error='', $maxlength=null)
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$filename = substr($data, $headerlen, $filenamelen);
$headerlen += $filenamelen + 1;
}
$commentlen = 0;
$comment = "";
$comment = '';
if ($flags & 16) {
// C-style string COMMENT data in header
if ($len - $headerlen - 1 < 8) {
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$commentlen = strpos(substr($data, $headerlen), chr(0));
@@ -244,36 +264,39 @@ function _phpman_gzdecode($data, &$filename='', &$error='', $maxlength=null)
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // Invalid header format
}
$comment = substr($data, $headerlen, $commentlen);
$headerlen += $commentlen + 1;
}
$headercrc = "";
$headercrc = '';
if ($flags & 2) {
// 2-bytes (lowest order) of CRC32 on header present
if ($len - $headerlen - 2 < 8) {
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // invalid
}
$calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;
$headercrc = unpack("v", substr($data,$headerlen,2));
$headercrc = unpack('v', substr($data, $headerlen, 2));
$headercrc = $headercrc[1];
if ($headercrc != $calccrc) {
$error = "Header checksum failed.";
$error = 'Header checksum failed.';
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false; // Bad header CRC
}
$headerlen += 2;
}
// GZIP FOOTER
$datacrc = unpack("V",substr($data,-8,4));
$datacrc = unpack('V', substr($data, -8, 4));
$datacrc = sprintf('%u', $datacrc[1] & 0xFFFFFFFF);
$isize = unpack("V",substr($data,-4));
$isize = unpack('V', substr($data, -4));
$isize = $isize[1];
// decompression:
$bodylen = $len - $headerlen - 8;
@@ -282,26 +305,29 @@ function _phpman_gzdecode($data, &$filename='', &$error='', $maxlength=null)
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return null;
}
$body = substr($data, $headerlen, $bodylen);
$data = "";
$data = '';
if ($bodylen > 0) {
switch ($method) {
case 8:
// Currently the only supported compression method:
$data = gzinflate($body, $maxlength);
break;
default:
$error = "Unknown compression method.";
$error = 'Unknown compression method.';
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return false;
}
} // zero-byte body content is allowed
// Verifiy CRC32
$crc = sprintf("%u",crc32($data));
$crc = sprintf('%u', crc32($data));
$crcOK = $crc == $datacrc;
$lenOK = $isize == strlen($data);
if (!$lenOK || !$crcOK) {
@@ -312,5 +338,6 @@ function _phpman_gzdecode($data, &$filename='', &$error='', $maxlength=null)
if ($mbIntEnc !== null) {
mb_internal_encoding($mbIntEnc);
}
return $ret;
}

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Exception;
use JSMin\JSMin;
/**
* @internal
*/
class JSMinTest extends TestCase
{
public function test1()
@@ -63,6 +66,7 @@ class JSMinTest extends TestCase
public function testJSMinException($js, $label, $expClass, $expMessage)
{
$eClass = $eMsg = '';
try {
JSMin::minify($js);
} catch (Exception $e) {
@@ -80,7 +84,7 @@ class JSMinTest extends TestCase
'"Hello',
'Unterminated String',
'JSMin\UnterminatedStringException',
"JSMin: Unterminated String at byte 5: \"Hello",
'JSMin: Unterminated String at byte 5: "Hello',
),
array(
@@ -119,10 +123,10 @@ class JSMinTest extends TestCase
),
array(
"/* Comment ",
'/* Comment ',
'Unterminated Comment',
'JSMin\UnterminatedCommentException',
"JSMin: Unterminated comment at byte 11: /* Comment ",
'JSMin: Unterminated comment at byte 11: /* Comment ',
),
);
}

View File

@@ -5,11 +5,14 @@ namespace Minify\Test;
use Minify_JS_ClosureCompiler;
use Minify_JS_ClosureCompiler_Exception;
/**
* @internal
*/
class JsClosureCompilerTest extends TestCase
{
public function test1()
{
$src = "
$src = '
(function (window, undefined){
function addOne(input) {
return 1 + input;
@@ -17,8 +20,8 @@ class JsClosureCompilerTest extends TestCase
window.addOne = addOne;
window.undefined = undefined;
})(window);
";
$minExpected = "(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);";
';
$minExpected = '(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);';
$minOutput = $this->compile($src);
$this->assertSame($minExpected, $minOutput, 'Minify_JS_ClosureCompiler : Overall');
@@ -28,26 +31,34 @@ class JsClosureCompilerTest extends TestCase
{
$src = "function blah({ return 'blah';} ";
$e = null;
try {
$this->compile($src);
} catch (Minify_JS_ClosureCompiler_Exception $e) {
}
$this->assertInstanceOf('Minify_JS_ClosureCompiler_Exception', $e,
'Throws Minify_JS_ClosureCompiler_Exception');
$this->assertInstanceOf(
'Minify_JS_ClosureCompiler_Exception',
$e,
'Throws Minify_JS_ClosureCompiler_Exception'
);
}
// Test maximum byte size check (default)
public function test3()
{
$fn = "(function() {})();";
$fn = '(function() {})();';
$src = str_repeat($fn, ceil(Minify_JS_ClosureCompiler::DEFAULT_MAX_BYTES / strlen($fn)));
$e = null;
try {
$this->compile($src);
} catch (Minify_JS_ClosureCompiler_Exception $e) {
}
$this->assertInstanceOf('Minify_JS_ClosureCompiler_Exception', $e,
'Throws Minify_JS_ClosureCompiler_Exception');
$this->assertInstanceOf(
'Minify_JS_ClosureCompiler_Exception',
$e,
'Throws Minify_JS_ClosureCompiler_Exception'
);
$expected = 'POST content larger than ' . Minify_JS_ClosureCompiler::DEFAULT_MAX_BYTES . ' bytes';
$this->assertEquals($expected, $e->getMessage(), 'Message must tell how big maximum byte size is');
@@ -56,7 +67,7 @@ class JsClosureCompilerTest extends TestCase
// Test maximum byte size check (no limit)
public function test4()
{
$src = "(function(){})();";
$src = '(function(){})();';
$minOutput = $this->compile($src, array(
Minify_JS_ClosureCompiler::OPTION_MAX_BYTES => 0,
));
@@ -67,17 +78,21 @@ class JsClosureCompilerTest extends TestCase
// Test maximum byte size check (custom)
public function test5()
{
$src = "(function() {})();";
$src = '(function() {})();';
$allowedBytes = 5;
$e = null;
try {
$this->compile($src, array(
Minify_JS_ClosureCompiler::OPTION_MAX_BYTES => $allowedBytes,
));
} catch (Minify_JS_ClosureCompiler_Exception $e) {
}
$this->assertInstanceOf('Minify_JS_ClosureCompiler_Exception', $e,
'Throws Minify_JS_ClosureCompiler_Exception');
$this->assertInstanceOf(
'Minify_JS_ClosureCompiler_Exception',
$e,
'Throws Minify_JS_ClosureCompiler_Exception'
);
$expected = 'POST content larger than ' . $allowedBytes . ' bytes';
$this->assertEquals($expected, $e->getMessage(), 'Message must tell how big maximum byte size is');
@@ -86,8 +101,9 @@ class JsClosureCompilerTest extends TestCase
// Test additional options passed to HTTP request
public function test6()
{
$ecmascript3 = "[1,].length;";
$ecmascript3 = '[1,].length;';
$e = null;
try {
$this->compile($ecmascript3, array(
Minify_JS_ClosureCompiler::OPTION_ADDITIONAL_OPTIONS => array(
@@ -96,13 +112,16 @@ class JsClosureCompilerTest extends TestCase
));
} catch (Minify_JS_ClosureCompiler_Exception $e) {
}
$this->assertInstanceOf('Minify_JS_ClosureCompiler_Exception', $e,
'Throws Minify_JS_ClosureCompiler_Exception');
$this->assertInstanceOf(
'Minify_JS_ClosureCompiler_Exception',
$e,
'Throws Minify_JS_ClosureCompiler_Exception'
);
}
public function test7()
{
$ecmascript5 = "[1,].length;";
$ecmascript5 = '[1,].length;';
$minExpected = '1;';
$minOutput = $this->compile($ecmascript5, array(
@@ -118,6 +137,7 @@ class JsClosureCompilerTest extends TestCase
*
* @param string $script
* @param array $options
*
* @return string
*/
private function compile($script, $options = array())

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_HTML_Helper;
/**
* @internal
*/
class LessSourceTest extends TestCase
{
public function setUp()
@@ -13,14 +16,14 @@ class LessSourceTest extends TestCase
}
/**
* @link https://github.com/mrclay/minify/issues/500
* @see https://github.com/mrclay/minify/issues/500
*/
public function testLessTimestamp()
{
$baseDir = self::$test_files;
$mainLess = "$baseDir/main.less";
$includedLess = "$baseDir/included.less";
$mainLess = "${baseDir}/main.less";
$includedLess = "${baseDir}/included.less";
// touch timestamp with 1s difference
touch($mainLess);
@@ -33,7 +36,7 @@ class LessSourceTest extends TestCase
$max = max($mtime1, $mtime2);
$options = array(
'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php",
'groupsConfigFile' => "${baseDir}/htmlHelper_groupsConfig.php",
);
$res = Minify_HTML_Helper::getUri('less', $options);

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Minify_Build;
use Minify_Source;
/**
* @internal
*/
class MinifyBuildTest extends TestCase
{
public function test()

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_CSS_UriRewriter;
/**
* @internal
*/
class MinifyCSSUriRewriterTest extends TestCase
{
public function setUp()
@@ -16,9 +19,10 @@ class MinifyCSSUriRewriterTest extends TestCase
$in = file_get_contents(self::$test_files . '/css_uriRewriter/in.css');
$expected = file_get_contents(self::$test_files . '/css_uriRewriter/exp.css');
$actual = Minify_CSS_UriRewriter::rewrite(
$in
, self::$test_files . '/css_uriRewriter' // currentDir
, self::$document_root // use DOCUMENT_ROOT = '/full/path/to/min_unit_tests'
$in,
self::$test_files . '/css_uriRewriter' // currentDir
,
self::$document_root // use DOCUMENT_ROOT = '/full/path/to/min_unit_tests'
);
$this->assertEquals($expected, $actual, 'rewrite, debug: ' . Minify_CSS_UriRewriter::$debugText);
@@ -47,9 +51,9 @@ class MinifyCSSUriRewriterTest extends TestCase
$in = '../../../../assets/skins/sam/sprite.png';
$exp = '/yui/assets/skins/sam/sprite.png';
$actual = Minify_CSS_UriRewriter::rewriteRelative(
$in
, 'sf_root_dir\web\yui\menu\assets\skins\sam'
, 'sf_root_dir\web'
$in,
'sf_root_dir\web\yui\menu\assets\skins\sam',
'sf_root_dir\web'
);
$this->assertEquals($exp, $actual, 'Issue 99, debug: ' . Minify_CSS_UriRewriter::$debugText);

View File

@@ -4,13 +4,16 @@ namespace Minify\Test;
use Minify_Cache_APC;
/**
* @internal
*/
class MinifyCacheAPCTest extends TestCase
{
public function setUp()
{
if (!function_exists('apc_store')) {
// FIXME: is APCu extension ok too?
$this->markTestSkipped("To test this component, install APC extension");
$this->markTestSkipped('To test this component, install APC extension');
}
}

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_Cache_File;
/**
* @internal
*/
class MinifyCacheFileTest extends TestCase
{
public function test1()

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Memcache;
use Minify_Cache_Memcache;
/**
* @internal
*/
class MinifyCacheMemcacheTest extends TestCase
{
/** @var Memcache */
@@ -13,12 +16,12 @@ class MinifyCacheMemcacheTest extends TestCase
public function setUp()
{
if (!function_exists('memcache_set')) {
$this->markTestSkipped("To test this component, install memcache in PHP");
$this->markTestSkipped('To test this component, install memcache in PHP');
}
$this->mc = new Memcache();
if (!$this->mc->connect('localhost', 11211)) {
$this->markTestSkipped("Memcache server not found on localhost:11211");
$this->markTestSkipped('Memcache server not found on localhost:11211');
}
}
@@ -34,7 +37,7 @@ class MinifyCacheMemcacheTest extends TestCase
public function test2()
{
if (!function_exists('gzencode')) {
$this->markTestSkipped("enable gzip extension to test this");
$this->markTestSkipped('enable gzip extension to test this');
}
$data = str_repeat(md5(time()) . 'í', 100); // 3400 bytes in UTF-8
@@ -45,4 +48,3 @@ class MinifyCacheMemcacheTest extends TestCase
$this->assertTestCache($cache, $id, $data);
}
}

View File

@@ -4,12 +4,15 @@ namespace Minify\Test;
use Minify_Cache_WinCache;
/**
* @internal
*/
class MinifyCacheWinCacheTest extends TestCase
{
public function setUp()
{
if (!function_exists('wincache_ucache_info')) {
$this->markTestSkipped("To test this component, install WinCache extension");
$this->markTestSkipped('To test this component, install WinCache extension');
}
}

View File

@@ -4,13 +4,16 @@ namespace Minify\Test;
use Minify_Cache_ZendPlatform;
/**
* @internal
*/
class MinifyCacheZendPlatformTest extends TestCase
{
public function setUp()
{
if (!function_exists('output_cache_put')) {
// FIXME: be specific what to actually install
$this->markTestSkipped("To test this component, install ZendPlatform");
$this->markTestSkipped('To test this component, install ZendPlatform');
}
}

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Exception;
use Minify_ClosureCompiler;
/**
* @internal
*/
class MinifyClosureCompilerTest extends TestCase
{
public static function setupBeforeClass()
@@ -29,6 +32,7 @@ class MinifyClosureCompilerTest extends TestCase
// clear params
Minify_ClosureCompiler::$jarFile = null;
Minify_ClosureCompiler::$tempDir = null;
try {
Minify_ClosureCompiler::minify('');
$this->fail();
@@ -45,7 +49,7 @@ class MinifyClosureCompilerTest extends TestCase
public function test2()
{
$this->assertHasJar();
$src = "
$src = '
(function (window, undefined){
function addOne(input) {
return 1 + input;
@@ -53,8 +57,8 @@ class MinifyClosureCompilerTest extends TestCase
window.addOne = addOne;
window.undefined = undefined;
})(window);
";
$minExpected = "(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);";
';
$minExpected = '(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);';
$minOutput = Minify_ClosureCompiler::minify($src);
$this->assertSame($minExpected, $minOutput, 'minimum necessary settings');
}
@@ -65,10 +69,10 @@ class MinifyClosureCompilerTest extends TestCase
public function test3()
{
$this->assertHasJar();
$src = "function unused() {};";
$src = 'function unused() {};';
$minExpected = '';
$options = array(
'compilation_level' => 'ADVANCED_OPTIMIZATIONS'
'compilation_level' => 'ADVANCED_OPTIMIZATIONS',
);
$minOutput = Minify_ClosureCompiler::minify($src, $options);
$this->assertSame($minExpected, $minOutput, 'advanced optimizations');
@@ -118,8 +122,9 @@ class MinifyClosureCompilerTest extends TestCase
protected function assertHasJar()
{
$this->assertNotEmpty(Minify_ClosureCompiler::$jarFile);
try {
$this->assertFileExists(Minify_ClosureCompiler::$jarFile, "Have closure compiler compiler.jar");
$this->assertFileExists(Minify_ClosureCompiler::$jarFile, 'Have closure compiler compiler.jar');
} catch (Exception $e) {
$this->markTestSkipped($e->getMessage());
}

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_CommentPreserver;
/**
* @internal
*/
class MinifyCommentPreserverTest extends TestCase
{
public function test()
@@ -24,11 +27,15 @@ class MinifyCommentPreserverTest extends TestCase
/**
* @internal
*
* @param mixed $content
* @param mixed $options
*/
public static function _test_MCP_processor($content, $options = array())
{
static $callCount = 0;
++$callCount;
return $callCount . strtoupper($content);
}
}

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Minify_HTML_Helper;
use Minify_Source;
/**
* @internal
*/
class MinifyHTMLHelperTest extends TestCase
{
private $realDocRoot;
@@ -38,21 +41,18 @@ class MinifyHTMLHelperTest extends TestCase
$actual = Minify_HTML_Helper::getUri(array($file1, $file2));
$this->assertEquals($expected, $actual, 'given filepaths');
$expected = "/min/g=notRealGroup&amp;debug";
$expected = '/min/g=notRealGroup&amp;debug';
$actual = Minify_HTML_Helper::getUri('notRealGroup', array('debug' => true));
$this->assertEquals($expected, $actual, 'non-existent group & debug');
$expected = "/myApp/min/?g=css&amp;{$maxTime}";
$actual = Minify_HTML_Helper::getUri('css', array(
'rewriteWorks' => false
,
'minAppUri' => '/myApp/min/'
,
'groupsConfigFile' => self::$test_files . '/htmlHelper_groupsConfig.php'
'rewriteWorks' => false,
'minAppUri' => '/myApp/min/',
'groupsConfigFile' => self::$test_files . '/htmlHelper_groupsConfig.php',
));
$this->assertEquals($expected, $actual, 'existing group');
$utilsFile = dirname(__DIR__) . '/min/utils.php';
if (is_file($utilsFile)) {
require_once $utilsFile;
@@ -73,9 +73,8 @@ class MinifyHTMLHelperTest extends TestCase
'lastModified' => strtotime('2000-01-01'),
));
$output = Minify_mtime(array(
$obj
,
'css'
$obj,
'css',
), self::$test_files . '/htmlHelper_groupsConfig.php');
$this->assertEquals($maxTime, $output, 'utils.php : Minify_mtime w/ obj & group');
}

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_HTML;
/**
* @internal
*/
class MinifyHTMLTest extends TestCase
{
public function test1()

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_ImportProcessor;
/**
* @internal
*/
class MinifyImportProcessorTest extends TestCase
{
public function test()
@@ -23,7 +26,10 @@ class MinifyImportProcessorTest extends TestCase
realpath($linDir . '/lib/css/example.css'),
);
$this->assertEquals($expectedIncludes, Minify_ImportProcessor::$filesIncluded,
'included right files in right order');
$this->assertEquals(
$expectedIncludes,
Minify_ImportProcessor::$filesIncluded,
'included right files in right order'
);
}
}

View File

@@ -8,9 +8,12 @@ use Minify_Controller_Files;
use Minify_Env;
use Minify_Source_Factory;
/**
* @internal
*/
class MinifyLinesTest extends TestCase
{
public function test_lines()
public function testLines()
{
$env = new Minify_Env(array(
'server' => array(
@@ -21,7 +24,7 @@ class MinifyLinesTest extends TestCase
$controller = new Minify_Controller_Files($env, $sourceFactory);
$minify = new Minify(new Minify_Cache_Null());
$files = glob(self::$test_files . "/lines/*.in.js");
$files = glob(self::$test_files . '/lines/*.in.js');
// uncomment to debug one
//$files = array(self::$test_files . "/lines/basic.in.js");
@@ -41,7 +44,7 @@ class MinifyLinesTest extends TestCase
// uncomment to set up expected output
//file_put_contents($outFile, $ret['content']);
$this->assertEquals($exp, $ret['content'], "Did not match: " . basename($outFile));
$this->assertEquals($exp, $ret['content'], 'Did not match: ' . basename($outFile));
}
}
}

View File

@@ -6,6 +6,9 @@ use Exception;
use Minify_ClosureCompiler;
use Minify_NailgunClosureCompiler;
/**
* @internal
*/
class MinifyNailgunClosureCompilerTest extends TestCase
{
public static function setupBeforeClass()
@@ -29,7 +32,7 @@ class MinifyNailgunClosureCompilerTest extends TestCase
public function test1()
{
$this->assertHasJar();
$src = "
$src = '
(function (window, undefined){
function addOne(input) {
return 1 + input;
@@ -37,8 +40,8 @@ class MinifyNailgunClosureCompilerTest extends TestCase
window.addOne = addOne;
window.undefined = undefined;
})(window);
";
$minExpected = "(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);";
';
$minExpected = '(function(a,b){a.addOne=function(a){return 1+a};a.undefined=b})(window);';
$minOutput = Minify_NailgunClosureCompiler::minify($src);
$this->assertSame($minExpected, $minOutput, 'minimum necessary settings');
}
@@ -47,9 +50,10 @@ class MinifyNailgunClosureCompilerTest extends TestCase
{
$this->assertNotEmpty(Minify_ClosureCompiler::$jarFile);
$this->assertNotEmpty(Minify_NailgunClosureCompiler::$ngJarFile);
try {
$this->assertFileExists(Minify_ClosureCompiler::$jarFile, "Have closure compiler compiler.jar");
$this->assertFileExists(Minify_NailgunClosureCompiler::$ngJarFile, "Have nailgun.jar");
$this->assertFileExists(Minify_ClosureCompiler::$jarFile, 'Have closure compiler compiler.jar');
$this->assertFileExists(Minify_NailgunClosureCompiler::$ngJarFile, 'Have nailgun.jar');
} catch (Exception $e) {
$this->markTestSkipped($e->getMessage());
}

View File

@@ -8,9 +8,12 @@ use Minify_Controller_Files;
use Minify_Env;
use Minify_Source_Factory;
/**
* @internal
*/
class MinifyTest extends TestCase
{
public function test_Minify()
public function testMinify()
{
$minifyTestPath = self::$test_files . '/minify';
@@ -62,8 +65,8 @@ class MinifyTest extends TestCase
$content = preg_replace('/\\r\\n?/', "\n", file_get_contents($minifyTestPath . '/minified.js'));
$lastModified = max(
filemtime($minifyTestPath . '/email.js')
, filemtime($minifyTestPath . '/QueryString.js')
filemtime($minifyTestPath . '/email.js'),
filemtime($minifyTestPath . '/QueryString.js')
);
$expected = array(
'success' => true,
@@ -78,11 +81,10 @@ class MinifyTest extends TestCase
'Cache-Control' => 'max-age=86400',
'Content-Length' => $this->countBytes($content),
'Content-Type' => 'application/x-javascript; charset=utf-8',
)
),
);
unset($_SERVER['HTTP_IF_NONE_MATCH']);
unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
unset($_SERVER['HTTP_IF_NONE_MATCH'], $_SERVER['HTTP_IF_MODIFIED_SINCE']);
$env = new Minify_Env(array(
'server' => $_SERVER,
@@ -102,7 +104,7 @@ class MinifyTest extends TestCase
$this->assertEquals($expected, $output, 'JS and Expires');
// test for Issue 73
$expected = ";function h(){}";
$expected = ';function h(){}';
$output = $minify->serve($controller, array(
'files' => array(
$minifyTestPath . '/issue73_1.js',
@@ -153,8 +155,10 @@ class MinifyTest extends TestCase
));
$output = $output['content'];
$this->assertFalse(strpos($output, $defaultOptions['importWarning']),
'Issue 89 : don\'t warn about valid imports');
$this->assertFalse(
strpos($output, $defaultOptions['importWarning']),
'Issue 89 : don\'t warn about valid imports'
);
// Test Issue 132
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
@@ -164,8 +168,11 @@ class MinifyTest extends TestCase
'encodeOutput' => false,
));
$this->assertEquals(77, $output['headers']['Content-Length'],
'Issue 132 : mbstring.func_overload shouldn\'t cause incorrect Content-Length');
$this->assertEquals(
77,
$output['headers']['Content-Length'],
'Issue 132 : mbstring.func_overload shouldn\'t cause incorrect Content-Length'
);
}
// Test minifying CSS and responding with Etag/Last-Modified
@@ -186,7 +193,7 @@ class MinifyTest extends TestCase
'Cache-Control' => 'max-age=0',
'Content-Length' => $this->countBytes($expectedContent),
'Content-Type' => 'text/css; charset=utf-8',
)
),
);
$env = new Minify_Env(array(

View File

@@ -5,6 +5,9 @@ namespace Minify\Test;
use Exception;
use Minify_YUICompressor;
/**
* @internal
*/
class MinifyYuiCSSTest extends TestCase
{
public static function setupBeforeClass()
@@ -37,6 +40,7 @@ class MinifyYuiCSSTest extends TestCase
// fails with java.lang.StackOverflowError as of Yui 2.4.6
// unfortunately error output is not caught from yui, so have to guess
$e = null;
try {
Minify_YUICompressor::minifyCss($src);
// if reached here, then Correctly handles input which caused stack overflow in 2.4.6
@@ -54,8 +58,9 @@ class MinifyYuiCSSTest extends TestCase
protected function assertHasJar()
{
$this->assertNotEmpty(Minify_YUICompressor::$jarFile);
try {
$this->assertFileExists(Minify_YUICompressor::$jarFile, "Have YUI yuicompressor.jar");
$this->assertFileExists(Minify_YUICompressor::$jarFile, 'Have YUI yuicompressor.jar');
} catch (Exception $e) {
$this->markTestSkipped($e->getMessage());
}

View File

@@ -4,6 +4,9 @@ namespace Minify\Test;
use Minify_HTML_Helper;
/**
* @internal
*/
class ScssSourceTest extends TestCase
{
public function setUp()
@@ -13,14 +16,14 @@ class ScssSourceTest extends TestCase
}
/**
* @link https://github.com/mrclay/minify/issues/500
* @see https://github.com/mrclay/minify/issues/500
*/
public function testTimestamp()
{
$baseDir = self::$test_files;
$mainLess = "$baseDir/main.scss";
$includedLess = "$baseDir/_included.scss";
$mainLess = "${baseDir}/main.scss";
$includedLess = "${baseDir}/_included.scss";
// touch timestamp with 1s difference
touch($mainLess);
@@ -33,7 +36,7 @@ class ScssSourceTest extends TestCase
$max = max($mtime1, $mtime2);
$options = array(
'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php",
'groupsConfigFile' => "${baseDir}/htmlHelper_groupsConfig.php",
);
$res = Minify_HTML_Helper::getUri('scss', $options);

View File

@@ -8,6 +8,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
{
/** @var string */
protected static $document_root;
/** @var string */
protected static $test_files;
@@ -21,6 +22,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
* Get number of bytes in a string regardless of mbstring.func_overload
*
* @param string $str
*
* @return int
*/
protected function countBytes($str)
@@ -39,17 +41,17 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
*/
protected function assertTestCache(Minify_CacheInterface $cache, $id, $data)
{
$this->assertTrue($cache->store($id, $data), "$id store");
$this->assertEquals($cache->getSize($id), $this->countBytes($data), "$id getSize");
$this->assertTrue($cache->isValid($id, $_SERVER['REQUEST_TIME'] - 10), "$id isValid");
$this->assertTrue($cache->store($id, $data), "${id} store");
$this->assertEquals($cache->getSize($id), $this->countBytes($data), "${id} getSize");
$this->assertTrue($cache->isValid($id, $_SERVER['REQUEST_TIME'] - 10), "${id} isValid");
ob_start();
$cache->display($id);
$displayed = ob_get_contents();
ob_end_clean();
$this->assertSame($data, $displayed, "$id display");
$this->assertEquals($data, $cache->fetch($id), "$id fetch");
$this->assertSame($data, $displayed, "${id} display");
$this->assertEquals($data, $cache->fetch($id), "${id} fetch");
}
/**
@@ -57,6 +59,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
* As a side effect calls trim() to fight against different Editors that insert or strip final newline.
*
* @param string $filename
*
* @return string
*/
protected function getDataFile($filename)

View File

@@ -6,10 +6,7 @@
* You must make sure that functions are not redefined, and if your use custom sources,
* you must require_once __DIR__ . '/lib/Minify/Source.php' so that
* class is available.
*
* @package Minify
*/
require __DIR__ . '/bootstrap.php';
/*
@@ -40,7 +37,6 @@ function Minify_getUri($keyOrFiles, $opts = array())
return Minify_HTML_Helper::getUri($keyOrFiles, $opts);
}
/**
* Get the last modification time of several source js/css files. If you're
* caching the output of Minify_getUri(), you might want to know if one of the
@@ -49,7 +45,9 @@ function Minify_getUri($keyOrFiles, $opts = array())
* Since this makes a bunch of stat() calls, you might not want to check this
* on every request.
*
* @param array $keysAndFiles group keys and/or file paths/URIs.
* @param array $keysAndFiles group keys and/or file paths/URIs
* @param mixed|null $groupsConfigFile
*
* @return int latest modification time of all given keys/files
*/
function Minify_mtime($keysAndFiles, $groupsConfigFile = null)
@@ -61,8 +59,8 @@ function Minify_mtime($keysAndFiles, $groupsConfigFile = null)
$sources = array();
foreach ($keysAndFiles as $keyOrFile) {
if (is_object($keyOrFile)
|| 0 === strpos($keyOrFile, '/')
|| 1 === strpos($keyOrFile, ':\\')) {
|| strpos($keyOrFile, '/') === 0
|| strpos($keyOrFile, ':\\') === 1) {
// a file/source obj
$sources[] = $keyOrFile;
} else {
@@ -74,5 +72,6 @@ function Minify_mtime($keysAndFiles, $groupsConfigFile = null)
}
}
}
return Minify_HTML_Helper::getLastModified($sources);
}