| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPCoder\Optimization; |
| 4 |
|
| 5 |
// Exit if accessed directly. |
| 6 |
defined( 'ABSPATH' ) || exit; |
| 7 |
|
| 8 |
class JSMinifier { |
| 9 |
|
| 10 |
public static function minify( $input ): string { |
| 11 |
if ( trim( $input ) === "" ) { |
| 12 |
return $input; |
| 13 |
} |
| 14 |
|
| 15 |
return preg_replace( |
| 16 |
array( |
| 17 |
// Remove comment(s) |
| 18 |
'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#', |
| 19 |
// Remove white-space(s) outside the string and regex |
| 20 |
'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s', |
| 21 |
// Remove the last semicolon |
| 22 |
'#;+\}#', |
| 23 |
// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}` |
| 24 |
'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i', |
| 25 |
// --ibid. From `foo['bar']` to `foo.bar` |
| 26 |
'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i' |
| 27 |
), |
| 28 |
array( |
| 29 |
'$1', |
| 30 |
'$1$2', |
| 31 |
'}', |
| 32 |
'$1$3', |
| 33 |
'$1.$3' |
| 34 |
), |
| 35 |
$input ); |
| 36 |
} |
| 37 |
|
| 38 |
} |