1
0
mirror of https://github.com/mrclay/minify.git synced 2025-08-30 00:59:48 +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

@@ -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
@@ -116,7 +110,7 @@ class HTTP_ConditionalGet
// backwards compatibility (can be removed later)
if (isset($spec['setExpires'])
&& is_numeric($spec['setExpires'])
&& ! isset($spec['maxAge'])) {
&& !isset($spec['maxAge'])) {
$spec['maxAge'] = $spec['setExpires'] - $_SERVER['REQUEST_TIME'];
}
if (isset($spec['maxAge'])) {
@@ -128,9 +122,9 @@ class HTTP_ConditionalGet
$etagAppend = '';
if (isset($spec['encoding'])) {
$this->_stripEtag = true;
if ('' !== $spec['encoding']) {
if ($spec['encoding'] !== '') {
$this->_headers['Vary'] = 'Accept-Encoding';
if (0 === strpos($spec['encoding'], 'x-')) {
if (strpos($spec['encoding'], 'x-') === 0) {
$spec['encoding'] = substr($spec['encoding'], 2);
}
$etagAppend = ';' . substr($spec['encoding'], 0, 2);
@@ -227,19 +221,17 @@ class HTTP_ConditionalGet
*
* @param int $lastModifiedTime if given, both ETag AND Last-Modified headers
* will be sent with content. This is recommended.
*
* @param bool $isPublic (default false) if true, the Cache-Control header
* will contain "public", allowing proxies to cache the content. Otherwise
* "private" will be sent, allowing only browser caching.
*
* @param array $options (default empty) additional options for constructor
*/
public static function check($lastModifiedTime = null, $isPublic = false, $options = array())
{
if (null !== $lastModifiedTime) {
$options['lastModifiedTime'] = (int)$lastModifiedTime;
if ($lastModifiedTime !== null) {
$options['lastModifiedTime'] = (int) $lastModifiedTime;
}
$options['isPublic'] = (bool)$isPublic;
$options['isPublic'] = (bool) $isPublic;
$cg = new HTTP_ConditionalGet($options);
$cg->sendHeaders();
if ($cg->cacheIsValid) {
@@ -264,13 +256,15 @@ class HTTP_ConditionalGet
}
protected $_headers = array();
protected $_lmTime = null;
protected $_etag = null;
protected $_lmTime;
protected $_etag;
protected $_stripEtag = false;
/**
* @param string $hash
*
* @param string $scope
*/
protected function _setEtag($hash, $scope)
@@ -284,7 +278,7 @@ class HTTP_ConditionalGet
*/
protected function _setLastModified($time)
{
$this->_lmTime = (int)$time;
$this->_lmTime = (int) $time;
$this->_headers['Last-Modified'] = self::gmtDate($time);
}
@@ -295,7 +289,7 @@ class HTTP_ConditionalGet
*/
protected function _isCacheValid()
{
if (null === $this->_etag) {
if ($this->_etag === null) {
// lmTime is copied to ETag, so this condition implies that the
// server sent neither ETag nor Last-Modified, so the client can't
// possibly has a valid cache.

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?
*
@@ -89,11 +82,11 @@ class HTTP_Encoder
{
$this->_useMbStrlen = (function_exists('mb_strlen')
&& (ini_get('mbstring.func_overload') !== '')
&& ((int)ini_get('mbstring.func_overload') & 2));
&& ((int) ini_get('mbstring.func_overload') & 2));
$this->_content = $spec['content'];
$this->_headers['Content-Length'] = $this->_useMbStrlen
? (string)mb_strlen($this->_content, '8bit')
: (string)strlen($this->_content);
? (string) mb_strlen($this->_content, '8bit')
: (string) strlen($this->_content);
if (isset($spec['type'])) {
$this->_headers['Content-Type'] = $spec['type'];
}
@@ -180,7 +173,6 @@ class HTTP_Encoder
* rarely sent by servers, so client support could be buggier.
*
* @param bool $allowCompress allow the older compress encoding
*
* @param bool $allowDeflate allow the more recent deflate encoding
*
* @return array two values, 1st is the actual encoding method, 2nd is the
@@ -191,40 +183,44 @@ class HTTP_Encoder
{
// @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
if (! isset($_SERVER['HTTP_ACCEPT_ENCODING'])
if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])
|| self::isBuggyIe()) {
return array('', '');
}
$ae = $_SERVER['HTTP_ACCEPT_ENCODING'];
// gzip checks (quick)
if (0 === strpos($ae, 'gzip,') // most browsers
|| 0 === strpos($ae, 'deflate, gzip,') // opera
if (strpos($ae, 'gzip,') === 0 // most browsers
|| strpos($ae, 'deflate, gzip,') === 0 // opera
) {
return array('gzip', 'gzip');
}
// gzip checks (slow)
if (preg_match(
'@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
,$ae
,$m)) {
'@(?:^|,)\\s*((?:x-)?gzip)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae,
$m
)) {
return array('gzip', $m[1]);
}
if ($allowDeflate) {
// deflate checks
$aeRev = strrev($ae);
if (0 === strpos($aeRev, 'etalfed ,') // ie, webkit
|| 0 === strpos($aeRev, 'etalfed,') // gecko
|| 0 === strpos($ae, 'deflate,') // opera
if (strpos($aeRev, 'etalfed ,') === 0 // ie, webkit
|| strpos($aeRev, 'etalfed,') === 0 // gecko
|| strpos($ae, 'deflate,') === 0 // opera
// slow parsing
|| preg_match(
'@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@', $ae)) {
'@(?:^|,)\\s*deflate\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae
)) {
return array('deflate', 'deflate');
}
}
if ($allowCompress && preg_match(
'@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@'
,$ae
,$m)) {
'@(?:^|,)\\s*((?:x-)?compress)\\s*(?:$|,|;\\s*q=(?:0\\.|1))@',
$ae,
$m
)) {
return array('compress', $m[1]);
}
@@ -250,13 +246,13 @@ class HTTP_Encoder
*/
public function encode($compressionLevel = null)
{
if (! self::isBuggyIe()) {
if (!self::isBuggyIe()) {
$this->_headers['Vary'] = 'Accept-Encoding';
}
if (null === $compressionLevel) {
if ($compressionLevel === null) {
$compressionLevel = self::$compressionLevel;
}
if ('' === $this->_encodeMethod[0]
if ($this->_encodeMethod[0] === ''
|| ($compressionLevel == 0)
|| !extension_loaded('zlib')) {
return false;
@@ -268,12 +264,12 @@ class HTTP_Encoder
} else {
$encoded = gzcompress($this->_content, $compressionLevel);
}
if (false === $encoded) {
if ($encoded === false) {
return false;
}
$this->_headers['Content-Length'] = $this->_useMbStrlen
? (string)mb_strlen($encoded, '8bit')
: (string)strlen($encoded);
? (string) mb_strlen($encoded, '8bit')
: (string) strlen($encoded);
$this->_headers['Content-Encoding'] = $this->_encodeMethod[1];
$this->_content = $encoded;
@@ -286,7 +282,6 @@ class HTTP_Encoder
* This is a convenience method for common use of the class
*
* @param string $content
*
* @param int $compressionLevel given to zlib functions. If not given, the
* class default will be used.
*
@@ -294,7 +289,7 @@ class HTTP_Encoder
*/
public static function output($content, $compressionLevel = null)
{
if (null === $compressionLevel) {
if ($compressionLevel === null) {
$compressionLevel = self::$compressionLevel;
}
$he = new HTTP_Encoder(array('content' => $content));
@@ -316,20 +311,23 @@ class HTTP_Encoder
}
$ua = $_SERVER['HTTP_USER_AGENT'];
// quick escape for non-IEs
if (0 !== strpos($ua, 'Mozilla/4.0 (compatible; MSIE ')
|| false !== strpos($ua, 'Opera')) {
if (strpos($ua, 'Mozilla/4.0 (compatible; MSIE ') !== 0
|| strpos($ua, 'Opera') !== false) {
return false;
}
// no regex = faaast
$version = (float)substr($ua, 30);
$version = (float) substr($ua, 30);
return self::$encodeToIe6
? ($version < 6 || ($version == 6 && false === strpos($ua, 'SV1')))
? ($version < 6 || ($version == 6 && strpos($ua, 'SV1') === false))
: ($version < 7);
}
protected $_content = '';
protected $_headers = array();
protected $_encodeMethod = array('', '');
protected $_useMbStrlen = false;
}

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';
/**
@@ -99,30 +97,30 @@ class Minify
public function getDefaultOptions()
{
return array(
'isPublic' => true,
'isPublic' => true,
'encodeOutput' => function_exists('gzdeflate'),
'encodeMethod' => null, // determine later
'encodeLevel' => 9,
'encodeLevel' => 9,
'minifiers' => array(
Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
),
'minifierOptions' => array(), // no minifier options
'contentTypeCharset' => 'utf-8',
'maxAge' => 1800, // 30 minutes
'rewriteCssUris' => true,
'bubbleCssImports' => false,
'quiet' => false, // serve() will send headers and output
'debug' => false,
'concatOnly' => false,
'maxAge' => 1800, // 30 minutes
'rewriteCssUris' => true,
'bubbleCssImports' => false,
'quiet' => false, // serve() will send headers and output
'debug' => false,
'concatOnly' => false,
// if you override these, the response codes MUST be directly after
// the first space.
'badRequestHeader' => 'HTTP/1.0 400 Bad Request',
'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
'errorHeader' => 'HTTP/1.0 500 Internal Server Error',
// callback function to see/modify content of all sources
'postprocessor' => null,
@@ -135,7 +133,7 @@ class Minify
* appear too late in the combined stylesheet. If found, serve() will prepend
* the output with this warning.
*/
'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n"
'importWarning' => "/* See https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md#imports-can-appear-in-invalid-locations-in-combined-css-files */\n",
);
}
@@ -176,6 +174,7 @@ class Minify
*
* 'debug' : set to true to minify all sources with the 'Lines' controller, which
* eases the debugging of combined files. This also prevents 304 responses.
*
* @see Minify_Lines::minify()
*
* 'concatOnly' : set to true to disable minification and simply concatenate the files.
@@ -211,14 +210,13 @@ class Minify
* Any controller options are documented in that controller's createConfiguration() method.
*
* @param Minify_ControllerInterface $controller instance of subclass of Minify_Controller_Base
*
* @param array $options controller/serve options
*
* @return null|array if the 'quiet' option is set to true, an array
* with keys "success" (bool), "statusCode" (int), "content" (string), and
* "headers" (array).
*
* @throws Exception
*
* @return array|null if the 'quiet' option is set to true, an array
* with keys "success" (bool), "statusCode" (int), "content" (string), and
* "headers" (array)
*/
public function serve(Minify_ControllerInterface $controller, $options = array())
{
@@ -239,16 +237,16 @@ class Minify
// check request validity
if (!$this->sources) {
// invalid request!
if (! $this->options['quiet']) {
if (!$this->options['quiet']) {
$this->errorExit($this->options['badRequestHeader'], self::URL_DEBUG);
} else {
list(,$statusCode) = explode(' ', $this->options['badRequestHeader']);
list(, $statusCode) = explode(' ', $this->options['badRequestHeader']);
return array(
'success' => false,
'statusCode' => (int)$statusCode,
'content' => '',
'headers' => array(),
'success' => false,
'statusCode' => (int) $statusCode,
'content' => '',
'headers' => array(),
);
}
}
@@ -273,7 +271,7 @@ class Minify
// getAcceptedEncoding(false, false) leaves out compress and deflate as options.
$list = HTTP_Encoder::getAcceptedEncoding(false, false);
list($this->options['encodeMethod'], $contentEncoding) = $list;
$sendVary = ! HTTP_Encoder::isBuggyIe();
$sendVary = !HTTP_Encoder::isBuggyIe();
}
} else {
$this->options['encodeMethod'] = ''; // identity (no encoding)
@@ -282,8 +280,8 @@ class Minify
// check client cache
$cgOptions = array(
'lastModifiedTime' => $this->options['lastModifiedTime'],
'isPublic' => $this->options['isPublic'],
'encoding' => $this->options['encodeMethod'],
'isPublic' => $this->options['isPublic'],
'encoding' => $this->options['encodeMethod'],
);
if ($this->options['maxAge'] > 0) {
@@ -295,17 +293,17 @@ class Minify
$cg = new HTTP_ConditionalGet($cgOptions);
if ($cg->cacheIsValid) {
// client's cache is valid
if (! $this->options['quiet']) {
if (!$this->options['quiet']) {
$cg->sendHeaders();
return;
}
return array(
'success' => true,
'success' => true,
'statusCode' => 304,
'content' => '',
'headers' => $cg->getHeaders(),
'content' => '',
'headers' => $cg->getHeaders(),
);
}
@@ -332,7 +330,7 @@ class Minify
}
// check server cache
if (! $this->options['debug']) {
if (!$this->options['debug']) {
// using cache
// the goal is to use only the cache methods to sniff the length and
// output the content, as they do not require ever loading the file into
@@ -350,9 +348,10 @@ class Minify
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
if (! $this->options['quiet']) {
if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
$this->cache->store($cacheId, $content);
@@ -363,17 +362,19 @@ class Minify
} else {
// no cache
$cacheIsReady = false;
try {
$content = $this->combineMinify();
} catch (Exception $e) {
$this->logger && $this->logger->critical($e->getMessage());
if (! $this->options['quiet']) {
if (!$this->options['quiet']) {
$this->errorExit($this->options['errorHeader'], self::URL_DEBUG);
}
throw $e;
}
}
if (! $cacheIsReady && $this->options['encodeMethod']) {
if (!$cacheIsReady && $this->options['encodeMethod']) {
// still need to encode
$content = gzencode($content, $this->options['encodeLevel']);
}
@@ -382,7 +383,7 @@ class Minify
if ($cacheIsReady) {
$headers['Content-Length'] = $cacheContentLength;
} else {
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
$headers['Content-Length'] = mb_strlen($content, '8bit');
} else {
$headers['Content-Length'] = strlen($content);
@@ -401,7 +402,7 @@ class Minify
$headers['Vary'] = 'Accept-Encoding';
}
if (! $this->options['quiet']) {
if (!$this->options['quiet']) {
// output headers & content
foreach ($headers as $name => $val) {
header($name . ': ' . $val);
@@ -413,10 +414,10 @@ class Minify
}
} else {
return array(
'success' => true,
'success' => true,
'statusCode' => 200,
'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
'headers' => $headers,
'content' => $cacheIsReady ? $this->cache->fetch($fullCacheId) : $content,
'headers' => $headers,
);
}
}
@@ -427,8 +428,7 @@ class Minify
* No internal caching will be used and the content will not be HTTP encoded.
*
* @param array $sources array of filepaths and/or Minify_Source objects
*
* @param array $options (optional) array of options for serve.
* @param array $options (optional) array of options for serve
*
* @return string
*/
@@ -444,9 +444,9 @@ class Minify
$controller = new Minify_Controller_Files($env, $sourceFactory, $this->logger);
$options = array_merge($options, array(
'files' => (array)$sources,
'quiet' => true,
'encodeMethod' => '',
'files' => (array) $sources,
'quiet' => true,
'encodeMethod' => '',
'lastModifiedTime' => 0,
));
$out = $this->serve($controller, $options);
@@ -464,24 +464,24 @@ class Minify
* @param string $msgHtml HTML message for the client
*
* @return void
*
* @internal This is not part of the public API and is subject to change
* @access private
*/
public function errorExit($header, $url = '', $msgHtml = '')
{
$url = htmlspecialchars($url, ENT_QUOTES);
list(,$h1) = explode(' ', $header, 2);
list(, $h1) = explode(' ', $header, 2);
$h1 = htmlspecialchars($h1);
// FastCGI environments require 3rd arg to header() to be set
list(, $code) = explode(' ', $header, 3);
header($header, true, $code);
header('Content-Type: text/html; charset=utf-8');
echo "<h1>$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()
{
@@ -590,10 +591,11 @@ class Minify
// do we need to process our group right now?
if ($i > 0 // yes, we have at least the first group populated
&& (
! $source // yes, we ran out of sources
!$source // yes, we ran out of sources
|| $type === self::TYPE_CSS // yes, to process CSS individually (avoiding PCRE bugs/limits)
|| $minifier !== $lastMinifier // yes, minifier changed
|| $options !== $lastOptions)) { // yes, options changed
|| $options !== $lastOptions
)) { // yes, options changed
// minify previous sources with last settings
$imploded = implode($implodeSeparator, $groupToProcessTogether);
$groupToProcessTogether = array();
@@ -601,7 +603,7 @@ class Minify
try {
$content[] = call_user_func($lastMinifier, $imploded, $lastOptions);
} catch (Exception $e) {
throw new Exception("Exception in minifier: " . $e->getMessage());
throw new Exception('Exception in minifier: ' . $e->getMessage());
}
} else {
$content[] = $imploded;
@@ -618,7 +620,7 @@ class Minify
$content = implode($implodeSeparator, $content);
if ($type === self::TYPE_CSS && false !== strpos($content, '@import')) {
if ($type === self::TYPE_CSS && strpos($content, '@import') !== false) {
$content = $this->handleCssImports($content);
}
@@ -671,12 +673,11 @@ class Minify
if ($this->options['bubbleCssImports']) {
// bubble CSS imports
preg_match_all('/@import.*?;/', $css, $imports);
$css = implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
return $css;
return implode('', $imports[0]) . preg_replace('/@import.*?;/', '', $css);
}
if ('' === $this->options['importWarning']) {
if ($this->options['importWarning'] === '') {
return $css;
}
@@ -684,8 +685,8 @@ class Minify
$noCommentCss = preg_replace('@/\\*[\\s\\S]*?\\*/@', '', $css);
$lastImportPos = strrpos($noCommentCss, '@import');
$firstBlockPos = strpos($noCommentCss, '{');
if (false !== $lastImportPos
&& false !== $firstBlockPos
if ($lastImportPos !== false
&& $firstBlockPos !== false
&& $firstBlockPos < $lastImportPos
) {
// { appears before @import : prepend warning
@@ -738,7 +739,7 @@ class Minify
}
if (empty($options['contentType'])) {
if (null === $type) {
if ($type === null) {
$type = 'text/plain';
}
$options['contentType'] = $type;

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,16 +75,15 @@ class Minify_Build
* Create a build object
*
* @param array $sources array of Minify_Source objects and/or file paths
*
*/
public function __construct($sources)
{
$max = 0;
foreach ((array)$sources as $source) {
foreach ((array) $sources as $source) {
if ($source instanceof Minify_Source) {
$max = max($max, $source->getLastModified());
} elseif (is_string($source)) {
if (0 === strpos($source, '//')) {
if (strpos($source, '//') === 0) {
$source = $_SERVER['DOCUMENT_ROOT'] . substr($source, 1);
}
if (is_file($source)) {

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
@@ -59,13 +52,13 @@ class Minify_CSS
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'preserveComments' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'compress' => true,
'removeCharsets' => true,
'preserveComments' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
@@ -73,7 +66,7 @@ class Minify_CSS
}
if ($options['compress']) {
if (! $options['preserveComments']) {
if (!$options['preserveComments']) {
$css = Minify_CSS_Compressor::process($css, $options);
} else {
$processor = array('Minify_CSS_Compressor', 'process');
@@ -81,7 +74,7 @@ class Minify_CSS
}
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
if (!$options['currentDir'] && !$options['prependRelativePath']) {
return $css;
}

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
*/
@@ -97,7 +88,7 @@ class Minify_CSS_UriRewriter
$css = self::_trimUrls($css);
$css = self::_owlifySvgPaths($css);
// append
$pattern = '/@import\\s+([\'"])(.*?)[\'"]/';
$css = preg_replace_callback($pattern, array(self::$className, '_processUriCB'), $css);
@@ -134,11 +125,8 @@ class Minify_CSS_UriRewriter
* </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
@@ -53,12 +46,12 @@ class Minify_CSSmin
public static function minify($css, $options = array())
{
$options = array_merge(array(
'compress' => true,
'removeCharsets' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'compress' => true,
'removeCharsets' => true,
'currentDir' => null,
'docRoot' => $_SERVER['DOCUMENT_ROOT'],
'prependRelativePath' => null,
'symlinks' => array(),
'symlinks' => array(),
), $options);
if ($options['removeCharsets']) {
@@ -68,21 +61,21 @@ class Minify_CSSmin
$obj = new CSSmin();
$css = $obj->run($css);
}
if (! $options['currentDir'] && ! $options['prependRelativePath']) {
if (!$options['currentDir'] && !$options['prependRelativePath']) {
return $css;
}
if ($options['currentDir']) {
return Minify_CSS_UriRewriter::rewrite(
$css
,$options['currentDir']
,$options['docRoot']
,$options['symlinks']
$css,
$options['currentDir'],
$options['docRoot'],
$options['symlinks']
);
}
return Minify_CSS_UriRewriter::prepend(
$css
,$options['prependRelativePath']
$css,
$options['prependRelativePath']
);
}
}

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
@@ -55,29 +49,28 @@ class Minify_Cache_APC implements Minify_CacheInterface
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
if (!$this->_fetch($id)) {
return false;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return strlen($this->_data);
}
return strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -102,12 +95,14 @@ class Minify_Cache_APC implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
private $_exp = null;
private $_exp;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
private $_lm;
private $_data;
private $_id;
/**
* Fetch data and timestamp from apc, store in instance
@@ -122,7 +117,7 @@ class Minify_Cache_APC implements Minify_CacheInterface
return true;
}
$ret = apc_fetch($id);
if (false === $ret) {
if ($ret === false) {
$this->_id = null;
return false;

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
*/
@@ -31,7 +28,7 @@ class Minify_Cache_File implements Minify_CacheInterface
*/
public function __construct($path = '', $fileLocking = false, LoggerInterface $logger = null)
{
if (! $path) {
if (!$path) {
$path = sys_get_temp_dir();
}
$this->locking = $fileLocking;
@@ -47,7 +44,6 @@ class Minify_Cache_File implements Minify_CacheInterface
* Write data to cache.
*
* @param string $id cache id (e.g. a filename)
*
* @param string $data
*
* @return bool success
@@ -57,14 +53,14 @@ class Minify_Cache_File implements Minify_CacheInterface
$flag = $this->locking ? LOCK_EX : null;
$file = $this->path . '/' . $id;
if (! @file_put_contents($file, $data, $flag)) {
$this->logger->warning("Minify_Cache_File: Write failed to '$file'");
if (!@file_put_contents($file, $data, $flag)) {
$this->logger->warning("Minify_Cache_File: Write failed to '${file}'");
}
// write control
if ($data !== $this->fetch($id)) {
@unlink($file);
$this->logger->warning("Minify_Cache_File: Post-write read failed for '$file'");
$this->logger->warning("Minify_Cache_File: Post-write read failed for '${file}'");
return false;
}
@@ -88,7 +84,6 @@ class Minify_Cache_File implements Minify_CacheInterface
* Does a valid cache entry exist?
*
* @param string $id cache id (e.g. a filename)
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
@@ -97,7 +92,7 @@ class Minify_Cache_File implements Minify_CacheInterface
{
$file = $this->path . '/' . $id;
return (is_file($file) && (filemtime($file) >= $srcMtime));
return is_file($file) && (filemtime($file) >= $srcMtime);
}
/**
@@ -160,6 +155,7 @@ class Minify_Cache_File implements Minify_CacheInterface
* Get a usable temp directory
*
* @return string
*
* @deprecated
*/
public static function tmp()
@@ -171,8 +167,11 @@ class Minify_Cache_File implements Minify_CacheInterface
/**
* Send message to the Minify logger
*
* @param string $msg
*
* @return null
*
* @deprecated Use $this->logger
*/
protected function _log($msg)

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
@@ -58,29 +54,28 @@ class Minify_Cache_Memcache implements Minify_CacheInterface
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
if (!$this->_fetch($id)) {
return false;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return strlen($this->_data);
}
return strlen($this->_data);
}
/**
* Does a valid cache entry exist?
*
* @param string $id cache id
*
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -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
{
@@ -64,4 +62,4 @@ class Minify_Cache_Null implements Minify_CacheInterface
public function fetch($id)
{
}
}
}

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
@@ -136,4 +133,4 @@ class Minify_Cache_WinCache implements Minify_CacheInterface
return true;
}
}
}

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,19 +45,20 @@ class Minify_Cache_XCache implements Minify_CacheInterface
* Get the size of a cache entry
*
* @param string $id cache id
*
* @return int size in bytes
*/
public function getSize($id)
{
if (! $this->_fetch($id)) {
if (!$this->_fetch($id)) {
return false;
}
if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
if (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2)) {
return mb_strlen($this->_data, '8bit');
} else {
return strlen($this->_data);
}
return strlen($this->_data);
}
/**
@@ -68,11 +66,12 @@ class Minify_Cache_XCache implements Minify_CacheInterface
*
* @param string $id cache id
* @param int $srcMtime mtime of the original source file(s)
*
* @return bool exists
*/
public function isValid($id, $srcMtime)
{
return ($this->_fetch($id) && ($this->_lm >= $srcMtime));
return $this->_fetch($id) && ($this->_lm >= $srcMtime);
}
/**
@@ -89,6 +88,7 @@ class Minify_Cache_XCache implements Minify_CacheInterface
* Fetch the cached content
*
* @param string $id cache id
*
* @return string
*/
public function fetch($id)
@@ -96,17 +96,20 @@ class Minify_Cache_XCache implements Minify_CacheInterface
return $this->_fetch($id) ? $this->_data : '';
}
private $_exp = null;
private $_exp;
// cache of most recently fetched id
private $_lm = null;
private $_data = null;
private $_id = null;
private $_lm;
private $_data;
private $_id;
/**
* Fetch data and timestamp from xcache, store in instance
*
* @param string $id
*
* @return bool success
*/
private function _fetch($id)
@@ -116,7 +119,7 @@ class Minify_Cache_XCache implements Minify_CacheInterface
}
$ret = xcache_get($id);
if (false === $ret) {
if ($ret === false) {
$this->_id = null;
return false;

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
{
@@ -60,9 +55,9 @@ class Minify_ClosureCompiler
* @var array
*/
public static $defaultOptions = array(
'charset' => 'utf-8',
'charset' => 'utf-8',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'warning_level' => 'QUIET',
'warning_level' => 'QUIET',
);
/**
@@ -70,9 +65,12 @@ class Minify_ClosureCompiler
*
* @param string $js
* @param array $options (verbose is ignored)
*
* @see https://code.google.com/p/closure-compiler/source/browse/trunk/README
* @return string
*
* @throws Minify_ClosureCompiler_Exception
*
* @return string
*/
public static function minify($js, $options = array())
{
@@ -86,17 +84,21 @@ class Minify_ClosureCompiler
*
* @param string $js
* @param array $options
* @return string
*
* @throws Exception
* @throws Minify_ClosureCompiler_Exception
*
* @return string
*/
public function process($js, $options)
{
$tmpFile = $this->dumpFile(self::$tempDir, $js);
try {
$result = $this->compile($tmpFile, $options);
} catch (Exception $e) {
unlink($tmpFile);
throw $e;
}
unlink($tmpFile);
@@ -107,8 +109,10 @@ class Minify_ClosureCompiler
/**
* @param string $tmpFile
* @param array $options
* @return string
*
* @throws Minify_ClosureCompiler_Exception
*
* @return string
*/
protected function compile($tmpFile, $options)
{
@@ -120,6 +124,7 @@ class Minify_ClosureCompiler
/**
* @param array $userOptions
* @param string $tmpFile
*
* @return string
*/
protected function getCommand($userOptions, $tmpFile)
@@ -133,23 +138,24 @@ class Minify_ClosureCompiler
}
/**
* @return array
* @throws Minify_ClosureCompiler_Exception
*
* @return array
*/
protected function getCompilerCommandLine()
{
$this->checkJar(self::$jarFile);
$server = array(
return array(
self::$javaExecutable,
'-jar',
escapeshellarg(self::$jarFile)
escapeshellarg(self::$jarFile),
);
return $server;
}
/**
* @param array $userOptions
*
* @return array
*/
protected function getOptionsCommandLine($userOptions)
@@ -170,6 +176,7 @@ class Minify_ClosureCompiler
/**
* @param string $jarFile
*
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkJar($jarFile)
@@ -184,6 +191,7 @@ class Minify_ClosureCompiler
/**
* @param string $tempDir
*
* @throws Minify_ClosureCompiler_Exception
*/
protected function checkTempdir($tempDir)
@@ -201,8 +209,10 @@ class Minify_ClosureCompiler
*
* @param string $dir
* @param string $content
* @return string
*
* @throws Minify_ClosureCompiler_Exception
*
* @return string
*/
protected function dumpFile($dir, $content)
{
@@ -221,14 +231,16 @@ class Minify_ClosureCompiler
*
* @param string $command
* @param array $expectedCodes
* @return mixed
*
* @throws Minify_ClosureCompiler_Exception
*
* @return mixed
*/
protected function shell($command, $expectedCodes = array(0))
{
exec($command, $output, $result_code);
if (!in_array($result_code, $expectedCodes)) {
throw new Minify_ClosureCompiler_Exception("Unpexpected return code: $result_code");
throw new Minify_ClosureCompiler_Exception("Unpexpected return code: ${result_code}");
}
return $output;

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:
@@ -49,8 +43,8 @@ class Minify_Controller_Files extends Minify_Controller_Base
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
} elseif (!is_array($files)) {
$files = (array) $files;
}
unset($options['files']);
@@ -68,4 +62,3 @@ class Minify_Controller_Files extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources);
}
}

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);
}
@@ -64,8 +59,8 @@ class Minify_Controller_Groups extends Minify_Controller_Files
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
} elseif (!is_array($files)) {
$files = (array) $files;
}
$options['files'] = $files;
@@ -73,4 +68,3 @@ class Minify_Controller_Groups extends Minify_Controller_Files
return parent::createConfiguration($options);
}
}

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
*
@@ -26,15 +21,15 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$get = $this->env->get();
foreach (array('g', 'b', 'f') as $key) {
if (isset($get[$key])) {
$get[$key] = str_replace("\x00", '', (string)$get[$key]);
$get[$key] = str_replace("\x00", '', (string) $get[$key]);
}
}
// filter controller options
$defaults = array(
'groupsOnly' => false,
'groups' => array(),
'symlinks' => array(),
'groups' => array(),
'symlinks' => array(),
);
$minApp = isset($options['minApp']) ? $options['minApp'] : array();
$localOptions = array_merge($defaults, $minApp);
@@ -44,7 +39,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// normalize $symlinks in order to map to target
$symlinks = array();
foreach ($localOptions['symlinks'] as $link => $target) {
if (0 === strpos($link, '//')) {
if (strpos($link, '//') === 0) {
$link = rtrim(substr($link, 1), '/') . '/';
$target = rtrim($target, '/\\');
$symlinks[$link] = $target;
@@ -60,12 +55,12 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$selectionId .= 'g=' . $get['g'];
$keys = explode(',', $get['g']);
if ($keys != array_unique($keys)) {
$this->logger->info("Duplicate group key found.");
$this->logger->info('Duplicate group key found.');
return new Minify_ServeConfiguration($options);
}
foreach ($keys as $key) {
if (! isset($localOptions['groups'][$key])) {
if (!isset($localOptions['groups'][$key])) {
$this->logger->info("A group configuration for \"{$key}\" was not found");
return new Minify_ServeConfiguration($options);
@@ -74,8 +69,8 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// if $files is a single object, casting will break it
if (is_object($files)) {
$files = array($files);
} elseif (! is_array($files)) {
$files = (array)$files;
} elseif (!is_array($files)) {
$files = (array) $files;
}
foreach ($files as $file) {
try {
@@ -83,20 +78,20 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$sources[] = $source;
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
if (null === $firstMissing) {
if ($firstMissing === null) {
$firstMissing = basename($file);
continue;
} else {
$secondMissing = basename($file);
$this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing'");
return new Minify_ServeConfiguration($options);
continue;
}
$secondMissing = basename($file);
$this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}'");
return new Minify_ServeConfiguration($options);
}
}
}
}
if (! $localOptions['groupsOnly'] && isset($get['f'])) {
if (!$localOptions['groupsOnly'] && isset($get['f'])) {
// try user files
// The following restrictions are to limit the URLs that minify will
// respond to.
@@ -115,7 +110,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$ext = ".{$m[1]}";
$files = explode(',', $get['f']);
if ($files != array_unique($files)) {
$this->logger->info("Duplicate files were specified");
$this->logger->info('Duplicate files were specified');
return new Minify_ServeConfiguration($options);
}
@@ -123,7 +118,7 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
if (isset($get['b'])) {
// check for validity
$isValidBase = preg_match('@^[^/]+(?:/[^/]+)*$@', $get['b']);
$hasDots = false !== strpos($get['b'], '..');
$hasDots = strpos($get['b'], '..') !== false;
$isDot = $get['b'] === '.';
if ($isValidBase && !$hasDots && !$isDot) {
@@ -145,8 +140,9 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
// try to rewrite path
foreach ($symlinks as $link => $target) {
if (0 === strpos($uri, $link)) {
if (strpos($uri, $link) === 0) {
$path = $target . DIRECTORY_SEPARATOR . substr($uri, strlen($link));
break;
}
}
@@ -157,15 +153,15 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
$basenames[] = basename($path, $ext);
} catch (Minify_Source_FactoryException $e) {
$this->logger->error($e->getMessage());
if (null === $firstMissing) {
if ($firstMissing === null) {
$firstMissing = $uri;
continue;
} else {
$secondMissing = $uri;
$this->logger->info("More than one file was missing: '$firstMissing', '$secondMissing`'");
return new Minify_ServeConfiguration($options);
continue;
}
$secondMissing = $uri;
$this->logger->info("More than one file was missing: '${firstMissing}', '${secondMissing}`'");
return new Minify_ServeConfiguration($options);
}
}
if ($selectionId) {
@@ -175,18 +171,18 @@ class Minify_Controller_MinApp extends Minify_Controller_Base
}
if (!$sources) {
$this->logger->info("No sources to serve");
$this->logger->info('No sources to serve');
return new Minify_ServeConfiguration($options);
}
if (null !== $firstMissing) {
if ($firstMissing !== null) {
array_unshift($sources, new Minify_Source(array(
'id' => 'missingFile',
// should not cause cache invalidation
'lastModified' => 0,
// due to caching, filename is unreliable.
'content' => "/* Minify: at least one missing file. See " . Minify::URL_DEBUG . " */\n",
'content' => '/* Minify: at least one missing file. See ' . Minify::URL_DEBUG . " */\n",
'minifier' => 'Minify::nullMinifier',
)));
}

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,14 +33,14 @@ class Minify_Controller_Page extends Minify_Controller_Base
{
if (isset($options['file'])) {
$sourceSpec = array(
'filepath' => $options['file']
'filepath' => $options['file'],
);
$f = $options['file'];
} else {
// strip controller options
$sourceSpec = array(
'content' => $options['content'],
'id' => $options['id'],
'id' => $options['id'],
);
$f = $options['id'];
unset($options['content'], $options['id']);
@@ -55,7 +52,7 @@ class Minify_Controller_Page extends Minify_Controller_Base
// this will be the 2nd argument passed to Minify_HTML::minify()
$sourceSpec['minifyOptions'] = array(
'cssMinifier' => array('Minify_CSSmin', 'minify'),
'jsMinifier' => array('JSMin\\JSMin', 'minify'),
'jsMinifier' => array('JSMin\\JSMin', 'minify'),
);
unset($options['minifyAll']);
}
@@ -66,4 +63,3 @@ class Minify_Controller_Page extends Minify_Controller_Base
return new Minify_ServeConfiguration($options, $sources, $selectionId);
}
}

View File

@@ -1,9 +1,7 @@
<?php
interface Minify_ControllerInterface
{
/**
* Create controller sources and options for Minify::serve()
*
@@ -19,4 +17,4 @@ interface Minify_ControllerInterface
* @return Minify_Env
*/
public function getEnv();
}
}

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
*/
@@ -23,8 +22,8 @@ class Minify_Env
{
$options = array_merge(array(
'server' => $_SERVER,
'get' => $_GET,
'post' => $_POST,
'get' => $_GET,
'post' => $_POST,
'cookie' => $_COOKIE,
), $options);
@@ -43,7 +42,7 @@ class Minify_Env
public function server($key = null)
{
if (null === $key) {
if ($key === null) {
return $this->server;
}
@@ -52,7 +51,7 @@ class Minify_Env
public function cookie($key = null, $default = null)
{
if (null === $key) {
if ($key === null) {
return $this->cookie;
}
@@ -61,7 +60,7 @@ class Minify_Env
public function get($key = null, $default = null)
{
if (null === $key) {
if ($key === null) {
return $this->get;
}
@@ -70,7 +69,7 @@ class Minify_Env
public function post($key = null, $default = null)
{
if (null === $key) {
if ($key === null) {
return $this->post;
}
@@ -103,19 +102,23 @@ class Minify_Env
}
protected $server;
protected $get;
protected $post;
protected $cookie;
/**
* Compute $_SERVER['DOCUMENT_ROOT'] for IIS using SCRIPT_FILENAME and SCRIPT_NAME.
*
* @param array $server
*
* @return string
*/
protected function computeDocRoot(array $server)
{
if (isset($server['SERVER_SOFTWARE']) && 0 !== strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/')) {
if (isset($server['SERVER_SOFTWARE']) && strpos($server['SERVER_SOFTWARE'], 'Microsoft-IIS/') !== 0) {
throw new InvalidArgumentException('DOCUMENT_ROOT is not provided and could not be computed');
}

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
@@ -70,7 +64,7 @@ class Minify_HTML
{
$this->_html = str_replace("\r\n", "\n", trim($html));
if (isset($options['xhtml'])) {
$this->_isXhtml = (bool)$options['xhtml'];
$this->_isXhtml = (bool) $options['xhtml'];
}
if (isset($options['cssMinifier'])) {
$this->_cssMinifier = $options['cssMinifier'];
@@ -79,7 +73,7 @@ class Minify_HTML
$this->_jsMinifier = $options['jsMinifier'];
}
if (isset($options['jsCleanComments'])) {
$this->_jsCleanComments = (bool)$options['jsCleanComments'];
$this->_jsCleanComments = (bool) $options['jsCleanComments'];
}
}
@@ -91,7 +85,7 @@ class Minify_HTML
public function process()
{
if ($this->_isXhtml === null) {
$this->_isXhtml = (false !== strpos($this->_html, '<!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.
@@ -132,31 +128,32 @@ class Minify_HTML
// remove ws around block/undisplayed elements
$this->_html = preg_replace('/\\s+(<\\/?(?:area|article|aside|base(?:font)?|blockquote|body'
.'|canvas|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|figcaption|figure|footer|form'
.'|frame(?:set)?|h[1-6]|head|header|hgroup|hr|html|legend|li|link|main|map|menu|meta|nav'
.'|ol|opt(?:group|ion)|output|p|param|section|t(?:able|body|head|d|h||r|foot|itle)'
.'|ul|video)\\b[^>]*>)/iu', '$1', $this->_html);
. '|canvas|caption|center|col(?:group)?|dd|dir|div|dl|dt|fieldset|figcaption|figure|footer|form'
. '|frame(?:set)?|h[1-6]|head|header|hgroup|hr|html|legend|li|link|main|map|menu|meta|nav'
. '|ol|opt(?:group|ion)|output|p|param|section|t(?:able|body|head|d|h||r|foot|itle)'
. '|ul|video)\\b[^>]*>)/iu', '$1', $this->_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,20 +25,21 @@ class Minify_HTML_Helper
* 'minAppUri' : (default '/min') URI of min directory
* 'rewriteWorks' : (default true) does mod_rewrite work in min app?
* 'groupsConfigFile' : specify if different
*
* @return string
*/
public static function getUri($keyOrFiles, $opts = array())
{
$opts = array_merge(array( // default options
'farExpires' => true,
'debug' => false,
'charset' => 'UTF-8',
'minAppUri' => '/min',
'rewriteWorks' => true,
'farExpires' => true,
'debug' => false,
'charset' => 'UTF-8',
'minAppUri' => '/min',
'rewriteWorks' => true,
'groupsConfigFile' => self::app()->groupsConfigPath,
), $opts);
$h = new self;
$h = new self();
$h->minAppUri = $opts['minAppUri'];
$h->rewriteWorks = $opts['rewriteWorks'];
$h->groupsConfigFile = $opts['groupsConfigFile'];
@@ -60,24 +59,25 @@ class Minify_HTML_Helper
*
* @param bool $farExpires
* @param bool $debug
*
* @return string
*/
public function getRawUri($farExpires = true, $debug = false)
{
$path = rtrim($this->minAppUri, '/') . '/';
if (! $this->rewriteWorks) {
if (!$this->rewriteWorks) {
$path .= '?';
}
if (null === $this->_groupKey) {
if ($this->_groupKey === null) {
// @todo: implement shortest uri
$path = self::_getShortestUri($this->_filePaths, $path);
} else {
$path .= "g=" . $this->_groupKey;
$path .= 'g=' . $this->_groupKey;
}
if ($debug) {
$path .= "&debug";
$path .= '&debug';
} elseif ($farExpires && $this->_lastModified) {
$path .= "&" . $this->_lastModified;
$path .= '&' . $this->_lastModified;
}
return $path;
@@ -97,9 +97,9 @@ class Minify_HTML_Helper
}
// normalize paths like in /min/f=<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, '\\', '/');
@@ -118,7 +118,7 @@ class Minify_HTML_Helper
{
$this->_groupKey = $key;
if ($checkLastModified) {
if (! $this->groupsConfigFile) {
if (!$this->groupsConfigFile) {
$this->groupsConfigFile = self::app()->groupsConfigPath;
}
if (is_file($this->groupsConfigFile)) {
@@ -142,6 +142,7 @@ class Minify_HTML_Helper
*
* @param array|string $sources
* @param int $lastModified
*
* @return int
*/
public static function getLastModified($sources, $lastModified = 0)
@@ -150,7 +151,7 @@ class Minify_HTML_Helper
$factory = self::app()->sourceFactory;
/** @var Minify_Source $source */
foreach ((array)$sources as $source) {
foreach ((array) $sources as $source) {
$source = $factory->makeSource($source);
$max = max($max, $source->getLastModified());
}
@@ -160,7 +161,9 @@ class Minify_HTML_Helper
/**
* @param \Minify\App $app
*
* @return \Minify\App
*
* @internal
*/
public static function app(\Minify\App $app = null)
@@ -178,9 +181,11 @@ class Minify_HTML_Helper
return $cached;
}
protected $_groupKey = null; // if present, URI will be like g=...
protected $_groupKey; // if present, URI will be like g=...
protected $_filePaths = array();
protected $_lastModified = null;
protected $_lastModified;
/**
* In a given array of strings, find the character they all have at
@@ -188,6 +193,7 @@ class Minify_HTML_Helper
*
* @param array $arr array of strings
* @param int $pos index to check
*
* @return mixed a common char or '' if any do not match
*/
protected static function _getCommonCharAtPos($arr, $pos)
@@ -214,6 +220,7 @@ class Minify_HTML_Helper
*
* @param array $paths root-relative URIs of files
* @param string $minRoot root-relative URI of the "min" application
*
* @return string
*/
protected static function _getShortestUri($paths, $minRoot = '/min/')
@@ -224,9 +231,9 @@ class Minify_HTML_Helper
$c = self::_getCommonCharAtPos($paths, $pos);
if ($c === '') {
break;
} else {
$base .= $c;
}
$base .= $c;
++$pos;
}
$base = preg_replace('@[^/]+$@', '', $base);

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;
@@ -56,9 +51,9 @@ class Minify_ImportProcessor
{
$file = preg_replace('~\\?.*~', '', $file);
$file = realpath($file);
if (! $file
if (!$file
|| in_array($file, self::$filesIncluded)
|| false === ($content = @file_get_contents($file))) {
|| ($content = @file_get_contents($file)) === false) {
// file missing, already included, or failed read
return '';
}
@@ -66,7 +61,7 @@ class Minify_ImportProcessor
$this->_currentDir = dirname($file);
// remove UTF-8 BOM if present
if (pack("CCC",0xef,0xbb,0xbf) === substr($content, 0, 3)) {
if (pack('CCC', 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
$content = substr($content, 3);
}
// ensure uniform EOLs
@@ -104,9 +99,9 @@ class Minify_ImportProcessor
// protocol, leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
: "/* Minify_ImportProcessor will not include remote content */";
: '/* Minify_ImportProcessor will not include remote content */';
}
if ('/' === $url[0]) {
if ($url[0] === '/') {
// protocol-relative or root path
$url = ltrim($url, '/');
$file = realpath($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR
@@ -118,7 +113,7 @@ class Minify_ImportProcessor
}
$obj = new Minify_ImportProcessor(dirname($file), $this->_currentDir);
$content = $obj->_getContent($file, true);
if ('' === $content) {
if ($content === '') {
// failed. leave in place for CSS, comment for JS
return self::$_isCss
? $m[0]
@@ -137,7 +132,7 @@ class Minify_ImportProcessor
$url = ($quote === '') ? $m[1] : substr($m[1], 1, strlen($m[1]) - 2);
if ('/' !== $url[0]) {
if ($url[0] !== '/') {
if (strpos($url, '//') > 0) {
// probably starts with protocol, do not alter
} else {
@@ -156,6 +151,7 @@ class Minify_ImportProcessor
* @param string $from
* @param string $to
* @param string $ps
*
* @return string
*/
private function getPathDiff($from, $to, $ps = DIRECTORY_SEPARATOR)
@@ -170,19 +166,22 @@ class Minify_ImportProcessor
array_shift($arTo);
}
return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
return str_pad('', count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
}
/**
* This function is to replace PHP's extremely buggy realpath().
* @param string $path The original path, can be relative etc.
* @return string The resolved path, it might not exist.
*
* @param string $path the original path, can be relative etc
*
* @return string the resolved path, it might not exist
*
* @see http://stackoverflow.com/questions/4049856/replace-phps-realpath
*/
private function truepath($path)
{
// whether $path is unix or not
$unipath = ('' === $path) || ($path{0} !== '/');
$unipath = ($path === '') || ($path[0] !== '/');
// attempts to detect if path is relative in which case, add cwd
if (strpos($path, ':') === false && $unipath) {
@@ -194,10 +193,10 @@ class Minify_ImportProcessor
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' === $part) {
if ($part === '.') {
continue;
}
if ('..' === $part) {
if ($part === '..') {
array_pop($absolutes);
} else {
$absolutes[] = $part;
@@ -210,8 +209,6 @@ class Minify_ImportProcessor
$path = readlink($path);
}
// put initial separator that could have been lost
$path = !$unipath ? '/' . $path : $path;
return $path;
return !$unipath ? '/' . $path : $path;
}
}

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'
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
);
/**
* @var string $url URL of compiler server. defaults to Google's
* @var string URL of compiler server. defaults to Google's
*/
protected $serviceUrl = 'https://closure-compiler.appspot.com/compile';
/**
* @var int $maxBytes The maximum JS size that can be sent to the compiler server in bytes
* @var int The maximum JS size that can be sent to the compiler server in bytes
*/
protected $maxBytes = self::DEFAULT_MAX_BYTES;
/**
* @var string[] $additionalOptions Additional options to pass to the compiler service
* @var string[] Additional options to pass to the compiler service
*/
protected $additionalOptions = array();
@@ -120,15 +116,17 @@ class Minify_JS_ClosureCompiler
* Call the service to perform the minification
*
* @param string $js JavaScript code
* @return string
*
* @throws Minify_JS_ClosureCompiler_Exception
*
* @return string
*/
public function min($js)
{
$postBody = $this->buildPostBody($js);
if ($this->maxBytes > 0) {
$bytes = (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2))
$bytes = (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload') & 2))
? mb_strlen($postBody, '8bit')
: strlen($postBody);
if ($bytes > $this->maxBytes) {
@@ -143,7 +141,7 @@ class Minify_JS_ClosureCompiler
if (preg_match('/^Error\(\d\d?\):/', $response)) {
if (is_callable($this->fallbackMinifier)) {
// use fallback
$response = "/* Received errors from Closure Compiler API:\n$response"
$response = "/* Received errors from Closure Compiler API:\n${response}"
. "\n(Using fallback minifier)\n*/\n";
$response .= call_user_func($this->fallbackMinifier, $js);
} else {
@@ -153,6 +151,7 @@ class Minify_JS_ClosureCompiler
if ($response === '') {
$errors = $this->getResponse($this->buildPostBody($js, true));
throw new Minify_JS_ClosureCompiler_Exception($errors);
}
@@ -163,8 +162,10 @@ class Minify_JS_ClosureCompiler
* Get the response for a given POST body
*
* @param string $postBody
* @return string
*
* @throws Minify_JS_ClosureCompiler_Exception
*
* @return string
*/
protected function getResponse($postBody)
{
@@ -173,15 +174,15 @@ class Minify_JS_ClosureCompiler
if ($allowUrlFopen) {
$contents = file_get_contents($this->serviceUrl, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'method' => 'POST',
'compilation_level' => 'SIMPLE',
'output_format' => 'text',
'output_info' => 'compiled_code',
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
'content' => $postBody,
'max_redirects' => 0,
'timeout' => 15,
)
'output_format' => 'text',
'output_info' => 'compiled_code',
'header' => "Content-type: application/x-www-form-urlencoded\r\nConnection: close\r\n",
'content' => $postBody,
'max_redirects' => 0,
'timeout' => 15,
),
)));
} elseif (defined('CURLOPT_POST')) {
$ch = curl_init($this->serviceUrl);
@@ -195,13 +196,13 @@ class Minify_JS_ClosureCompiler
curl_close($ch);
} else {
throw new Minify_JS_ClosureCompiler_Exception(
"Could not make HTTP request: allow_url_open is false and cURL not available"
'Could not make HTTP request: allow_url_open is false and cURL not available'
);
}
if (false === $contents) {
if ($contents === false) {
throw new Minify_JS_ClosureCompiler_Exception(
"No HTTP response from server"
'No HTTP response from server'
);
}
@@ -213,6 +214,7 @@ class Minify_JS_ClosureCompiler
*
* @param string $js JavaScript code
* @param bool $returnErrors
*
* @return string
*/
protected function buildPostBody($js, $returnErrors = false)
@@ -222,8 +224,8 @@ class Minify_JS_ClosureCompiler
self::$DEFAULT_OPTIONS,
$this->additionalOptions,
array(
'js_code' => $js,
'output_info' => ($returnErrors ? 'errors' : 'compiled_code')
'js_code' => $js,
'output_info' => ($returnErrors ? 'errors' : 'compiled_code'),
)
),
null,

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?
*
@@ -102,7 +94,8 @@ class Minify_Lines
// stop comment and keep walking line
$inComment = false;
@$line = (string)substr($line, $index + 2);
@$line = (string) substr($line, $index + 2);
continue;
}
@@ -116,7 +109,8 @@ class Minify_Lines
if ($single === false || $multi < $single) {
// start comment and keep walking line
$inComment = true;
@$line = (string)substr($line, $multi + 2);
@$line = (string) substr($line, $multi + 2);
continue;
}
@@ -131,12 +125,9 @@ class Minify_Lines
* Prepend a comment (or note) to the given line
*
* @param string $line current line of code
*
* @param string $note content of note/comment
*
* @param bool $inComment was the parser in a comment at the
* beginning of the line?
*
* @param int $padTo minimum width of comment
*
* @return string
@@ -157,6 +148,7 @@ class Minify_Lines
*
* @param string $str String containing the token
* @param string $token Token being checked
*
* @return bool
*/
private static function _find($str, $token)
@@ -164,24 +156,26 @@ class Minify_Lines
switch ($token) {
case '//':
$fakes = array(
'://' => 1,
'"//' => 1,
'\'//' => 1,
'".//' => 2,
'://' => 1,
'"//' => 1,
'\'//' => 1,
'".//' => 2,
'\'.//' => 2,
);
break;
case '/*':
$fakes = array(
'"/*' => 1,
'\'/*' => 1,
'"//*' => 2,
'\'//*' => 2,
'".//*' => 3,
'"/*' => 1,
'\'/*' => 1,
'"//*' => 2,
'\'//*' => 2,
'".//*' => 3,
'\'.//*' => 3,
'*/*' => 1,
'\\/*' => 1,
'*/*' => 1,
'\\/*' => 1,
);
break;
default:
$fakes = array();
@@ -197,6 +191,7 @@ class Minify_Lines
// move offset and scan again
$offset += $index + strlen($token);
$index = strpos($str, $token, $offset);
break;
}
}

View File

@@ -19,6 +19,6 @@ class LegacyHandler extends AbstractProcessingHandler
protected function write(array $record)
{
$this->obj->log((string)$record['formatted']);
$this->obj->log((string) $record['formatted']);
}
}

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();
@@ -170,7 +171,7 @@ class Minify_ScssCssSource extends Minify_Source
'elapsed' => $elapsed, // statistic, can be dropped
'updated' => $updated,
'content' => $css,
'files' => $imports,
'files' => $imports,
);
}
}

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,32 +39,30 @@ class Minify_Source_Factory
* file, use the touch command to update the mtime on the server. If the mtime
* jumps ahead by a number of hours, set this variable to that number. If the mtime
* moves back, this should not be needed.
*
* @param Minify_CacheInterface $cache Optional cache for handling .less files.
*
*/
public function __construct(Minify_Env $env, array $options = array(), Minify_CacheInterface $cache = null)
{
$this->env = $env;
$this->options = array_merge(array(
'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
'fileChecker' => array($this, 'checkIsFile'),
'resolveDocRoot' => true,
'checkAllowDirs' => true,
'allowDirs' => array('//'),
'noMinPattern' => '@[-\\.]min\\.(?:[a-zA-Z]+)$@i', // matched against basename
'fileChecker' => array($this, 'checkIsFile'),
'resolveDocRoot' => true,
'checkAllowDirs' => true,
'allowDirs' => array('//'),
'uploaderHoursBehind' => 0,
), $options);
// resolve // in allowDirs
$docRoot = $env->getDocRoot();
foreach ($this->options['allowDirs'] as $i => $dir) {
if (0 === strpos($dir, '//')) {
if (strpos($dir, '//') === 0) {
$this->options['allowDirs'][$i] = $docRoot . substr($dir, 1);
}
}
if ($this->options['fileChecker'] && !is_callable($this->options['fileChecker'])) {
throw new InvalidArgumentException("fileChecker option is not callable");
throw new InvalidArgumentException('fileChecker option is not callable');
}
$this->setHandler('~\.less$~i', function ($spec) use ($cache) {
@@ -92,24 +89,25 @@ class Minify_Source_Factory
/**
* @param string $file
* @return string
*
* @throws Minify_Source_FactoryException
*
* @return string
*/
public function checkIsFile($file)
{
$realpath = realpath($file);
if (!$realpath) {
throw new Minify_Source_FactoryException("File failed realpath(): $file");
throw new Minify_Source_FactoryException("File failed realpath(): ${file}");
}
$basename = basename($file);
if (0 === strpos($basename, '.')) {
throw new Minify_Source_FactoryException("Filename starts with period (may be hidden): $basename");
if (strpos($basename, '.') === 0) {
throw new Minify_Source_FactoryException("Filename starts with period (may be hidden): ${basename}");
}
if (!is_file($realpath) || !is_readable($realpath)) {
throw new Minify_Source_FactoryException("Not a file or isn't readable: $file");
throw new Minify_Source_FactoryException("Not a file or isn't readable: ${file}");
}
return $realpath;
@@ -118,9 +116,9 @@ class Minify_Source_Factory
/**
* @param mixed $spec
*
* @return Minify_SourceInterface
*
* @throws Minify_Source_FactoryException
*
* @return Minify_SourceInterface
*/
public function makeSource($spec)
{
@@ -139,7 +137,7 @@ class Minify_Source_Factory
return new Minify_Source($spec);
}
if ($this->options['resolveDocRoot'] && 0 === strpos($spec['filepath'], '//')) {
if ($this->options['resolveDocRoot'] && strpos($spec['filepath'], '//') === 0) {
$spec['filepath'] = $this->env->getDocRoot() . substr($spec['filepath'], 1);
}
@@ -148,7 +146,7 @@ class Minify_Source_Factory
}
if ($this->options['checkAllowDirs']) {
$allowDirs = (array)$this->options['allowDirs'];
$allowDirs = (array) $this->options['allowDirs'];
$inAllowedDir = false;
$filePath = $this->env->normalizePath($spec['filepath']);
foreach ($allowDirs as $allowDir) {
@@ -159,9 +157,10 @@ class Minify_Source_Factory
if (!$inAllowedDir) {
$allowDirsStr = implode(';', $allowDirs);
throw new Minify_Source_FactoryException("File '{$spec['filepath']}' is outside \$allowDirs "
. "($allowDirsStr). If the path is resolved via an alias/symlink, look into the "
. "\$min_symlinks option.");
. "(${allowDirsStr}). If the path is resolved via an alias/symlink, look into the "
. '$min_symlinks option.');
}
}
@@ -170,7 +169,7 @@ class Minify_Source_Factory
if ($this->options['noMinPattern'] && preg_match($this->options['noMinPattern'], $basename)) {
if (preg_match('~\.(css|less)$~i', $basename)) {
$spec['minifyOptions']['compress'] = false;
// we still want URI rewriting to work for CSS
// we still want URI rewriting to work for CSS
} else {
$spec['minifier'] = 'Minify::nullMinifier';
}
@@ -184,12 +183,13 @@ class Minify_Source_Factory
foreach ($this->handlers as $basenamePattern => $handler) {
if (preg_match($basenamePattern, $basename)) {
$source = call_user_func($handler, $spec);
break;
}
}
if (!$source) {
throw new Minify_Source_FactoryException("Handler not found for file: $basename");
throw new Minify_Source_FactoryException("Handler not found for file: ${basename}");
}
return $source;

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
@@ -90,8 +83,8 @@ class Minify_YUICompressor
private static function _minify($type, $content, $options)
{
self::_prepare();
if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
throw new Exception('Minify_YUICompressor : could not create temp file in "'.self::$tempDir.'".');
if (!($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
throw new Exception('Minify_YUICompressor : could not create temp file in "' . self::$tempDir . '".');
}
file_put_contents($tmpFile, $content);
@@ -107,13 +100,13 @@ class Minify_YUICompressor
private static function _getCmd($userOptions, $type, $tmpFile)
{
$defaults = array(
'charset' => '',
'line-break' => 5000,
'type' => $type,
'nomunge' => false,
'preserve-semi' => false,
'charset' => '',
'line-break' => 5000,
'type' => $type,
'nomunge' => false,
'preserve-semi' => false,
'disable-optimizations' => false,
'stack-size' => '',
'stack-size' => '',
);
$o = array_merge($defaults, $userOptions);
@@ -125,7 +118,7 @@ class Minify_YUICompressor
? " --charset {$o['charset']}"
: '')
. (is_numeric($o['line-break']) && $o['line-break'] >= 0
? ' --line-break ' . (int)$o['line-break']
? ' --line-break ' . (int) $o['line-break']
: '');
if ($type === 'js') {
foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) {
@@ -140,18 +133,17 @@ class Minify_YUICompressor
private static function _prepare()
{
if (! is_file(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not a valid file.');
if (!is_file(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile(' . self::$jarFile . ') is not a valid file.');
}
if (! is_readable(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile('.self::$jarFile.') is not readable.');
if (!is_readable(self::$jarFile)) {
throw new Exception('Minify_YUICompressor : $jarFile(' . self::$jarFile . ') is not readable.');
}
if (! is_dir(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not a valid direcotry.');
if (!is_dir(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir(' . self::$tempDir . ') is not a valid direcotry.');
}
if (! is_writable(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir('.self::$tempDir.') is not writable.');
if (!is_writable(self::$tempDir)) {
throw new Exception('Minify_YUICompressor : $tempDir(' . self::$tempDir . ') is not writable.');
}
}
}

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,19 +60,19 @@ class Cli
/**
* @var resource
*/
protected $_stdin = null;
protected $_stdin;
/**
* @var resource
*/
protected $_stdout = null;
protected $_stdout;
/**
* @param bool $exitIfNoStdin (default true) Exit() if STDIN is not defined
*/
public function __construct($exitIfNoStdin = true)
{
if ($exitIfNoStdin && ! defined('STDIN')) {
if ($exitIfNoStdin && !defined('STDIN')) {
exit('This script is for command-line use only.');
}
if (isset($GLOBALS['argv'][1])
@@ -85,6 +83,7 @@ class Cli
/**
* @param Arg|string $letter
*
* @return Arg
*/
public function addOptionalArg($letter)
@@ -94,6 +93,7 @@ class Cli
/**
* @param Arg|string $letter
*
* @return Arg
*/
public function addRequiredArg($letter)
@@ -105,15 +105,17 @@ class Cli
* @param string $letter
* @param bool $required
* @param Arg|null $arg
* @return Arg
*
* @throws InvalidArgumentException
*
* @return Arg
*/
public function addArgument($letter, $required, Arg $arg = null)
{
if (! preg_match('/^[a-zA-Z]$/', $letter)) {
if (!preg_match('/^[a-zA-Z]$/', $letter)) {
throw new InvalidArgumentException('$letter must be in [a-zA-Z]');
}
if (! $arg) {
if (!$arg) {
$arg = new Arg($required);
}
$this->_args[$letter] = $arg;
@@ -123,6 +125,7 @@ class Cli
/**
* @param string $letter
*
* @return Arg|null
*/
public function getArgument($letter)
@@ -170,35 +173,36 @@ class Cli
if (is_bool($o[$letter])) {
// remove from argv copy
$k = array_search("-$letter", $argvCopy);
$k = array_search("-${letter}", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 1);
}
if ($arg->mustHaveValue) {
$this->addError($letter, "Missing value");
$this->addError($letter, 'Missing value');
} else {
$this->values[$letter] = true;
}
} else {
// string
$this->values[$letter] = $o[$letter];
$v =& $this->values[$letter];
$v = &$this->values[$letter];
// remove from argv copy
// first look for -ovalue or -o=value
$pattern = "/^-{$letter}=?" . preg_quote($v, '/') . "$/";
$pattern = "/^-{$letter}=?" . preg_quote($v, '/') . '$/';
$foundInArgv = false;
foreach ($argvCopy as $k => $argV) {
if (preg_match($pattern, $argV)) {
array_splice($argvCopy, $k, 1);
$foundInArgv = true;
break;
}
}
if (! $foundInArgv) {
if (!$foundInArgv) {
// space separated
$k = array_search("-$letter", $argvCopy);
$k = array_search("-${letter}", $argvCopy);
if ($k !== false) {
array_splice($argvCopy, $k, 2);
}
@@ -206,17 +210,17 @@ class Cli
// check that value isn't really another option
if (strlen($lettersUsed) > 1) {
$pattern = "/^-[" . str_replace($letter, '', $lettersUsed) . "]/i";
$pattern = '/^-[' . str_replace($letter, '', $lettersUsed) . ']/i';
if (preg_match($pattern, $v)) {
$this->addError($letter, "Value was read as another option: %s", $v);
$this->addError($letter, 'Value was read as another option: %s', $v);
return false;
}
}
if ($arg->assertFile || $arg->assertDir) {
if ($v[0] !== '/' && $v[0] !== '~') {
$this->values["$letter.raw"] = $v;
$v = getcwd() . "/$v";
$this->values["${letter}.raw"] = $v;
$v = getcwd() . "/${v}";
}
}
if ($arg->assertFile) {
@@ -225,28 +229,29 @@ class Cli
} elseif ($arg->useAsOutfile) {
$this->_stdout = $v;
}
if ($arg->assertReadable && ! is_readable($v)) {
$this->addError($letter, "File not readable: %s", $v);
if ($arg->assertReadable && !is_readable($v)) {
$this->addError($letter, 'File not readable: %s', $v);
continue;
}
if ($arg->assertWritable) {
if (is_file($v)) {
if (! is_writable($v)) {
$this->addError($letter, "File not writable: %s", $v);
if (!is_writable($v)) {
$this->addError($letter, 'File not writable: %s', $v);
}
} else {
if (! is_writable(dirname($v))) {
$this->addError($letter, "Directory not writable: %s", dirname($v));
if (!is_writable(dirname($v))) {
$this->addError($letter, 'Directory not writable: %s', dirname($v));
}
}
}
} elseif ($arg->assertDir && $arg->assertWritable && ! is_writable($v)) {
$this->addError($letter, "Directory not readable: %s", $v);
} elseif ($arg->assertDir && $arg->assertWritable && !is_writable($v)) {
$this->addError($letter, 'Directory not readable: %s', $v);
}
}
} else {
if ($arg->isRequired()) {
$this->addError($letter, "Missing");
$this->addError($letter, 'Missing');
}
}
}
@@ -266,7 +271,7 @@ class Cli
$r = $this->moreArgs;
foreach ($r as $k => $v) {
if ($v[0] !== '/' && $v[0] !== '~') {
$v = getcwd() . "/$v";
$v = getcwd() . "/${v}";
$v = str_replace('/./', '/', $v);
do {
$v = preg_replace('@/[^/]+/\\.\\./@', '/', $v, 1, $changed);
@@ -290,7 +295,7 @@ class Cli
}
$r = "Some arguments did not pass validation:\n";
foreach ($this->errors as $letter => $arr) {
$r .= " $letter : " . implode(', ', $arr) . "\n";
$r .= " ${letter} : " . implode(', ', $arr) . "\n";
}
$r .= "\n";
@@ -306,11 +311,11 @@ class Cli
foreach ($this->_args as $letter => $arg) {
/* @var Arg $arg */
$desc = $arg->getDescription();
$flag = " -$letter ";
$flag = " -${letter} ";
if ($arg->mayHaveValue) {
$flag .= "[VAL]";
$flag .= '[VAL]';
} elseif ($arg->mustHaveValue) {
$flag .= "VAL";
$flag .= 'VAL';
}
if ($arg->assertFile) {
$flag = str_replace('VAL', 'FILE', $flag);
@@ -318,9 +323,9 @@ class Cli
$flag = str_replace('VAL', 'DIR', $flag);
}
if ($arg->isRequired()) {
$desc = "(required) $desc";
$desc = "(required) ${desc}";
}
$flag = str_pad($flag, 12, " ", STR_PAD_RIGHT);
$flag = str_pad($flag, 12, ' ', STR_PAD_RIGHT);
$desc = wordwrap($desc, 70);
$r .= $flag . str_replace("\n", "\n ", $desc) . "\n\n";
}
@@ -336,18 +341,17 @@ class Cli
*/
public function openInput()
{
if (null === $this->_stdin) {
if ($this->_stdin === null) {
return STDIN;
} else {
$this->_stdin = fopen($this->_stdin, 'rb');
return $this->_stdin;
}
$this->_stdin = fopen($this->_stdin, 'rb');
return $this->_stdin;
}
public function closeInput()
{
if (null !== $this->_stdin) {
if ($this->_stdin !== null) {
fclose($this->_stdin);
}
}
@@ -361,18 +365,17 @@ class Cli
*/
public function openOutput()
{
if (null === $this->_stdout) {
if ($this->_stdout === null) {
return STDOUT;
} else {
$this->_stdout = fopen($this->_stdout, 'wb');
return $this->_stdout;
}
$this->_stdout = fopen($this->_stdout, 'wb');
return $this->_stdout;
}
public function closeOutput()
{
if (null !== $this->_stdout) {
if ($this->_stdout !== null) {
fclose($this->_stdout);
}
}
@@ -390,4 +393,3 @@ class Cli
$this->errors[$letter][] = sprintf($msg, $value);
}
}

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
@@ -51,14 +50,14 @@ class Arg
public function getDefaultSpec()
{
return array(
'mayHaveValue' => false,
'mustHaveValue' => false,
'assertFile' => false,
'assertDir' => false,
'mayHaveValue' => false,
'mustHaveValue' => false,
'assertFile' => false,
'assertDir' => false,
'assertReadable' => false,
'assertWritable' => false,
'useAsInfile' => false,
'useAsOutfile' => false,
'useAsInfile' => false,
'useAsOutfile' => false,
);
}
@@ -93,6 +92,7 @@ class Arg
* Assert that the argument's value points to a writable file. When
* Cli::openOutput() is called, a write pointer to this file will
* be provided.
*
* @return Arg
*/
public function useAsOutfile()
@@ -106,6 +106,7 @@ class Arg
* Assert that the argument's value points to a readable file. When
* Cli::openInput() is called, a read pointer to this file will
* be provided.
*
* @return Arg
*/
public function useAsInfile()
@@ -125,6 +126,7 @@ class Arg
/**
* @param string $desc
*
* @return Arg
*/
public function setDescription($desc)
@@ -155,8 +157,10 @@ class Arg
*
* @param string $name
* @param array $args
* @return Arg
*
* @throws BadMethodCallException
*
* @return Arg
*/
public function __call($name, array $args = array())
{
@@ -176,6 +180,7 @@ class Arg
* Note: magic properties declared in class PHPDOC
*
* @param string $name
*
* @return bool|null
*/
public function __get($name)