forked from gpbmike/PHP-YUI-Compressor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyuicompressor.php
105 lines (83 loc) · 2.92 KB
/
yuicompressor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
class YUICompressor
{
// absolute path to YUI jar file.
private static $JAR_PATH;
private static $TEMP_FILES_DIR;
private $options = array('type' => 'js',
'linebreak' => false,
'verbose' => false,
'nomunge' => false,
'semi' => false,
'nooptimize' => false);
private $files = array();
private $string = '';
// construct with a path to the YUI jar and a path to a place to put temporary files
function __construct($JAR_PATH, $TEMP_FILES_DIR, $options = array())
{
$this->JAR_PATH = $JAR_PATH;
$this->TEMP_FILES_DIR = $TEMP_FILES_DIR;
foreach ($options as $option => $value)
{
$this->setOption($option, $value);
}
}
// set one of the YUI compressor options
function setOption($option, $value)
{
$this->options[$option] = $value;
}
// add a file (absolute path) to be compressed
function addFile($file)
{
array_push($this->files, $file);
}
// add a strong to be compressed
function addString($string)
{
$this->string .= ' ' . $string;
}
// the meat and potatoes, executes the compression command in shell
function compress()
{
// read the input
foreach ($this->files as $file) {
$this->string .= file_get_contents($file) or die("Cannot read from uploaded file");
}
// create single file from all input
$input_hash = sha1($this->string);
$file = $this->TEMP_FILES_DIR . '/' . $input_hash . '.txt';
$fh = fopen($file, 'w') or die("Can't create new file");
fwrite($fh, $this->string);
fclose($fh);
// start with basic command
$cmd = "java -Xmx32m -jar " . escapeshellarg($this->JAR_PATH) . ' ' . escapeshellarg($file) . " --charset UTF-8";
// set the file type
$cmd .= " --type " . (strtolower($this->options['type']) == "css" ? "css" : "js");
// and add options as needed
if ($this->options['linebreak'] && intval($this->options['linebreak']) > 0) {
$cmd .= ' --line-break ' . intval($this->options['linebreak']);
}
if ($this->options['verbose']) {
$cmd .= " -v";
}
if ($this->options['nomunge']) {
$cmd .= ' --nomunge';
}
if ($this->options['semi']) {
$cmd .= ' --preserve-semi';
}
if ($this->options['nooptimize']) {
$cmd .= ' --disable-optimizations';
}
// execute the command
exec($cmd . ' 2>&1', $raw_output);
// add line breaks to show errors in an intelligible manner
$flattened_output = implode("\n", $raw_output);
// clean up (remove temp file)
unlink($file);
// return compressed output
return $flattened_output;
}
}
?>