openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

JSMinifier.class.php (1639B)


      1 <?php
      2 
      3 namespace util;
      4 
      5 class JSMinifier
      6 {
      7 	const FLAG_IMPORT_MIN_JS            = 1;
      8 	const FLAG_REMOVE_MULTILINE_COMMENT = 2;
      9 	const FLAG_REMOVE_BLANK_LINES       = 4;
     10 	const FLAG_REMOVE_LINE_COMMENTS     = 8;
     11 	const FLAG_REMOVE_WHITESPACE        = 16;
     12 	const FLAG_REMOVE_LINEBREAK         = 32;
     13 	const FLAG_REMOVE_TABS              = 64;
     14 	const FLAG_REMOVE_SUPERFLOUS_SPACES = 128;
     15 	const FLAG_ALL                      = 255;
     16 
     17 	const REPLACER = [
     18 		self::FLAG_REMOVE_MULTILINE_COMMENT => ["/\/\*[\s\S]*?\*\//"           , ''               ],
     19 		self::FLAG_REMOVE_LINE_COMMENTS     => ["/^(.*)\/\/.*$/m"              ,'${1}'            ],
     20 		self::FLAG_REMOVE_BLANK_LINES       => ['/^\n+|^[\t\s]*\n+/m'          , ''               ],
     21 		self::FLAG_IMPORT_MIN_JS            => ['/^(import.*from.*)\.js(.*)$/m','${1}.min.js${2}' ],
     22 		self::FLAG_REMOVE_WHITESPACE        => ['/^\s*(.*)\s*$/m'              ,'${1}'            ],
     23 		self::FLAG_REMOVE_LINEBREAK         => ['/\n/'                         ,''                ],
     24 		self::FLAG_REMOVE_TABS              => ['/\t/'                         ,''                ],
     25 		self::FLAG_REMOVE_SUPERFLOUS_SPACES => ['/\s{2,}7'                     ,' '               ],
     26 	];
     27 
     28 	/**
     29 	 * Which flags are enabled?
     30 	 * @var int
     31 	 */
     32 	public $config = self::FLAG_ALL;
     33 
     34 	public function __construct( $flags = null )
     35 	{
     36 		if   ( $flags )
     37 			$this->config = $flags;
     38 	}
     39 
     40 
     41 	public function minify( $code ) {
     42 		foreach( self::REPLACER as $flag => $replacer )
     43 			if   ( $this->config & $flag ) {
     44 				list( $replace, $with ) = $replacer;
     45 				$code = preg_replace( $replace, $with, $code );
     46 			}
     47 		return $code;
     48 	}
     49 }