1
0
mirror of https://github.com/mrclay/minify.git synced 2025-08-08 07:06:49 +02:00

Merge pull request #475 from mrclay/css_docs

Migrate to CSSmin and docs overhaul
This commit is contained in:
Steve Clay
2015-09-28 21:18:15 -04:00
27 changed files with 348 additions and 518 deletions

View File

@@ -1,6 +1,9 @@
Minify Release History
(master)
Version 3.0.0
* Better CSS minification via Túbal Martín's CSSMin
* New API incompatible with the 2.x versions
* Installation requires use of Composer to install dependencies
* Builder styled with Bootstrap (thanks to help from acidvertigo)
* Add config option for simply concatenating files

186
MIN.txt
View File

@@ -1,186 +0,0 @@
The files in the /min/ directory represent the default Minify setup designed to ease
integration with your site. This app will combine and minify your Javascript or
CSS files and serve them with HTTP compression and cache headers.
RECOMMENDED
It's recommended to edit /min/config.php to set $min_cachePath to a writeable
(by PHP) directory on your system. This will improve performance.
GETTING STARTED
The quickest way to get started is to use the Minify URI Builder application
on your website: http://example.com/min/builder/
MINIFYING A SINGLE FILE
Let's say you want to serve this file:
http://example.com/wp-content/themes/default/default.css
Here's the "Minify URL" for this file:
http://example.com/min/?f=wp-content/themes/default/default.css
In other words, the "f" argument is set to the file path from root without the
initial "/". As CSS files may contain relative URIs, Minify will automatically
"fix" these by rewriting them as root relative.
COMBINING MULTIPLE FILES IN ONE DOWNLOAD
Separate the paths given to "f" with commas.
Let's say you have CSS files at these URLs:
http://example.com/scripts/jquery-1.2.6.js
http://example.com/scripts/site.js
You can combine these files through Minify by requesting this URL:
http://example.com/min/?f=scripts/jquery-1.2.6.js,scripts/site.js
SIMPLIFYING URLS WITH A BASE PATH
If you're combining files that share the same ancestor directory, you can use
the "b" argument to set the base directory for the "f" argument. Do not include
the leading or trailing "/" characters.
E.g., the following URLs will serve the exact same content:
http://example.com/min/?f=scripts/jquery-1.2.6.js,scripts/site.js,scripts/home.js
http://example.com/min/?b=scripts&f=jquery-1.2.6.js,site.js,home.js
MINIFY URLS IN HTML
In HTML files, don't forget to replace any "&" characters with "&".
SPECIFYING ALLOWED DIRECTORIES
By default, Minify will serve any *.css/*.js files within the DOCUMENT_ROOT. If
you'd prefer to limit Minify's access to certain directories, set the
$min_serveOptions['minApp']['allowDirs'] array in config.php. E.g. to limit
to the /js and /themes/default directories, use:
$min_serveOptions['minApp']['allowDirs'] = array('//js', '//themes/default');
GROUPS: NICER URLS
For nicer URLs, edit groupsConfig.php to pre-specify groups of files
to be combined under preset keys. E.g., here's an example configuration in
groupsConfig.php:
return array(
'js' => array('//js/Class.js', '//js/email.js')
);
This pre-selects the following files to be combined under the key "js":
http://example.com/js/Class.js
http://example.com/js/email.js
You can now serve these files with this simple URL:
http://example.com/min/?g=js
GROUPS: SPECIFYING FILES OUTSIDE THE DOC_ROOT
In the groupsConfig.php array, the "//" in the file paths is a shortcut for
the DOCUMENT_ROOT, but you can also specify paths from the root of the filesystem
or relative to the DOC_ROOT:
return array(
'js' => array(
'//js/file.js' // file within DOC_ROOT
,'//../file.js' // file in parent directory of DOC_ROOT
,'C:/Users/Steve/file.js' // file anywhere on filesystem
)
);
COMBINE MULTIPLE GROUPS AND FILES IN ONE URL
E.g.: http://example.com/min/?g=js&f=more/scripts.js
Separate group keys with commas:
http://example.com/min/?g=baseCss,css1&f=moreStyles.css
FAR-FUTURE EXPIRES HEADERS
Minify can send far-future (one year) Expires headers. To enable this you must
add a number or the parameter "v" to the querystring (e.g. /min/?g=js&1234 or
/min/?g=js&v=1234) and alter it whenever a source file is changed. If you have a
build process you can use a build/source control revision number.
You can alternately use the utility function Minify_getUri() to get a "versioned"
Minify URI for use in your HTML. E.g.:
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/min/utils.php';
$jsUri = Minify_getUri('js'); // a key in groupsConfig.php
echo "<script src='{$jsUri}'></script>";
$cssUri = Minify_getUri(array(
'//css/styles1.css'
,'//css/styles2.css'
)); // a list of files
echo "<link rel=stylesheet href='{$cssUri}'>";
STORING CONFIG FILES OUTSIDE THE MINIFY DIRECTORY
It is possible to store config files (min/config.php, min/config-test.php,
min/groupsConfig.php) in a custom directory outside the Minify directory. This is
useful if you wish to include Minify as an external dependency inside another
project via SVN external or Git submodule inclusion.
For example, let's assume you have a Minify directory "min" in your site root. Then
you could create a new directory called "min-configs" in the site root. Copy any
config files you wish to modify to "min-configs", and modify as desired.
Then create a new file, for example "min.php" in your site root. The contents of
this file could look like this:
<?php
$customConfigDirectory = __DIR__ . '/min-configs';
$min_customConfigPaths = array(
'base' => $customConfigDirectory . '/config.php',
'test' => $customConfigDirectory . '/config-test.php',
'groups' => $customConfigDirectory . '/groupsConfig.php'
);
include_once 'min/index.php';
You would then reference min.php in your JS and CSS links instead of min/index.php.
This method will affect those using the Minify_getUri() function. You will need
to add options to calls to that function, e.g.:
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/min/utils.php';
$jsUri = Minify_getUri('//js/file.js', array('minAppUri' => '/min.php'));
echo "<script src='{$jsUri}'></script>";
DEBUG MODE
In debug mode, instead of compressing files, Minify sends combined files with
comments prepended to each line to show the line number in the original source
file. To enable this, set $min_allowDebugFlag to true in config.php and append
"&debug=1" to your URIs. E.g. /min/?f=script1.js,script2.js&debug=1
Known issue: files with comment-like strings/regexps can cause problems in this mode.
BYPASSING MINIFICATION
See the $min_concatOnly option in config.php.
QUESTIONS?
http://groups.google.com/group/minify

View File

@@ -114,9 +114,9 @@ $min_serveOptions['maxAge'] = 1800;
/**
* To use CSSmin (Túbal Martín's port of the YUI CSS compressor), uncomment the following line:
* To use the CSS compressor that shipped with 2.x, uncomment the following line:
*/
//$min_serveOptions['minifiers']['text/css'] = array('Minify_CSSmin', 'minify');
//$min_serveOptions['minifiers'][Minify::TYPE_CSS] = array('Minify_CSS', 'minify');
/**

View File

@@ -1,12 +1,13 @@
If you test sites in a subdirectory (e.g. `http://localhost/testSite/`) rather than a virtualhost, then you'll need to adjust the way you use Minify to rewrite CSS correctly.
1. Place the following in `min/config.php`:
```
1. Place the following in `config.php`:
```php
// Set the document root to be the path of the "site root"
$min_documentRoot = substr(__FILE__, 0, -15);
$min_documentRoot = substr(__FILE__, 0, -11);
// Set $sitePrefix to the path of the site from the webserver's real docroot
list($sitePrefix) = explode('/min/index.php', $_SERVER['SCRIPT_NAME'], 2);
list($sitePrefix) = explode('/index.php', $_SERVER['SCRIPT_NAME'], 2);
// Prepend $sitePrefix to the rewritten URIs in CSS files
$min_symlinks['//' . ltrim($sitePrefix, '/')] = $min_documentRoot;
@@ -25,5 +26,5 @@ Now the `min` application should operate correctly from a subdirectory and will
| **file served** | `/home/mysite_com/www/js/file1.js` | `/var/www/testSite/js/file1.js` |
Caveats:
* This configuration may break the Builder application (located at `/min/builder/`) used to create Minify URIs, but you can still [create them by hand](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/README.txt#18).
* This configuration may break the Builder application (located at `/min/builder/`) used to create Minify URIs, but you can still create them by hand.
* Make sure you don't reset `$min_symlinks` to a different value lower in your config file.

View File

@@ -4,6 +4,6 @@ It also does some run-time checks of your PHP and Minify configuration to look f
After installation, this is found at **`http://example.com/min/builder/`**
You must enable it by editing `min/config.php` and setting `$min_enableBuilder = true;`
You must enable it by editing `config.php` and setting `$min_enableBuilder = true;`
After use, you should disable it by resetting `$min_enableBuilder = false;`

View File

@@ -2,20 +2,11 @@ If this page doesn't help, please post a question on our [Google group](http://g
## URIs are re-written incorrectly in CSS output
See UriRewriting.
## Files aren't cached in IE6
**Use Minify 2.1.4+**.
For Minify 2.1.3 and below:
1. Open `/min/lib/HTTP/Encoder.php`
1. On line [62](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/HTTP/Encoder.php#62), change `false` to `true`.
See [UriRewriting](UriRewriting.wiki.md).
## Builder Fails / 400 Errors
**Use Minify 2.1.4+**, and you can see the cause of 400 responses using FirePHP (See [Debugging](Debugging.md)).
This is usually due to an unusual server setup. You can see the cause of 400 responses using FirePHP (See [Debugging](Debugging.wiki.md)).
## PHP/Apache crashes
@@ -23,15 +14,15 @@ For Minify 2.1.3 and below:
* Raise Apache's [ThreadStackSize](http://stackoverflow.com/a/7597506/3779)
* In [php.ini](http://php.net/manual/en/pcre.configuration.php) raise `pcre.backtrack_limit` and `pcre.recursion_limit` to 1000000. These will allow processing longer strings, but also require a larger stack size.
* Try [this CSSmin configuration](http://code.google.com/p/minify/wiki/CookBook#CSSmin_PHP_port)
* Use YUICompressor instead of PHP-based CSS compressors
## Dealing with Javascript errors
Short answer: **use Minify 2.1.4+, use a pre-compressed version of your file, and rename it `*.min.js` or `*-min.js`**. By default Minify won't try to minify these files (but will still gzip them). The [Compressor Rater](http://compressorrater.thruhere.net/) is handy for compressing files individually.
If the error is in your code, enable [debug mode](Debugging.md) while debugging your code in Firebug or your favorite browser's Javascript debugger. This will insert comments to allow you to keep track of the individual source locations in the combined file.
If the error is in your code, enable [debug mode](Debugging.wiki.md) while debugging your code in Firebug or your favorite browser's Javascript debugger. This will insert comments to allow you to keep track of the individual source locations in the combined file.
If you have Java on your web host, you can use the [wrapper for YUI Compressor](http://code.google.com/p/minify/source/browse/min/lib/Minify/YUICompressor.php) instead of JSMin. [This thread](http://groups.google.com/group/minify/browse_thread/thread/f12f25f27e1256fe) shows how a user has done this.
If you have Java on your web host, you can use the [wrapper for YUI Compressor](https://github.com/mrclay/minify/blob/master/lib/Minify/YUICompressor.php) instead of JSMin. [This thread](http://groups.google.com/group/minify/browse_thread/thread/f12f25f27e1256fe) shows how a user has done this.
## Javascript isn't being minified
@@ -53,7 +44,7 @@ Scriptaculous 1.8.2 (and probably all 1.x) has an [autoloader script](http://git
If you upload files using [Coda or Transmit](http://groups.google.com/group/coda-users/browse_thread/thread/572d2dc315ec02e7/) or from a Windows PC to a non-Windows server, your new files may end up with the wrong `mtime` (timestamp) on the server, confusing the cache system.
Setting the [$min\_uploaderHoursBehind option](https://github.com/mrclay/minify/blob/master/min/config.php#L171) in `config.php` can compensate for this.
Setting the [$min\_uploaderHoursBehind option](https://github.com/mrclay/minify/blob/master/config.php#L171) in `config.php` can compensate for this.
WinSCP has a [Daylight Saving Time option](http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time) that can prevent this issue.
@@ -69,8 +60,8 @@ If a change is not seen, verify that the server cache file is being updated.
## Disable Caching
If you'd like to temporarily disable the cache without using [debug mode](Debugging.md), place these settings at the end of `config.php`:
```
If you'd like to temporarily disable the cache without using [debug mode](Debugging.wiki.md), place these settings at the end of `config.php`:
```php
// disable server caching
$min_cachePath = null;
// prevent client caching
@@ -103,8 +94,8 @@ Debug mode adds line numbers in comments. Unfortunately, in versions <= 2.1.1, i
This issue was resolved in version 2.1.2.
In rare instances the [JSMin](http://code.google.com/p/minify/source/browse/tags/release_2.1.1/min/lib/JSMin.php#14) algorithm in versions <= 2.1.1 could be confused by regexes in certain contexts and throw an exception. The workaround was to simply wrap the expression in parenthesis. E.g.
```
In rare instances the [JSMin](https://github.com/mrclay/jsmin-php/blob/master/src/JSMin/JSMin.php) algorithm in versions <= 2.1.1 could be confused by regexes in certain contexts and throw an exception. The workaround was to simply wrap the expression in parenthesis. E.g.
```js
// in 2.1.1 and previous
return /'/; // JSMin throws error
return (/'/); // no error
@@ -124,6 +115,14 @@ Use Minify 2.1.4+. Before there was a setting to adjust the maximum allowed.
This may also appear as "Virtual Directory does not allow contents to be listed". Minify requires that the URI `/min/` (a request for a directory listing) result in the execution of `/min/index.php`. On Apache, you would make sure `index.php` is listed in the [DirectoryIndex directive](http://httpd.apache.org/docs/2.0/mod/mod_dir.html#directoryindex). IIS calls this the [Default Document](http://www.iis.net/ConfigReference/system.webServer/defaultDocument).
## "!WARN: environment : Local HTTP request failed. Testing cannot continue."
The `test_environment.php` unit test makes a few local HTTP requests to sniff for `zlib.output_compression` and other auto-encoding behavior, which may break Minify's output. This warning will appear if `allow_url_fopen` is disabled in php.ini, but **does not** necessarily mean there is a problem.
If Minify seems to work fine, ignore the warning. If Minify produces garbled output, enable `allow_url_fopen` in php.ini and re-run the tests. The tests may be able to tell you if PHP or your server is automatically encoding output.
Unless you need it in other scripts, disable `allow_url_fopen` once the issue is resolved. Minify does not need it.
## See Also
* [Debugging](Debugging.md)
* [Debugging](Debugging.wiki.md)

View File

@@ -1,5 +1,7 @@
# PHP5 Component Classes
(This information is not updated for version 3)
| **Class** | **Functionality** |
|:----------|:------------------|
| [Minify](http://code.google.com/p/minify/source/browse/min/lib/Minify.php) | Combine, process, and serve pieces of content (usually CSS/JS files). Almost all behavior is configurable including request handling (via [controllers](http://code.google.com/p/minify/source/browse/min/lib/Minify/Controller/)), HTTP headers & encoding, caching ([file/APC/memcached](http://code.google.com/p/minify/source/browse/min/lib/Minify/Cache/)), and compression functions (by default, the classes below) |

View File

@@ -1,21 +1,19 @@
Unless mentioned, all the following snippets go in `min/config.php`.
Unless mentioned, all the following snippets go in `config.php`.
## Faster Cache Performance
By default, Minify uses [Minify\_Cache\_File](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Cache/File.php). It uses `readfile`/`fpassthru` to improve performance over most file-based systems, but it's still file IO. I haven't done comparative benchmarks on all three, but APC/Memcache _should_ be faster. In all cases, Minify cache ids begin with `"minify_"`.
By default, Minify uses `Minify_Cache_File`. It uses `readfile`/`fpassthru` to improve performance over most file-based systems, but it's still file IO, so the following caching options should be faster. In all cases, Minify cache ids begin with `"minify_"`.
### APC
```
require 'lib/Minify/Cache/APC.php';
```php
$min_cachePath = new Minify_Cache_APC();
```
### Memcache
You must create and connect your Memcache object then pass it to `Minify_Cache_Memcache`'s constructor.
```
require 'lib/Minify/Cache/Memcache.php';
```php
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$min_cachePath = new Minify_Cache_Memcache($memcache);
@@ -23,30 +21,44 @@ $min_cachePath = new Minify_Cache_Memcache($memcache);
### Zend Platform
Patrick van Dissel has contributed a [cache adapter for Zend Platform](http://code.google.com/p/minify/issues/detail?id=167).
```php
$min_cachePath = new Minify_Cache_ZendPlatform();
```
### XCache
```php
$min_cachePath = new Minify_Cache_XCache();
```
### WinCache
```php
$min_cachePath = new Minify_Cache_WinCache();
```
## Closure Compiler API Wrapper
An [experimental wrapper for Google's closure compiler API](https://github.com/mrclay/minify/blob/master/min/lib/Minify/JS/ClosureCompiler.php) is available for compressing Javascript. If the API fails for any reason, JSMin is used as the default backup minifier.
```
$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');
```php
$min_serveOptions['minifiers'][Minify::TYPE_JS] = array('Minify_JS_ClosureCompiler', 'minify');
```
## YUICompressor
If your host can execute Java, you can use Minify's YUI Compressor wrapper. You'll need the latest [yuicompressor-x.x.x.jar](http://yuilibrary.com/downloads/#yuicompressor) and a temp directory. Place the .jar in `min/lib`, then:
```
If your host can execute Java, you can use Minify's YUI Compressor wrapper. You'll need the latest [yuicompressor-x.x.x.jar](https://github.com/yui/yuicompressor/releases) and a temp directory. Place the .jar in `min/lib`, then:
```php
function yuiJs($js) {
Minify_YUICompressor::$jarFile = __DIR__ . '/lib/yuicompressor-x.x.x.jar';
Minify_YUICompressor::$tempDir = '/tmp';
return Minify_YUICompressor::minifyJs($js);
}
$min_serveOptions['minifiers']['application/x-javascript'] = 'yuiJs';
$min_serveOptions['minifiers'][Minify::TYPE_JS] = 'yuiJs';
```
To use YUIC for CSS with fixed URIs:
```
```php
function yuiCss($css, $options) {
Minify_YUICompressor::$jarFile = __DIR__ . '/lib/yuicompressor-x.x.x.jar';
Minify_YUICompressor::$tempDir = '/tmp';
@@ -60,49 +72,31 @@ function yuiCss($css, $options) {
);
return $css;
}
$min_serveOptions['minifiers']['text/css'] = 'yuiCss';
```
### CSSmin PHP port
Minify has added Túbal Martín's [PHP port](https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port/blob/master/cssmin.php) of the YUI Compressor's CSSmin. While it is not completely integrated yet, you may try it out:
```
function yuiCssPort($css, $options) {
$compressor = new CSSmin();
$css = $compressor->run($css, 9999999);
$css = Minify_CSS_UriRewriter::rewrite(
$css,
$options['currentDir'],
isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT'],
isset($options['symlinks']) ? $options['symlinks'] : array()
);
return $css;
}
$min_serveOptions['minifiers']['text/css'] = 'yuiCssPort';
```
As of commit [218f37](https://github.com/mrclay/minify/commit/218f37fb44f9be2ea138cf9efb8b7f6dc84bad7f), this is easier:
```
$min_serveOptions['minifiers']['text/css'] = array('Minify_CSSmin', 'minify');
$min_serveOptions['minifiers'][Minify::TYPE_CSS] = 'yuiCss';
```
## JSMin+
Minify 2.1.3 comes with Tino Zijdel's [JSMin+](http://crisp.tweakblogs.net/blog/1665/a-new-javascript-minifier-jsmin+.html) 1.1. This is a full parser based on a port of [Narcissus](http://en.wikipedia.org/wiki/Narcissus_(JavaScript_engine)). To try it out:
```
$min_serveOptions['minifiers']['application/x-javascript'] = array('JSMinPlus', 'minify');
```php
$min_serveOptions['minifiers'][Minify::TYPE_JS] = array('JSMinPlus', 'minify');
```
This should yield smaller javascript files, but I've tested this only briefly. For production you may want to get the [latest version](http://crisp.tweakblogs.net/blog/cat/716) (you must rename it: `min/lib/JSMinPlus.php`).
Note: JSMin+ is memory intensive, so be prepared to up your memory limit. Also it has no [comment preservation](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/JSMin.php#10) as of 1.3, in case you rely on this.
Note: JSMin+ is memory intensive, so be prepared to up your memory limit. Also it does not preserve comments that begin with `/*!` like JSMin does.
## Legacy CSS compressor
In 3.x, Minify uses [CSSmin](https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port), a PHP port of the YUI CSS compressor. To use the compressor that came with Minify 2.x (not recommended), uncomment this line in your `config.php` file:
```php
//$min_serveOptions['minifiers'][Minify::TYPE_CSS] = array('Minify_CSS', 'minify');
```
## Server-specific Options
You may need to have different options depending on what server you're on. You can do this just how you'd expect:
```
```php
if ($_SERVER['SERVER_NAME'] == 'myTestingWorkstation') {
// testing
$min_allowDebugFlag = true;
@@ -127,7 +121,7 @@ If you test/develop sites in a subdirectory (e.g. `http://localhost/siteA/`), se
## Group-specific Options
In "group" requests, `$_GET['g']` holds the group key, so you can code based on it:
```
```php
if (isset($_GET['g'])) {
switch ($_GET['g']) {
case 'js' : $min_serveOptions['maxAge'] = 86400 * 7;
@@ -145,7 +139,7 @@ See CustomSource.
## Processing Output After Minification
If `$min_serveOptions['postprocessor']` is set to a callback, Minify will pass the minified content to this function with type as the second argument. This allows you to apply changes to your minified content without making your own custom minifier. E.g.:
```
```php
function postProcess($content, $type) {
if ($type === Minify::TYPE_CSS) {
require_once 'CssColorReplacer.php';

View File

@@ -1,153 +1,108 @@
Please see the UserGuide if you're just getting started with Minify. This guide is for more advanced users who wish to implement an HTTP server in PHP using the [Minify](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify.php) class.
Please see the UserGuide if you're just getting started with Minify. This guide is for more advanced users who wish to implement an HTTP server in PHP using the `Minify` class.
The basic steps are:
1. Set up the include\_path
1. Set up caching
1. Choose a Minify controller
1. Set up service and controller options
1. Handle the request
## Set up the include\_path
## Pull in Minify via Composer
In composer.json:
```
set_include_path('/path/to/min/lib' . PATH_SEPARATOR . get_include_path());
"require": {
"mrclay/minify": "~3"
},
```
## Set up caching
Minify ships with [cache classes](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Cache/) for files, APC, and memcache. Choose one, instantiate it, and pass it to Minify:
```bash
composer install
```
require 'Minify.php';
require 'Minify/Cache/File.php';
Minify::setCache(new Minify_Cache_File()); // files in directory chosen by Solar_Dir
## Set up autoloading, caching, and the Minify instance
Minify ships with several [cache classes](https://github.com/mrclay/minify/tree/master/lib/Minify/Cache) for files, APC, memcache, etc.:
```php
require __DIR__ . '/vendor/autoload.php';
$cache = new Minify_Cache_APC();
$minify = new Minify($cache);
```
## Create the environment and the factory for source objects
```php
$env = new Minify_Env();
$sourceFactory = new Minify_Source_Factory($env, [], $cache);
```
## Choose a Minify controller
Minify uses controller classes to analyze HTTP requests and determine which sources will make up the response. (The content isn't always returned; if the browser's cache is valid, Minify can return a 304 header instead).
Minify uses controller classes to analyze the environment (HTTP requests) and determine which sources will make up the response. (The content isn't always returned; if the browser's cache is valid, Minify can return a 304 header instead).
The [Files](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/Files.php#9) controller doesn't care about the HTTP request. It just specifies a given array of sources (file paths or [source objects](CustomSource.md)).
The `Files` controller doesn't care about the HTTP request. It just specifies a given array of sources (file paths or [source objects](CustomSource.md)).
The [Groups](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/Groups.php) controller uses `$_SERVER['PATH_INFO']` to choose from an array of source lists. There's an example at the end of this page.
The `Groups` controller uses `$_SERVER['PATH_INFO']` to choose from an array of source lists. There's an example at the end of this page.
The Files controller is simple, so we'll use it here.
```php
$controller = new Minify_Controller_Files($env, $sourceFactory);
```
## Set up service and controller options
A single array is used for configuration, and is passed to the `Minify::serve` method. `serve` passes it to the controller, which picks off the keys it needs and returns it to `serve` for Minify's own built-in [options](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify.php#88). This architecture allows the controller to set defaults for `serve`.
A single array is used for configuring both the behavior of `Minify::serve` (see the [default options](https://github.com/mrclay/minify/blob/master/lib/Minify.php#L73)) and the controller, which has its own option keys.
The Files controller only needs one key: `files`: the array of sources to be combined and served.
The only `serve` option we'll set is `maxAge` (the default is a measly 1800 seconds).
The only `serve` option we'll set is `maxAge` (the default is only 1800 seconds).
```
$options = array(
```php
$options = [
// options for the controller
'files' => array('//js/file1.js', '//js/file2.js', $src),
'files' => ['//js/file1.js', '//js/file2.js'],
// options for Minify::serve
'maxAge' => 86400
);
'maxAge' => 86400,
'minifierOptions' => [
'text/css' => [
'docRoot' => $env->getDocRoot(), // allows URL rewriting
],
],
];
```
(In the above $src is a [Minify\_Source object](CustomSource.md), which allows you to serve non-file content, and/or apply settings to individual sources.)
Note: `files` can also accept `Minify_Source` objects, which allow serving more than static files.
## Handle the request
```
Minify::serve('Files', $options);
```php
$minify->serve($controller, $options);
```
That's it...
Minify's default application (sometimes referred to as "min") is implemented this way, in the file [min/index.php](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/index.php). Most of its request handling is encapsulated in its own [MinApp](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Controller/MinApp.php#15) controller.
Minify's default application (`index.php`) is implemented similarly, but uses the `MinApp` controller. If you need URL rewriting in CSS files, you'll need to configure
# The Request Cycle
In handling a request, `Minify::serve` does a number of operations:
1. creates a controller object, unless you pass it a readymade object (let's call this `$ctrl`).
1. calls `$ctrl->setupSources($options)`, which analyzes the request and sets `$ctrl->sources` accordingly to an array of Minify\_Source objects.
1. calls `$ctrl->analyzeSources($options)`, which set `$options` keys for `contentType` and `lastModifiedTime`, based on the sources.
1. calls `$ctrl->mixInDefaultOptions($options)`, to mix the controller's default options with the user's.
1. Minify merges your given options with its default options
1. calls the controller's `createConfiguration()`, which analyzes the request and returns a `Minify_ServeConfiguration` object, encapsulating the source objects found.
1. uses `analyzeSources()` to determine the Content-Type and last modified time.
1. determines if the browser accepts gzip
1. validates the browser cache (optionally responding with a 304)
1. validates the server cache. If it needs refreshing, `Minify::_combineMinify` is called, which...
* calls `$source->getContent` on each source
* the content is combined before or after minification (depending on individual source options)
1. validates the server cache. If it needs refreshing, `combineMinify()` fetchs and combines the content of each source.
1. sets up headers to be sent
1. either returns the headers and content in an array (if `quiet` is set), or sends it to the browser.
# Using the Groups controller
The Groups controller uses `$_SERVER['PATH_INFO']` to select an array of sources from the given options:
```
$options = array(
'groups' => array(
'js' => array('//js/file1.js', '//js/file2.js'),
'css' => array('//css/file1.css', '//css/file2.css'),
),
);
Minify::serve('Groups', $options);
$options = [
'groups' => [
'js' => ['//js/file1.js', '//js/file2.js'],
'css' => ['//css/file1.css', '//css/file2.css'],
],
];
```
With the above, if you request `http://example.org/myServer.php/css`, Apache will set `$_SERVER['PATH_INFO'] = '/css'` and the sources in `$options['groups']['css']` will be served.
<a href='Hidden comment: Move somewhere else
== Sending far future Expires headers ==
By default Minify enables [http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers conditional GETs] for client-side caching, but in this model the browser has to continuously check back with the server to revalidate its cache. A better method is to send [http://developer.yahoo.com/performance/rules.html#expires far future Expires headers] and change the URL when the file changes. As long as you generate your HTML with PHP, Minify makes it easy to do this.
1. Move the "groups" configuration array into a separate file "_groupsConfig.php":
```
<?php
// configures both Minify::serve() and Minify_Build
return array(
"js1" => array("//js/yourFile1.js", "//js/yourFile2.js")
,"js2" => array("//js/yourFile1.js", "//js/yourFile3.js")
,"jQuery" => array("//js/jquery-1.2.6.js")
,"css" => array("//css/layout.css", "//css/fonts.css")
);
```
2. Adjust "min.php" to use this file:
```
Minify::serve("Groups", array(
"groups" => (require "_groupsConfig.php")
));
```
3. In your HTML-generating script, create Minify_Build objects for each minify URI you"re going to use, and, to each, apply the uri() method:
```
require "Minify/Build.php";
$_gc = (require "_groupsConfig.php");
$js1Build = new Minify_Build($_gc["js1"]);
$cssBuild = new Minify_Build($_gc["css"]);
echo "<link rel="stylesheet" type="text/css" href="" . $cssBuild->uri("/min.php/css") . "" />";
/* ... */
echo "<script type="text/javascript" src="" . $js1Build->uri("/min.php/js1") . ""></script>";
```
5. Open the (X)HTML page in your browser. The Javascript and CSS should "work".
6. View source. The minify URIs should look like: "/min.php/js1?##########" (a unix timestamp)
7. Now that our URI"s are synched with source file changes, we can safely send Expires headers. In "min.php":
```
Minify::serve("Groups", array(
"groups" => (require "_groupsConfig.php")
,"maxAge" => 31536000 // 1 yr
// in 2.0 was "setExpires" => $_SERVER["REQUEST_TIME"] + 31536000
));
```
Now "min.php" will serve files with Expires headers, causing the browser to always retrieve them from cache (until the expiration date).
When you make a change to any of your source Javascript/CSS files, your HTML file will have a different querystring appended to the minify URIs, causing the browser to download it as a new URL, and Minify will automatically rebuild its cache files on the server.
'></a>

View File

@@ -1,11 +1,12 @@
In `groupsConfig.php`, usually you specify source file paths using strings like `/path/to/file.js` or `//js/file1.js` (Minify expands this to `"{$_SERVER['DOCUMENT_ROOT']}/js/file1.js"` ).
Instead of a string, you may substitute a "source object" (an instance of class [Minify\_Source](http://code.google.com/p/minify/source/browse/tags/release_2.1.3/min/lib/Minify/Source.php)). This allows you to customize how minification is applied, and/or pull content from a non-file location (e.g. a URL).
Instead of a string, you may substitute an instance of class `Minify_Source`. This allows you to customize how minification is applied, and/or pull content from a non-file location (e.g. a URL).
### Example: filepath
In the `$spec` array, set the key `filepath` to produce a source based on a file path:
```
```php
$src1 = new Minify_Source(array(
'filepath' => '//js/file1.js',
));
@@ -13,15 +14,16 @@ $src2 = new Minify_Source(array(
'filepath' => '//js/file2.js',
));
return array(
'js' => array($src1, $src2)
);
return [
'js' => [$src1, $src2]
];
```
Note the above is functionally identical to:
```
return array(
'js' => array('//js/file1.js', '//js/file2.js')
);
```php
return [
'js' => ['//js/file1.js', '//js/file2.js'],
];
```
### Example: Specify a different minifier or none at all
@@ -30,26 +32,19 @@ To change minifier, set `minifier` to a [callback](http://php.net/manual/en/lang
**`*`Prepare for `groupsConfig.php` to be executed more than once.** (This is likely if you're using the functions in `/min/utils.php`.) In practice this just means making sure functions are conditionally defined if they don't already exist, etc.
```
if (! function_exists('myMin')) {
function myMin($js) {
require_once 'JSMinPlus.php';
return JSMinPlus::minify($js);
}
}
```php
$src1 = new Minify_Source(array(
'filepath' => '//js/file1.js',
'minifier' => 'myMin',
'minifier' => ['JSMinPlus', 'minify'],
));
$src2 = new Minify_Source(array(
'filepath' => '//js/file2.js',
'minifier' => '', // don't compress
));
```
In the above, `myMin()` is only called when rebuilding the cache. This way `JSMinPlus.php` is only loaded when needed.
In the above, `JSMinPlus.php` is only loaded when the contents of `$src1` is needed.
**`*`Do _not_ use [create\_function](http://php.net/manual/en/function.create-function.php) or anonymous functions for the minifier.** The internal names of these function tend to vary, causing Minify to create lots of [duplicate cache files](http://code.google.com/p/minify/issues/detail?id=138) (and perform poorly).
**`*`Do _not_ use `create_function()` or anonymous functions for the minifier.** The internal names of these function tend to vary, causing endless cache misses, killing performance and filling cache storage up.
## Non-File Sources
@@ -63,24 +58,23 @@ You're not limited to flat js/css files, but without `filepath`, the `$spec` arr
### Example: Content from a URL
Here we want to fetch javascript from a URL. We don't know when it will change, so we use a stepping expression to re-fetch it every midnight:
```
```php
if (! function_exists('src1_fetch')) {
function src1_fetch() {
return file_get_contents('http://example.org/javascript.php');
}
}
$src1 = new Minify_Source(array(
$src1 = new Minify_Source([
'id' => 'source1',
'getContentFunc' => 'src1_fetch',
'contentType' => Minify::TYPE_JS,
'lastModified' => ($_SERVER['REQUEST_TIME'] - $_SERVER['REQUEST_TIME'] % 86400),
));
]);
```
If you know that the URL content only depends on a few local files, you can use the maximum of their `mtime`s as the `lastModified` key:
```
...
$src1 = new Minify_Source(array(
```php
$src1 = new Minify_Source([
'id' => 'source1',
'getContentFunc' => 'src1_fetch',
'contentType' => Minify::TYPE_JS,
@@ -88,51 +82,55 @@ $src1 = new Minify_Source(array(
filemtime('/path/to/javascript.php')
,filemtime('/path/to/javascript_input.css')
),
));
]);
```
## Performance Considerations
Be aware that all the code you put in groupsConfig.php will be evaluated upon every request like `/min/g=...`, so make it as light as possible.
Be aware that all the code you put in `groupsConfig.php` will be evaluated upon every request like `/min/g=...`, so make it as light as possible.
If you wish to keep groupsConfig.php "clean", you can alternately create a separate PHP script that manually sets up sources, caching, options, and calls Minify::serve().
```
<?php // myServer.php
If you wish to keep `groupsConfig.php` "clean", you can alternately create a separate PHP script that manually sets up sources, caching, options, and calls Minify::serve().
```php
// myServer.php
/**
* This script implements a Minify server for a single set of sources.
* If you don't want '.php' in the URL, use mod_rewrite...
*/
require __DIR__ . '/vendor/autoload.php';
// setup Minify
set_include_path('path/to/min/lib' . PATH_SEPARATOR . get_include_path());
require 'Minify.php';
require 'Minify/Cache/File.php';
Minify::setCache(new Minify_Cache_File()); // guesses a temp directory
$cache = new Minify_Cache_File();
$minify = new Minify($cache);
$env = new Minify_Env();
$sourceFactory = new Minify_Source_Factory($env, [], $cache);
$controller = new Minify_Controller_Files($env, $sourceFactory);
function src1_fetch() {
return file_get_contents('http://example.org/javascript.php');
}
// setup sources
$sources = array();
$sources[] = new Minify_Source(array(
'id' => 'source1'
,'getContentFunc' => 'src1_fetch'
,'contentType' => Minify::TYPE_JS
,'lastModified' => max(
filemtime('/path/to/javascript.php')
,filemtime('/path/to/javascript_input.js')
)
));
$sources = [];
$sources[] = new Minify_Source([
'id' => 'source1',
'getContentFunc' => 'src1_fetch',
'contentType' => Minify::TYPE_JS,
'lastModified' => max(
filemtime('/path/to/javascript.php'),
filemtime('/path/to/javascript_input.js')
),
]);
$sources[] = '//file2.js';
$sources[] = '//file3.js';
// setup serve options
$options = array(
// setup serve and controller options
$options = [
'files' => $sources,
'maxAge' => 86400,
);
];
// handle request
Minify::serve('Files', $options);
```
$minify->serve($controller, $options);
```

View File

@@ -7,9 +7,9 @@
You can find details by enabling FirePHP logging:
1. Install/enable [FirePHP](https://addons.mozilla.org/en-US/firefox/addon/6149).
1. Open Firebug's console
1. Set `$min_errorLogger = true;` in min/config.php
1. Install/enable FirePHP for [Firefox](https://addons.mozilla.org/en-US/firefox/addon/6149) or [Chrome](https://chrome.google.com/webstore/detail/firephp4chrome/gpgbmonepdpnacijbbdijfbecmgoojma?hl=en-US).
1. Open the Chrome DevTools/Firebug console
1. Set `$min_errorLogger = true;` in config.php
1. Reload the Minify URL
Hopefully you'll see the error appear:
@@ -22,7 +22,7 @@ Minify: Something bad happened!
When Javascript errors occur, or URIs in CSS files are incorrectly rewritten, enable "debug mode" to ease debugging combined files:
1. Set `$min_allowDebugFlag = 'true'` in min/config.php
1. Set `$min_allowDebugFlag = 'true'` in config.php
1. Append `&debug` to the Minify URI. E.g. `/min/?f=script1.js,script2.js&debug` (or use the bookmarklet provided by /min/builder/)
In "debug mode":
@@ -34,7 +34,7 @@ In "debug mode":
Example: a combination of two Javascript files in debug mode
```
```js
/* firstFile.js */
/* 1 */ (function () {
@@ -70,7 +70,7 @@ traversals removed : /images/bg.jpg
### Tips for handling Javascript errors
* Use the latest version (2.1.4 beta as of Dec 2010)
* Try [debug mode](#Javascript/CSS_Problems.md) to make the combined file more readable (and error locations findable)
* Try [debug mode](#javascriptcss-problems) to make the combined file more readable (and error locations findable)
* Find out if other browsers have the same error
* For pre-minified files, make the filenames end in `.min.js` or `-min.js`, which will prevent Minify from altering them
* Test your scripts in [JSLint](http://www.jslint.com/).

View File

@@ -1,13 +1,3 @@
## Why do the CSS & HTML minifiers add so many line breaks?
TL;DR: Ignore them. They don't add to the output size and if you absolutely want all content on one line you will have to use another tool.
It's [rumored](https://github.com/yui/yuicompressor/blob/master/doc/README#L43) that some source control tools and old browsers don't like very long lines. Compressed files with shorter lines are also easier to diff.
Since both Minify classes are regex-based, it would be very difficult/error-prone to count characters then try to re-establish context to add line breaks. Instead, both classes trade 1 space for 1 line break (`\n`) wherever possible, adding breaks but without adding bytes.
If you can think of another safe & efficient way to limit lines in these two tools without adding bytes, please submit a patch, but this is not something anyone should be worrying about.
## Minify doesn't compress as much as product XYZ. Why not?
Out of the box, Minify uses algorithms available in PHP, which frankly aren't as solid as competing products, but I consider them _good enough_. At this point I don't have time to work on further tweaking, so if you must have _perfect_ minification you can explore the CookBook to plug in other minifiers. If you'd like to propose specific tweaks in the algorithm (and don't have a patch), please propose these in the Google Group, not the issue tracker.
@@ -43,24 +33,23 @@ Yes. Based on the browser's Accept-Encoding header, Minify will serve content en
## Does it work with PHP opcode caches like APC and eAccelerator?
Of course, and you can also use [APC for content caching](CookBook.md).
Of course, and you can also use [APC for content caching](CookBook.wiki.md).
## Can it minify remote files/the output of dynamic scripts?
[Yes](http://code.google.com/p/minify/wiki/CustomSource#Non-File_Sources), but it's not a straightforward setup, and probably best avoided.
[Yes](CustomSource.wiki.md#non-file-sources), but it's not a straightforward setup, and probably best avoided.
## Is there a minifier for HTML?
Yes, but only in the form of a PHP class: [Minify\_HTML](http://code.google.com/p/minify/source/browse/min/lib/Minify/HTML.php).
It also can accept callbacks to minify embedded STYLE and SCRIPT elements.
Yes, the class `Minify_HTML` does this. It also can accept callbacks to minify embedded STYLE and SCRIPT elements.
Since Minify\_HTML is not fast, there's no _easy way_ to integrate it into dynamic pages, and you'll have to search the archives for ideas of how to use it. One opportunity would be when storing HTML (assuming writes are infrequent); e.g., in a DB keep one copy for editing and one minified for serving.
Since Minify_HTML is not fast, there's no _easy way_ to integrate it into dynamic pages, and you'll have to search the archives for ideas of how to use it. One opportunity would be when storing HTML (assuming writes are infrequent); e.g., in a DB keep one copy for editing and one minified for serving.
Minify is not suited for _serving_ HTML pages on a site, though it can be done for small numbers of static pages. Look the the [Page controller](http://code.google.com/p/minify/source/browse/min/lib/Minify/Controller/Page.php).
Minify is not suited for _serving_ HTML pages on a site, though it can be done for small numbers of static pages. Look at `Minify_Controller_Page`.
## How does it ensure that the client can't request files it shouldn't have access to?
In 2.1, by default, Minify allows files to be specified using the URI, or using pre-configured sets of files. With URI-specified files, Minify is [very careful](Security.md) to serve only JS/CSS files that are already public on your server, but if you hide public directories--with .htaccess, e.g.--Minify can't know that. Obvious Tip: don't put sensitive info in JS/CSS files inside DOC\_ROOT :)
In 2.1, by default, Minify allows files to be specified using the URI, or using pre-configured sets of files. With URI-specified files, Minify is [very careful](Security.wiki.md) to serve only JS/CSS files that are already public on your server, but if you hide public directories--with .htaccess, e.g.--Minify can't know that. Obvious Tip: don't put sensitive info in JS/CSS files inside DOC\_ROOT :)
An included option can disable URI-specified files so Minify will serve only the pre-configured file sets.
@@ -70,10 +59,10 @@ I'd love to know. 2.1.1 had 54K downloads and I know the library is powering sev
## Can I use it with my commercial website or product?
Yes. Minify is distributed under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php), which means that you're free to use, modify, and redistribute Minify or derivative works thereof, even for commercial purposes, as long as you comply with a few simple requirements. See the [LICENSE.txt](http://code.google.com/p/minify/source/browse/LICENSE.txt) file for details.
Yes. Minify is distributed under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php), which means that you're free to use, modify, and redistribute Minify or derivative works thereof, even for commercial purposes, as long as you comply with a few simple requirements. See the [LICENSE.txt](https://github.com/mrclay/minify/blob/master/LICENSE.txt) file for details.
## How can I tell if my server cache is working?
The easiest way is to place a Minify URL directly in your browser's address bar and refresh (F5), which should override the client-side caching that Minify specifies and force Minify to send you a complete response. With cache working, this response should take 100ms or so. Without cache, multiple seconds. (You can get accurate response times using an HTTP inspector like Firebug.)
The easiest way is to place a Minify URL directly in your browser's address bar and refresh (F5), which should override the client-side caching that Minify specifies and force Minify to send you a complete response. With cache working, this response should take 100ms or so. Without cache, it could be multiple seconds.
If you have file access to the server you can check your cache path directly for filenames beginning with "minify
If you have file access to the server you can check your cache path directly for filenames beginning with `minify_`.

View File

@@ -1,14 +1,14 @@
"Min" is the application included in Minify that handles requests to `http://example.com/min/` and responds with compressed/combined content.
"Min" is the front end application `index.php` that handles requests to `http://example.com/min/` and responds with compressed/combined content.
When the documentation refers to "Minify" it usually means this application, but sometimes refers to the ComponentClasses.
When the documentation refers to "Minify" it usually means this application, but sometimes refers to the [ComponentClasses](ComponentClasses.wiki.md).
User-configurable files:
* `/min/config.php`: general configuration
* `/min/groupsConfig.php`: configuration of pre-defined groups of files
* `/config.php`: general configuration
* `/groupsConfig.php`: configuration of pre-defined groups of files
Other files of interest:
* `/min/.htaccess`: rewrites URLs for the front controller
* `/min/index.php`: front controller
* `/min/lib/Minify/Controller/MinApp.php`: determines which files are combined based on `$_GET`, sets some default options
* `/.htaccess`: rewrites URLs for the front controller
* `/index.php`: front controller
* `/lib/Minify/Controller/MinApp.php`: determines which files are combined based on `$_GET`, sets some default options

View File

@@ -1,6 +1,6 @@
# Unit Testing
0. If you haven't already, install Minify using the UserGuide.
0. If you haven't already, install Minify using the [UserGuide](UserGuide.wiki.md).
1. Copy the "min\_unit\_tests" directory directly into your DOCUMENT\_ROOT.
@@ -10,10 +10,3 @@ You should see a list of "PASS"es. You can run the individual test PHP files in
## Common Problems
### !WARN: environment : Local HTTP request failed. Testing cannot continue.
[test\_environment.php](http://code.google.com/p/minify/source/browse/min_unit_tests/test_environment.php) makes a few local HTTP requests to sniff for `zlib.output_compression` and other auto-encoding behavior, which may break Minify's output. This warning will appear if `allow_url_fopen` is disabled in php.ini, but **does not** necessarily mean there is a problem.
If Minify seems to work fine, ignore the warning. If Minify produces garbled output, enable `allow_url_fopen` in php.ini and re-run the tests. The tests may be able to tell you if PHP or your server is automatically encoding output.
Unless you need it in other scripts, disable `allow_url_fopen` once the issue is resolved. Minify does not need it.

View File

@@ -12,24 +12,24 @@ When Minify serves this content (from `http://example.org/min/f=theme/fashion/st
body{background:url(/theme/fashion/bg.jpg)}
```
You can see the steps used to rewrite your URIs by enabling [debug mode](Debugging.md).
You can see the steps used to rewrite your URIs by enabling [debug mode](Debugging.wiki.md).
## Disable Rewriting
You can disable the automatic rewriting by setting this in min/config.php:
```
You can disable the automatic rewriting by setting this in config.php:
```php
$min_serveOptions['rewriteCssUris'] = false;
```
## Manual Rewriting
You can manually rewrite relative URIs in CSS in a couple ways. The simplest is to prepend a string to each relative URI:
```
```php
$min_serveOptions['rewriteCssUris'] = false;
$min_serveOptions['minifierOptions']['text/css']['prependRelativePath'] = '/css/';
$min_serveOptions['minifierOptions'][MINIFY::TYPE_CSS]['prependRelativePath'] = '/css/';
```
Or you can run the minified output through a custom [post-processor](CookBook#Processing_Output_After_Minification.md) function.
Or you can run the minified output through a custom [post-processor](CookBook.wiki.md#Processing_Output_After_Minification.md) function.
## Document Root Confusion
@@ -44,8 +44,8 @@ Whether you use [aliases](http://httpd.apache.org/docs/2.2/mod/mod_alias.html),
| Apache mod\_alias | `Alias /static /etc/static_content` |
| ...or symlink | `ln -s /etc/static_content /var/www/static` |
In `/min/config.php` you'll need the following:
```
In `/config.php` you'll need the following:
```php
// map URL path to file path
$min_symlinks = array(
'//static' => '/etc/static_content'
@@ -54,7 +54,7 @@ $min_symlinks = array(
This lets Minify know during the rewriting process that an internal file path starting with `/etc/static_content` should be rewritten as a public URI beginning with `/static`.
If your alias target directory is outside of DOC\_ROOT, you'll also need to explicitly allow Minify to serve files from it:
```
```php
$min_serveOptions['minApp']['allowDirs'] = array(
'//', // allow from the normal DOC_ROOT
'/etc/static_content' // allow from our alias target
@@ -67,7 +67,7 @@ You can enable the script `min/server-info.php` and open http://example.org/min/
## It's still not working
1. Make sure you have the [latest version](http://code.google.com/p/minify/downloads/list).
1. Enable [debug mode](Debugging.md), which will show you the URI transformation process.
1. Make sure you have the latest version.
1. Enable [debug mode](Debugging.wiki.md), which will show you the URI transformation process.
1. Check that `$_SERVER['DOCUMENT_ROOT']` is a real directory path. If not, URI rewriting will fail. If you cannot fix this in httpd.conf, etc., use the [configuration option](http://code.google.com/p/minify/source/browse/min/config.php?r=292#47).
1. Paste your [debug mode](Debugging.md) comment block into a new post on the [minify mailing list](http://groups.google.com/group/minify).
1. Paste your [debug mode](Debugging.wiki.md) comment block into a new post on the [minify mailing list](http://groups.google.com/group/minify).

View File

@@ -1,48 +1,131 @@
If this page doesn't help, please post a question on our [Google group](http://groups.google.com/group/minify).
# Installing Minify for the first time
# Creating Minify URLs
1. Clone the [minify git repository](https://github.com/mrclay/minify).
1. The distribution contains a folder "min". Copy this into your DOCUMENT\_ROOT so it is a **direct child** of DOCUMENT\_ROOT (e.g. `http://example.com/min/`). Document roots are usually named `htdocs`, `public_html`, or `www`.
1. Test it can serve content: http://example.com/min/?f=min/quick-test.js and http://example.com/min/?f=min/quick-test.css
1. If you want to use the BuilderApp, you must enable it in `min/config.php`.
Let's say you want to serve the file http://example.com/css/foo/bar.css
Note: The BuilderApp will not function properly in subdirectories, but it's not necessary for Minify's functionality.
You would use the URL http://example.com/min/?f=css/foo/bar.css
Done!
In other words, the "f" argument is set to the file path from root without the initial `/`. As CSS files may contain relative URIs, Minify will automatically "fix" these by rewriting them as root relative.
(Optional) See TestingMinify if you'd like to run unit tests.
To combine multiple files, separate the paths given to "f" with commas.
### Hosting on Lighttpd
Let's say you have CSS files at these URLs:
Minify comes with Apache mod\_rewrite rules, but this does the same for Lighttpd:
* http://example.com/scripts/library-1.5.js
* http://example.com/scripts/site.js
```
url.rewrite-once = ( "^/min/([a-z]=.*)" => "/min/index.php?$1" )
You'd use the URL http://example.com/min/?f=scripts/library-1.5.js,scripts/site.js
## Shortening URLs with common directories
If you're combining files that share the same ancestor directory, you can use the "b" argument to set the base directory for the "f" argument. Do not include the leading or trailing `/` characters.
E.g., the following URLs will serve the exact same content:
* http://example.com/min/?f=path/to/scripts/library-1.5.js,path/to/scripts/foo/site.js
* http://example.com/min/?b=path/to/scripts&f=library-1.5.js,site.js,home.js
# Limiting access to directories
By default, Minify will serve any CSS/JS files within the DOCUMENT_ROOT. If you'd prefer to limit Minify's access to certain directories, set the `$min_serveOptions['minApp']['allowDirs']` array in config.php. E.g. to limit to the `/js` and `/themes/default` directories, use:
```php
$min_serveOptions['minApp']['allowDirs'] = ['//js', '//themes/default'];
```
# Usage
# Using groups for nicer URLs
Enable the BuilderApp via your [config file](https://github.com/mrclay/minify/blob/master/min/config.php#L10). The default password is "admin", but even if no password is used there's very little server information disclosed.
For nicer URLs, edit groupsConfig.php to pre-specify groups of files to be combined under preset keys. E.g., here's an example configuration in groupsConfig.php:
Browse to http://example.com/min/
```php
return [
'js' => ['//js/Class.js', '//js/email.js'],
];
```
This pre-selects the following files to be combined under the key "js":
* http://example.com/js/Class.js
* http://example.com/js/email.js
You can now serve these files with http://example.com/min/?g=js
## Specifying files outside the document root
In the groupsConfig.php array, the `//` in the file paths is a shortcut for the DOCUMENT_ROOT, but you can also specify paths from the root of the filesystem or relative to the DOC_ROOT:
```php
return [
'js' => [
'//js/file.js', // file within DOC_ROOT
'//../file.js', // file in parent directory of DOC_ROOT
'C:/Users/Steve/file.js', // file anywhere on filesystem
],
];
```
## Multiple groups and files in one URL
E.g.: http://example.com/min/?g=js&f=more/scripts.js
Separate group keys with commas: http://example.com/min/?g=baseCss,css1&f=moreStyles.css
## Creating URLs with the Builder
Enable the [BuilderApp](BuilderApp.wiki.md) via config.php. The default password is "admin", but even if no password is used there's very little server information disclosed.
Browse to http://example.com/min/builder/
The Minify URI Builder will help you create URIs you can use to minify existing files on your site. You can see screenshots and get a feel for this process from this [walkthrough on mrclay.org](http://mrclay.org/index.php/2008/09/19/minify-21-on-mrclayorg/)
More info here: https://github.com/mrclay/minify/blob/master/MIN.txt
You may want to disable the BuilderApp when not in use.
You may want to disable the [BuilderApp](BuilderApp.wiki.md) when not in use.
# Far-future Expires headers
Minify can send far-future (one year) Expires headers. To enable this you must add a number or the parameter "v" to the querystring (e.g. `/min/?g=js&1234` or `/min/?g=js&v=1234`) and alter it whenever a source file is changed. If you have a build process you can use a build/source control revision number.
You can alternately use the utility function `Minify_getUri()` to get a "versioned" Minify URI for use in your HTML (it sniffs the `mtime` of the files). E.g.:
```php
require 'path/to/min/utils.php';
$jsUri = Minify_getUri('js'); // a key in groupsConfig.php
echo "<script src='{$jsUri}'></script>";
$cssUri = Minify_getUri([ // a list of files
'//css/styles1.css',
'//css/styles2.css',
]);
echo "<link rel=stylesheet href='{$cssUri}'>";
```
# Debug mode
In debug mode, instead of compressing files, Minify sends combined files with comments prepended to each line to show the line number in the original source file. To enable this, set `$min_allowDebugFlag` to `true` in config.php and append `&debug=1` to your URIs. E.g. `/min/?f=script1.js,script2.js&debug=1`
Known issue: files with comment-like strings/regexps can cause problems in this mode.
# Configuration
[min/config.php](https://github.com/mrclay/minify/blob/master/min/config.php) holds general config options.
See [config.php](https://github.com/mrclay/minify/blob/master/config.php) for general config options.
[min/groupsConfig.php](https://github.com/mrclay/minify/blob/master/min/groupsConfig.php) holds preset groups of files to minify. (The builder application can help with this).
[groupsConfig.php](https://github.com/mrclay/minify/blob/master/groupsConfig.php) holds preset groups of files to minify. (The builder application can help with this).
CookBook shows how to customize settings between production/development environments, and between groups.
[CookBook](CookBook.wiki.md) shows how to customize settings between production/development environments, and between groups.
CustomSource shows how to set some file/source-specific options, or serve content from a PHP script or URL.
[CustomSource](CustomSource.wiki.md) shows how to set some file/source-specific options, or serve content from a PHP script or URL.
### Hosting on Lighttpd
Minify comes with Apache mod_rewrite rules, but this does the same for Lighttpd:
```
url.rewrite-once = ( "^/min/([a-z]=.*)" => "/min/index.php?$1" )
```
# Problems?
See [CommonProblems](https://github.com/mrclay/minify/blob/master/docs/CommonProblems.wiki.md) and [Debugging](https://github.com/mrclay/minify/blob/master/docs/Debugging.wiki.md). You might also try [TestingMinify](https://github.com/mrclay/minify/blob/master/docs/TestingMinify.wiki.md) (running `test_environment.php` in particular).
See [CommonProblems](CommonProblems.wiki.md) and [Debugging](Debugging.wiki.md). You might also try [TestingMinify](TestingMinify.wiki.md) (running `test_environment.php` in particular).

View File

@@ -85,7 +85,7 @@ class Minify {
'minifiers' => array(
Minify::TYPE_JS => array('JSMin\\JSMin', 'minify'),
Minify::TYPE_CSS => array('Minify_CSS', 'minify'),
Minify::TYPE_CSS => array('Minify_CSSmin', 'minify'),
Minify::TYPE_HTML => array('Minify_HTML', 'minify'),
),
'minifierOptions' => array(), // no minifier options
@@ -293,7 +293,7 @@ class Minify {
if ($this->options['contentType'] === self::TYPE_JS) {
$source->setMinifier("");
} elseif ($this->options['contentType'] === self::TYPE_CSS) {
$source->setMinifier(array('Minify_CSS', 'minify'));
$source->setMinifier(array('Minify_CSSmin', 'minify'));
$sourceOpts = $source->getMinifierOptions();
$sourceOpts['compress'] = false;
$source->setMinifierOptions($sourceOpts);

View File

@@ -13,6 +13,8 @@
* @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 {

View File

@@ -13,10 +13,18 @@
* including the ie5/mac filter (and its inversion), but expect tricky
* hacks involving comment tokens in 'content' value strings to break
* minimization badly. A test suite is available.
*
*
* Note: This replaces a lot of spaces with line breaks. It's rumored
* (https://github.com/yui/yuicompressor/blob/master/README.md#global-options)
* that some source control tools and old browsers don't like very long lines.
* 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 {

View File

@@ -52,7 +52,7 @@ class Minify_Controller_Page extends Minify_Controller_Base {
if (isset($options['minifyAll'])) {
// this will be the 2nd argument passed to Minify_HTML::minify()
$sourceSpec['minifyOptions'] = array(
'cssMinifier' => array('Minify_CSS', 'minify')
'cssMinifier' => array('Minify_CSSmin', 'minify')
,'jsMinifier' => array('JSMin\\JSMin', 'minify')
);
unset($options['minifyAll']);

View File

@@ -34,7 +34,7 @@ if (isset($_POST['method']) && $_POST['method'] === 'Minify and serve') {
$sourceSpec['minifyOptions']['jsMinifier'] = array('JSMin\\JSMin', 'minify');
}
if (isset($_POST['minCss'])) {
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSS', 'minify');
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSSmin', 'minify');
}
$source = new Minify_Source($sourceSpec);
Minify_Logger::setLogger(FirePHP::getInstance(true));
@@ -50,14 +50,14 @@ if (isset($_POST['method']) && $_POST['method'] === 'Minify and serve') {
}
$tpl = array();
$tpl['classes'] = array('Minify_HTML', 'JSMin\\JSMin', 'Minify_CSS', 'Minify_CSSmin', 'JSMinPlus');
$tpl['classes'] = array('Minify_HTML', 'JSMin\\JSMin', 'Minify_CSS', 'Minify_CSS', 'JSMinPlus');
if (isset($_POST['method']) && in_array($_POST['method'], $tpl['classes'])) {
$args = array($textIn);
if ($_POST['method'] === 'Minify_HTML') {
$args[] = array(
'cssMinifier' => array('Minify_CSS', 'minify')
'cssMinifier' => array('Minify_CSSmin', 'minify')
,'jsMinifier' => array('JSMin\\JSMin', 'minify')
);
}

View File

@@ -99,7 +99,7 @@ if (isset($_POST['url'])) {
$sourceSpec['minifyOptions']['jsMinifier'] = array('JSMin\\JSMin', 'minify');
}
if (isset($_POST['minCss'])) {
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSS', 'minify');
$sourceSpec['minifyOptions']['cssMinifier'] = array('Minify_CSSmin', 'minify');
}
}

View File

@@ -7,12 +7,8 @@ name="description" content="A demonstration of what can be accomplished visually
name="robots" content="all" /><title>css Zen Garden: The Beauty in CSS Design</title> <script type="text/javascript">var is={ie:navigator.appName=='Microsoft Internet Explorer',java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=='Win32'}
is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}</script> <script type="text/javascript">/*<![CDATA[*/var i=0;while(++i<10)
{}/*]]>*/</script> <script type="text/javascript">i=1;</script> <script type="text/javascript">/*<![CDATA[*/(i<1);/*]]>*/</script> <!--[if IE 6]><style type="text/css">/*<![CDATA[*/
/*! copyright: you'll need CDATA for this < & */
body{background:white}/*]]>*/</style><![endif]--><style type="text/css" title="currentStyle" media="screen">@import "/001/001.css";/*\*/css
hack{}/**/ /*/*/css
hack{}/**/css
hack{display/**/:/**/none;display:none}</style><link
{}/*]]>*/</script> <script type="text/javascript">i=1;</script> <script type="text/javascript">/*<![CDATA[*/(i<1);/*]]>*/</script> <!--[if IE 6]><style type="text/css">/*<![CDATA[*//*! copyright: you'll need CDATA for this < & */
body{background:white}/*]]>*/</style><![endif]--><style type="text/css" title="currentStyle" media="screen">@import "/001/001.css";/*\*//**/css hack{display:none;display:none}</style><link
rel="Shortcut Icon"
type="image/x-icon"
href="http://www.csszengarden.com/favicon.ico" /><link

View File

@@ -7,12 +7,8 @@ name="description" content="A demonstration of what can be accomplished visually
name="robots" content="all"><title>css Zen Garden: The Beauty in CSS Design</title> <script type="text/javascript">var is={ie:navigator.appName=='Microsoft Internet Explorer',java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=='Win32'}
is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}</script> <script type="text/javascript">var i=0;while(++i<10)
{}</script> <script type="text/javascript">i=1;</script> <script type="text/javascript">(i<1);</script> <!--[if IE 6]><style type="text/css">
/*! copyright: you'll need CDATA for this < & */
body{background:white}</style><![endif]--><style type="text/css" title="currentStyle" media="screen">@import "/001/001.css";/*\*/css
hack{}/**/ /*/*/css
hack{}/**/css
hack{display/**/:/**/none;display:none}</style><link
{}</script> <script type="text/javascript">i=1;</script> <script type="text/javascript">(i<1);</script> <!--[if IE 6]><style type="text/css">/*! copyright: you'll need CDATA for this < & */
body{background:white}</style><![endif]--><style type="text/css" title="currentStyle" media="screen">@import "/001/001.css";/*\*//**/css hack{display:none;display:none}</style><link
rel="Shortcut Icon"
type="image/x-icon"
href="http://www.csszengarden.com/favicon.ico"><link

View File

@@ -1,5 +1,2 @@
@import url(/more.css);body,td,th{font-family:Verdana,"Bitstream Vera Sans",Arial Narrow,sans-serif;font-size:12px}.nav{margin-left:20%}#main-nav{background-color:red;border:1px
solid #0f7}div#content
h1+p{padding-top:0;margin-top:0}@media all and (min-width: 640px){#media-queries-1{background-color:#0f0}}@media screen and (max-width: 2000px){#media-queries-2{background-color:#0f0}}
/*! YUI Compressor style comments are preserved */
body{background:#fff url(/path/to/image.gif) repeat-y}
@import url(/more.css);body,td,th{font-family:Verdana,"Bitstream Vera Sans",Arial Narrow,sans-serif;font-size:12px}.nav{margin-left:20%}#main-nav{background-color:red;border:1px solid #0f7}div#content h1+p{padding-top:0;margin-top:0}@media all and (min-width:640px){#media-queries-1{background-color:#0f0}}@media screen and (max-width:2000px){#media-queries-2{background-color:#0f0}}/*! YUI Compressor style comments are preserved */
body{background:#fff url(/path/to/image.gif) repeat-y}

View File

@@ -56,7 +56,7 @@ function test_Minify()
}
assertTrue(
! class_exists('Minify_CSS', false)
! class_exists('Minify_CSSmin', false)
,'Minify : minifier classes aren\'t loaded for 304s'
);

View File

@@ -10,7 +10,7 @@ function test_HTML()
$time = microtime(true);
$minOutput = Minify_HTML::minify($src, array(
'cssMinifier' => array('Minify_CSS', 'minify')
'cssMinifier' => array('Minify_CSSmin', 'minify')
,'jsMinifier' => array('JSMin\\JSMin', 'minify')
));
$time = microtime(true) - $time;
@@ -33,7 +33,7 @@ function test_HTML()
$time = microtime(true);
$minOutput = Minify_HTML::minify($src, array(
'cssMinifier' => array('Minify_CSS', 'minify')
'cssMinifier' => array('Minify_CSSmin', 'minify')
,'jsMinifier' => array('JSMin\\JSMin', 'minify')
));
$time = microtime(true) - $time;