Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/phabricator
Path: blob/master/externals/JsShrink/jsShrink.php
12232 views
1
<?php
2
/** Remove spaces and comments from JavaScript code
3
* @param string code with commands terminated by semicolon
4
* @return string shrinked code
5
* @link http://vrana.github.com/JsShrink/
6
* @author Jakub Vrana, http://www.vrana.cz/
7
* @copyright 2007 Jakub Vrana
8
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
9
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
10
*/
11
function jsShrink($input) {
12
return preg_replace_callback('(
13
(?:
14
(^|[-+\([{}=,:;!%^&*|?~]|/(?![/*])|return|throw) # context before regexp
15
(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
16
(/(?![/*])(?:
17
\\\\[^\n]
18
|[^[\n/\\\\]++
19
|\[(?:\\\\[^\n]|[^]])++
20
)+/) # regexp
21
|(^
22
|\'(?:\\\\.|[^\n\'\\\\])*\'
23
|"(?:\\\\.|[^\n"\\\\])*"
24
|([0-9A-Za-z_$]+)
25
|([-+]+)
26
|.
27
)
28
)(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
29
)sx', 'jsShrinkCallback', "$input\n");
30
}
31
32
function jsShrinkCallback($match) {
33
static $last = '';
34
$match += array_fill(1, 5, null); // avoid E_NOTICE
35
list(, $context, $regexp, $result, $word, $operator) = $match;
36
if ($word != '') {
37
$result = ($last == 'word' ? "\n" : ($last == 'return' ? " " : "")) . $result;
38
$last = ($word == 'return' || $word == 'throw' || $word == 'break' ? 'return' : 'word');
39
} elseif ($operator) {
40
$result = ($last == $operator[0] ? "\n" : "") . $result;
41
$last = $operator[0];
42
} else {
43
if ($regexp) {
44
$result = $context . ($context == '/' ? "\n" : "") . $regexp;
45
}
46
$last = '';
47
}
48
return $result;
49
}
50
51