PluginProbe
WP Coder – Insert & Manage Code Snippets / 4.1
WP Coder – Insert & Manage Code Snippets v4.1
4.5.1 1.1 2.3.1 2.3.2 2.4.1 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.1 3.1.1 3.2 3.2.1 3.3 3.4 3.5 3.5.1 All 39 releases
wp-coder / classes / Optimization / JSMinifier.php

JSMinifier.php in WP Coder – Insert & Manage Code Snippets 4.1, at classes/Optimization/JSMinifier.php

38 lines 1.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 }