/
ResourceBuilder.php
652 lines (566 loc) · 15.6 KB
/
ResourceBuilder.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
<?php
/**
* Builds a resource from several other ones.
*
* @version $Id: builder.php 577 2015-01-07 03:54:49Z PointedEars $
* @author
* Copyright © 2011 Thomas 'PointedEars' Lahn <php@PointedEars.de>
*
* Part of PointedEars' JavaScript Extensions (JSX)
*
* JSX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JSX. If not, see <http://www.gnu.org/licenses/>.
*/
if (!function_exists('lcfirst'))
{
function lcfirst ($name)
{
return strtolower(substr($name, 0, 1)) . substr($name, 1);
}
}
/**
* Builds a resource from several other ones.
*
* Information is passed via <code>$_GET</code>. Supports PHP-generated
* resources; references to globals in resource SHOULD be avoided, but
* MUST be declared if used.
*
* @author
* Copyright © 2011 Thomas 'PointedEars' Lahn <php@PointedEars.de>
* @license http://www.gnu.org/licenses/gpl.html
* GNU General Public License, version 3 and later
* @property-read string $version
* Class version
* @property string $prefix
* Common path prefix for all resources
* @property array $sources
* Sources to be processed in order
* @property string $contentType
* Content-type to be used
* @property-read array $typeMap
* Maps MIME media types to file extensions
* @property boolean $debug
* If <code>true</code>, preserve original file content
* @property boolean $verbose
* If <code>true</code>, produce verbose messages
* @property-read int $commentCount
* Number of comments processed so far
*/
class ResourceBuilder
{
const SCRIPT_CONTENT_TYPE = 'text/javascript';
/**
* Class version
* @var string
*/
protected $_version = '0.4.6';
/**
* Common path prefix for all resources
* @var string
*/
protected $_prefix = '';
/**
* Common path suffix for all resources.
* Determined from <var>$_contentType</var> if <code>null</code>.
* @var string
*/
protected $_suffix = null;
/**
* Sources to be processed in order
* @var array
*/
protected $_sources = array();
/**
* Content-type to be used
* @var string
*/
protected $_contentType = self::SCRIPT_CONTENT_TYPE;
/**
* @property-read array $typeMap
* Maps MIME media types to file extensions
*/
protected $_typeMap = array(
'text/javascript' => 'js',
'text/css' => 'css',
);
/**
* If <code>true</code>, preserve original file content
* @var boolean
*/
protected $_debug = false;
/**
* If <code>true</code>, produce verbose messages
* @var boolean
*/
protected $_verbose = false;
/**
* If <code>true</code> or <code>false</code>, forces or forbids
* the use of gzip. The default is <code>false</code> which
* gzips only if gzip=1 is specified and the client supports it.
*
* @var boolean
*/
protected $_force_gzip = false;
/**
* Number of comments processed so far
* @var int
*/
protected $_commentCount = 0;
protected $_jsxDeps = array(
'collection' => array('object'),
'dom' => array('object'),
'dom/css' => array('dom'),
'dom/css/color' => array('dom/css'),
'dom/events' => array('dom'),
'dom/xpath' => array('object'),
'http' => array('object'),
'test/debug' => array('object', 'types', 'array'),
'types' => array('object'),
);
/**
* If <code>true</code>, resolve JSX dependencies statically
* (EXPERIMENTAL)
* @var boolean
*/
protected $_resolve = false;
public function __construct (array $options = array())
{
if (isset($options['src']) || isset($_GET['src']))
{
$params = array(
'prefix',
'contentType' => 'type',
'suffix',
'sources' => 'src',
'debug',
'verbose',
'force_gzip' => 'gzip',
'resolve'
);
foreach ($params as $property => $param)
{
$value = isset($options[$param])
? $options[$param]
: (isset($_GET[$param]) ? $_GET[$param] : null);
if (is_int($property))
{
$property = $param;
}
$this->$property = $value;
}
$this->commentCount = 0;
}
}
/**
* Universal getter
*
* @param string $name Property name
* @return mixed Property value
* @throws DomainException if no specific getter or such a property exists
*/
public function __get ($name)
{
$getter = 'get' . ucfirst($name);
$property = '_' . lcfirst($name);
if (method_exists($this, $getter))
{
return $this->$getter();
}
if (property_exists($this, $property))
{
return $this->$property;
}
$exceptionClass = 'DomainException';
$message = "No method '$getter' or property '$property' on this object";
if (function_exists($exceptionClass))
{
throw new $exceptionClass($message);
}
throw new Exception($message);
}
/**
* Universal setter
*
* @param string $name
* @param mixed $value
* @throws DomainException if no specific setter or such a property exists
*/
public function __set ($name, $value)
{
$setter = 'set' . ucfirst($name);
$property = '_' . lcfirst($name);
if (method_exists($this, $setter))
{
return $this->$setter($value);
}
if (property_exists($this, $property))
{
$this->$property = $value;
}
else
{
$exceptionClass = 'DomainException';
$message = "No method '$setter' or property '$property' on this object";
if (function_exists($exceptionClass))
{
throw new $exceptionClass($message);
}
throw new Exception($message);
}
}
/**
* Sets the _sources property
*
* @param string|array $value Sources to process
*/
protected function setSources ($value)
{
if (!is_array($value))
{
$value = explode(',', $value);
}
/* Prepend prefix, append suffix */
$suffix = $this->suffix;
if ($suffix === null)
{
$contentType = $this->contentType;
$this->suffix = (array_key_exists($contentType, $this->typeMap)
? '.' . $this->typeMap[$contentType]
: '');
}
$that = $this;
$this->sources = array_map(function ($source) use ($that) {
return $that->prefix . $source . $that->suffix;
}, $value);
return $this;
}
/**
* Sets the _contentType property
*
* @param string $value
*/
protected function setContentType ($value)
{
$this->_contentType = ($value ? $value : 'text/javascript');
}
/**
* Sets the _debug property
*
* @param string $value
*/
protected function setDebug ($value)
{
if ($value != 0)
{
$this->_debug = true;
}
}
/**
* Sets the _verbose property
*
* @param string $value
*/
protected function setVerbose ($value)
{
if ($value != 0)
{
$this->_verbose = true;
}
}
/**
* Sets the <code>_force_gzip</code> property
*
* @param mixed $value
*/
protected function setForce_gzip($value)
{
$this->_force_gzip = ($value !== null) ? !!$value : $value;
}
/**
* Sets the <code>_resolve</code> property
*
* @param mixed $value
*/
protected function setResolve ($value)
{
if ($value != 0)
{
$this->_resolve = true;
}
}
/**
* @param array $match
* Comment to work on
* @return string
* Original comment or the empty string
*/
protected function commentReplacer ($match)
{
++$this->_commentCount;
if ($this->_commentCount > 1)
{
return '';
}
return $match[0];
}
/**
* Returns the passed string with all single-line
* comments, leading and trailing whitespace removed.
*
* @param string $s Source code to process
* @return string Processed source code
* @todo Do not strip from within literals
*/
protected function uncomment ($s)
{
return preg_replace('#^[\\t ]*//.*(?:\\r?\\n|\\r)*#m', '',
preg_replace('/^\\s+|\\s+$/', '',
// preg_replace(
// '#/[\\t ]*\\*.*?\\*/[\\t ]*(?:\\r?\\n|\\n)*#s', '',
$s
// )
)
);
}
/**
* Returns the passed string with all JSdoc comments
* but the first one removed.
*
* @param string $s Source code to process
* @return string Processed source code
* @todo Do not strip from within literals
*/
protected function stripJSdoc ($in)
{
$out = preg_replace_callback(
'#[\\t ]*/\\*\\*(?:\\*[^/]|[^*])*\\*/(?:\\r?\\n|\\r)?#',
array('self', 'commentReplacer'),
$in);
if ($out === null)
{
$out = "/* ResourceBuilder::stripJSdoc(): preg_replace_callback() returned "
. 'NULL which indicates pcre.backtrack_limit=='
. ini_get('pcre.backtrack_limit') . ' was exceeded. Input length was '
. mb_strlen($in) . ' bytes. JSdoc was not stripped;'
. ' increase pcre.backtrack_limit if problem persists. */'
. "\n$in";
}
return $out;
}
/**
* Resolves JSX dependencies from static information
* @todo Use dynamic inline information
*
* @param array $sources
* List of required resources
* @param array $new_sources [optional $name => $name]
* Associative array used internally to build the list
* of sources with their dependencies
* @return array
* List of sources with their dependencies resolved
*/
protected function resolveDeps (array $sources, array &$new_sources = array())
{
$deps = $this->jsxDeps;
foreach ($sources as $name)
{
if (!array_key_exists($name, $new_sources)
&& array_key_exists($name, $deps))
{
$this->resolveDeps($deps[$name], $new_sources);
}
$new_sources[$name] = $name;
}
return $new_sources;
}
public function output ()
{
$contentType = $this->contentType;
header('Content-Type: ' . $contentType);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
/* Cached resource expires in HTTP/1.1 caches 24h after last retrieval */
header('Cache-Control: max-age=86400, s-maxage=86400, must-revalidate, proxy-revalidate');
/* Cached resource expires in HTTP/1.0 caches 24h after last retrieval */
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
$use_gzip = false;
if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])
&& preg_match('/\b((?:x-)?gzip)\s*,?/', $_SERVER['HTTP_ACCEPT_ENCODING'], $matches)
&& function_exists('gzencode'))
{
$force_gzip = $this->force_gzip;
$use_gzip = ($force_gzip !== false);
if ($use_gzip)
{
header("Content-Encoding: {$matches[1]}");
header('Vary: Accept-Encoding');
}
}
$prefix = $this->prefix;
if ($contentType === self::SCRIPT_CONTENT_TYPE
&& $this->resolve)
{
$this->sources = $this->resolveDeps($this->sources);
}
$suffix = $this->suffix;
$out = "/*\n"
. " * Compacted with PointedEars' ResourceBuilder {$this->version}\n"
. ($this->verbose
? " * Type: {$contentType}\n"
. " * Common Prefix: " . ($prefix ? $prefix : '<none>') . "\n"
. " * Common Suffix: " . $suffix . "\n"
. " * Resources: " . implode(', ', $this->sources) . "\n"
: '')
. " *\n"
. " * Please see the original files for the complete source code.\n"
. " */\n\n";
if (!$use_gzip)
{
echo $out;
}
$verbose = $this->verbose;
/* Compute sizes only when needed */
if ($verbose)
{
$totalSize = 0;
$totalCompactedSize = 0;
}
// var_dump($this->sources);
foreach ($this->sources as $index => $file)
{
$this->commentCount = 0;
if ($index > 0)
{
if ($use_gzip)
{
$out .= "\n\n";
}
else
{
echo "\n\n";
}
}
/* Minimum negotiation for dynamic content */
if (!file_exists($file) && file_exists($file . '.php'))
{
$file .= '.php';
}
/*
* NOTE: No file_get_contents(), so that PHP in resource gets parsed.
* See globals caveat in class's PHPdoc.
*/
ob_start();
require_once $file;
if ($verbose)
{
$originalSize = ob_get_length();
}
$content = ob_get_contents();
ob_end_clean();
if ($verbose)
{
$totalSize += $originalSize;
$originalSizeFormatted = number_format($originalSize, 0, '.', "'");
}
if (!$this->debug)
{
/* Pass 1: Remove all single-line comments (i.e., disabled code) */
$content = $this->uncomment($content);
/*
* Pass 2: Remove all JSdoc comments but the first one
* (i.e., the copyright section)
*/
$content = $this->stripJSdoc($content);
/* Pass 3: Minimize (removes multi-line comments and extra whitespace) */
}
if ($verbose)
{
$compactedSize = strlen($content);
$totalCompactedSize += $compactedSize;
$compactedSizeFormatted = number_format($compactedSize, 0, '.', "'");
$ratioPercentage = $compactedSize / $originalSize * 100;
$ratioFormatted = sprintf('%.1f %%', $ratioPercentage);
}
$content =
implode("\n", array(
'/*',
" * {$file}"
. ($verbose
? ": {$originalSizeFormatted} bytes reduced to {$compactedSizeFormatted} bytes"
. " ({$ratioFormatted})"
: ""),
" */\n"
))
. $content;
if ($use_gzip)
{
$out .= $content;
}
else
{
echo $content;
}
}
if ($verbose)
{
$totalSizeFormatted = number_format($totalSize, 0, '.', "'");
$totalCompactedSizeFormatted = number_format($totalCompactedSize, 0, '.', "'");
$ratioPercentage = $totalCompactedSize / $totalSize * 100;
$ratioFormatted = sprintf('%.1f %%', $ratioPercentage);
$summary = "\n\n/*"
. " Total of {$totalSizeFormatted} bytes reduced to {$totalCompactedSizeFormatted} bytes"
. " ({$ratioFormatted}). */";
if ($use_gzip)
{
$out .= $summary;
}
else
{
echo $summary;
}
}
if ($use_gzip)
{
$zipped = gzencode($out);
//header('Content-Length: ' . strlen($zipped));
echo $zipped;
}
}
public function getResourceURIs ()
{
if ($this->contentType === self::SCRIPT_CONTENT_TYPE
&& $this->resolve)
{
$this->sources = $this->resolveDeps($this->sources);
$this->resolve = false;
}
return $this->sources;
}
public function printScriptElements ()
{
$code = array_map(
function ($uri) {
return '<script type="text/javascript" src="' . $uri . '"></script>';
},
$this->getResourceURIs());
echo implode("\n", $code);
}
public function printLinkElements ()
{
$code = array_map(
function ($uri) {
return '<link rel="stylesheet" type="text/css" src="' . $uri . '" />';
},
$this->getResourceURIs());
echo implode("\n", $code);
}
}