forked from digitalnature/php-ref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ref.php
2186 lines (1645 loc) · 68.8 KB
/
ref.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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Shortcut to ref, HTML mode
*
* @version 1.0
* @param mixed $args
*/
function r(){
// arguments passed to this function
$args = func_get_args();
// options (operators) gathered by the expression parser;
// this variable gets passed as reference to getInputExpressions(), which will store the operators in it
$options = array();
// doh
$output = '';
$ref = new ref('html');
// names of the arguments that were passed to this function
$expressions = ref::getInputExpressions($options);
// something went wrong while trying to parse the source expressions?
// if so, silently ignore this part and leave out the expression info
if(func_num_args() !== count($expressions))
$expressions = array_fill(0, func_num_args(), null);
foreach($args as $index => $arg)
$output .= $ref->query($arg, $expressions[$index]);
// return the results if this function was called with the error suppression operator
if(in_array('@', $options, true))
return $output;
// IE goes funky if there's no doctype
if(!headers_sent() && !ob_get_length())
print '<!DOCTYPE HTML><html><head><title>REF</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>';
print $output;
// stop the script if this function was called with the bitwise not operator
if(in_array('~', $options, true)){
print '</body></html>';
exit(0);
}
}
/**
* Shortcut to ref, plain text mode
*
* @version 1.0
* @param mixed $args
*/
function rt(){
$args = func_get_args();
$options = array();
$output = '';
$expressions = ref::getInputExpressions($options);
$ref = new ref('text');
if(func_num_args() !== count($expressions))
$expressions = array_fill(0, func_num_args(), null);
foreach($args as $index => $arg)
$output .= $ref->query($arg, $expressions[$index]);
if(in_array('@', $options, true))
return $output;
if(!headers_sent())
header('Content-Type: text/plain; charset=utf-8');
print $output;
if(in_array('~', $options, true))
exit(0);
}
/**
* REF is a nicer alternative to PHP's print_r() / var_dump().
*
* @version 1.0
* @author digitalnature - http://digitalnature.eu
*/
class ref{
const
MARKER_KEY = '_phpRefArrayMarker_';
protected static
/**
* CPU time used for processing
*
* @var array
*/
$time = 0,
/**
* Configuration (+ default values)
*
* @var array
*/
$config = array(
// initial expand depth (for HTML mode only)
'expandDepth' => 1,
// shortcut functions used to access the query method below;
// if they are namespaced, the namespace must be present as well (methods are not supported)
'shortcutFunc' => array('r', 'rt'),
// callbacks for custom/external formatters (as associative array: format => callback)
'formatter' => array(),
// when this option is set to TRUE, additional information is
// returned (note that this seriously affects performance):
// - string matches (date, file, functions, classes, json, serialized data, regex etc.)
// - extra information for some resource types
// - contents of iterator objects
'extendedInfo' => true,
// stylesheet path (for HTML only);
// 'false' means no styles
'stylePath' => '{:dir}/ref.css',
// javascript path (for HTML only);
// 'false' means no js
'scriptPath' => '{:dir}/ref.js',
);
protected
/**
* Tracks current nesting level
*
* @var int
*/
$level = 0,
/**
* Max. expand depth of this instance
*
* @var int
*/
$expDepth = 1,
/**
* Output format of this instance
*
* @var string
*/
$format = null,
/**
* Some environment variables
* used to determine feature support
*
* @var string
*/
$env = array(),
/**
* Used to cache output to speed up processing.
* Cached objects will not be processed again in the same query
*
* @var array
*/
$cache = array();
/**
* Constructor
*
* @param string $format Output format, defaults to 'html'
* @param int|null $expDepth Maximum expand depth (relevant to the HTML format)
*/
public function __construct($format = 'html', $expDepth = null){
$this->format = $format;
$this->expDepth = ($expDepth !== null) ? $expDepth : static::$config['expandDepth'];
$this->env = array(
// php 5.4+ ?
'is54' => version_compare(PHP_VERSION, '5.4') >= 0,
// is the 'mbstring' extension active?
'mbStr' => function_exists('mb_detect_encoding'),
// @see: https://bugs.php.net/bug.php?id=52469
'supportsDate' => (strncasecmp(PHP_OS, 'WIN', 3) !== 0) || (version_compare(PHP_VERSION, '5.3.10') >= 0),
);
}
/**
* Enforce proper use of this class
*
* @param string $name
*/
public function __get($name){
throw new \Exception('No such property');
}
/**
* Enforce proper use of this class
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value){
throw new \Exception('Not allowed');
}
/**
* Used to dispatch output to a custom formatter
*
* @param string $name
* @param array $args
* @return string
*/
public function __call($name, array $args = array()){
if(isset(static::$config['formatters'][$name]))
return call_user_func_array(static::$config['formatters'][$name], $args);
throw new \Exception('Method not defined');
}
/**
* Generate structured information about a variable/value/expression (subject)
*
* @param mixed $subject
* @param string $expression
* @return string
*/
public function query($subject, $expression = null){
$startTime = microtime(true);
$output = $this->{"to{$this->format}"}('root', $this->evaluate($subject), $this->evaluateExp($expression));
$this->cache = array();
static::$time += microtime(true) - $startTime;
return $output;
}
/**
* Executes a function the given number of times and returns the elapsed time.
*
* Keep in mind that the returned time includes function call overhead (including
* microtime calls) x iteration count. This is why this is better suited for
* determining which of two or more functions is the fastest, rather than
* finding out how fast is a single function.
*
* @param int $iterations Number of times the function will be executed
* @param callable $function Function to execute
* @param mixed &$output If given, last return value will be available in this variable
* @return double Elapsed time
*/
public static function timeFunc($iterations, $function, &$output = null){
$time = 0;
for($i = 0; $i < $iterations; $i++){
$start = microtime(true);
$output = call_user_func($function);
$time += microtime(true) - $start;
}
return round($time, 4);
}
/**
* Timery utility
*
* First call of this function will start the timer.
* The second call will stop the timer and return the elapsed time
* since the timer started.
*
* Multiple timers can be controlled simultaneously by specifying a timer ID.
*
* @since 1.0
* @param int $id Timer ID, optional
* @param int $precision Precision of the result, optional
* @return void|double Elapsed time, or void if the timer was just started
*/
public static function timer($id = 1, $precision = 4){
static
$timers = array();
// check if this timer was started, and display the elapsed time if so
if(isset($timers[$id])){
$elapsed = round(microtime(true) - $timers[$id], $precision);
unset($timers[$id]);
return $elapsed;
}
// ID doesn't exist, start new timer
$timers[$id] = microtime(true);
}
/**
* Parses a DocBlock comment into a data structure.
*
* @link http://pear.php.net/manual/en/standards.sample.php
* @param string $comment DocBlock comment (must start with /**)
* @param string|null $key Field to return (optional)
* @return array|string|null Array containing all fields, array/string with the contents of
* the requested field, or null if the comment is empty/invalid
*/
public static function parseComment($comment, $key = null){
$description = '';
$tags = array();
$tag = null;
$pointer = '';
$padding = 0;
$comment = preg_split('/\r\n|\r|\n/', '* ' . trim($comment, "/* \t\n\r\0\x0B"));
// analyze each line
foreach($comment as $line){
// drop any wrapping spaces
$line = trim($line);
// drop "* "
if($line !== '')
$line = substr($line, 2);
if(strpos($line, '@') !== 0){
// preserve formatting of tag descriptions,
// because they may span across multiple lines
if($tag !== null){
$trimmed = trim($line);
if($padding !== 0)
$trimmed = static::strPad($trimmed, static::strLen($line) - $padding, ' ', STR_PAD_LEFT);
else
$padding = static::strLen($line) - static::strLen($trimmed);
$pointer .= "\n{$trimmed}";
continue;
}
// tag definitions have not started yet; assume this is part of the description text
$description .= "\n{$line}";
continue;
}
$padding = 0;
$parts = explode(' ', $line, 2);
// invalid tag? (should we include it as an empty array?)
if(!isset($parts[1]))
continue;
$tag = substr($parts[0], 1);
$line = ltrim($parts[1]);
// tags that have a single component (eg. link, license, author, throws...);
// note that @throws may have 2 components, however most people use it like "@throws ExceptionClass if whatever...",
// which, if broken into two values, leads to an inconsistent description sentence
if(!in_array($tag, array('global', 'param', 'return', 'var'))){
$tags[$tag][] = $line;
end($tags[$tag]);
$pointer = &$tags[$tag][key($tags[$tag])];
continue;
}
// tags with 2 or 3 components (var, param, return);
$parts = explode(' ', $line, 2);
$parts[1] = isset($parts[1]) ? ltrim($parts[1]) : null;
$lastIdx = 1;
// expecting 3 components on the 'param' tag: type varName varDescription
if($tag === 'param'){
$lastIdx = 2;
if(in_array($parts[1][0], array('&', '$'), true)){
$line = ltrim(array_pop($parts));
$parts = array_merge($parts, explode(' ', $line, 2));
$parts[2] = isset($parts[2]) ? ltrim($parts[2]) : null;
}else{
$parts[2] = $parts[1];
$parts[1] = null;
}
}
$tags[$tag][] = $parts;
end($tags[$tag]);
$pointer = &$tags[$tag][key($tags[$tag])][$lastIdx];
}
// split title from the description texts at the nearest 2x new-line combination
// (note: loose check because 0 isn't valid as well)
if(strpos($description, "\n\n")){
list($title, $description) = explode("\n\n", $description, 2);
// if we don't have 2 new lines, try to extract first sentence
}else{
// in order for a sentence to be considered valid,
// the next one must start with an uppercase letter
$sentences = preg_split('/(?<=[.?!])\s+(?=[A-Z])/', $description, 2, PREG_SPLIT_NO_EMPTY);
// failed to detect a second sentence? then assume there's only title and no description text
$title = isset($sentences[0]) ? $sentences[0] : $description;
$description = isset($sentences[1]) ? $sentences[1] : '';
}
$title = ltrim($title);
$description = ltrim($description);
$data = compact('title', 'description', 'tags');
if(!array_filter($data))
return null;
if($key !== null)
return isset($data[$key]) ? $data[$key] : null;
return $data;
}
/**
* Split a regex into its components
*
* Based on "Regex Colorizer" by Steven Levithan (this is a translation from javascript)
*
* @link https://github.com/slevithan/regex-colorizer
* @link https://github.com/symfony/Finder/blob/master/Expression/Regex.php#L64-74
* @param string $pattern
* @return array
*/
public static function splitRegex($pattern){
// detection attempt code from the Symfony Finder component
$maybeValid = false;
if(preg_match('/^(.{3,}?)([imsxuADU]*)$/', $pattern, $m)) {
$start = substr($m[1], 0, 1);
$end = substr($m[1], -1);
if(($start === $end && !preg_match('/[*?[:alnum:] \\\\]/', $start)) || ($start === '{' && $end === '}'))
$maybeValid = true;
}
if(!$maybeValid)
throw new \Exception('Pattern does not appear to be a valid PHP regex');
$output = array();
$capturingGroupCount = 0;
$groupStyleDepth = 0;
$openGroups = array();
$lastIsQuant = false;
$lastType = 1; // 1 = none; 2 = alternator
$lastStyle = null;
preg_match_all('/\[\^?]?(?:[^\\\\\]]+|\\\\[\S\s]?)*]?|\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\\\]+|./', $pattern, $matches);
$matches = $matches[0];
$getTokenCharCode = function($token){
if(strlen($token) > 1 && $token[0] === '\\'){
$t1 = substr($token, 1);
if(preg_match('/^c[A-Za-z]$/', $t1))
return strpos("ABCDEFGHIJKLMNOPQRSTUVWXYZ", strtoupper($t1[1])) + 1;
if(preg_match('/^(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4})$/', $t1))
return intval(substr($t1, 1), 16);
if(preg_match('/^(?:[0-3][0-7]{0,2}|[4-7][0-7]?)$/', $t1))
return intval($t1, 8);
$len = strlen($t1);
if($len === 1 && strpos('cuxDdSsWw', $t1) !== false)
return null;
if($len === 1){
switch ($t1) {
case 'b': return 8;
case 'f': return 12;
case 'n': return 10;
case 'r': return 13;
case 't': return 9;
case 'v': return 11;
default: return $t1[0];
}
}
}
return ($token !== '\\') ? $token[0] : null;
};
foreach($matches as $m){
if($m[0] === '['){
$lastCC = null;
$cLastRangeable = false;
$cLastType = 0; // 0 = none; 1 = range hyphen; 2 = short class
preg_match('/^(\[\^?)(]?(?:[^\\\\\]]+|\\\\[\S\s]?)*)(]?)$/', $m, $parts);
array_shift($parts);
list($opening, $content, $closing) = $parts;
if(!$closing)
throw new \Exception('Unclosed character class');
preg_match_all('/[^\\\\-]+|-|\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)/', $content, $ccTokens);
$ccTokens = $ccTokens[0];
$ccTokenCount = count($ccTokens);
$output[] = array('chr' => $opening);
foreach($ccTokens as $i => $cm) {
if($cm[0] === '\\'){
if(preg_match('/^\\\\[cux]$/', $cm))
throw new \Exception('Incomplete regex token');
if(preg_match('/^\\\\[dsw]$/i', $cm)) {
$output[] = array('chr-meta' => $cm);
$cLastRangeable = ($cLastType !== 1);
$cLastType = 2;
}elseif($cm === '\\'){
throw new \Exception('Incomplete regex token');
}else{
$output[] = array('chr-meta' => $cm);
$cLastRangeable = $cLastType !== 1;
$lastCC = $getTokenCharCode($cm);
}
}elseif($cm === '-'){
if($cLastRangeable){
$nextToken = ($i + 1 < $ccTokenCount) ? $ccTokens[$i + 1] : false;
if($nextToken){
$nextTokenCharCode = $getTokenCharCode($nextToken[0]);
if((!is_null($nextTokenCharCode) && $lastCC > $nextTokenCharCode) || $cLastType === 2 || preg_match('/^\\\\[dsw]$/i', $nextToken[0]))
throw new \Exception('Reversed or invalid range');
$output[] = array('chr-range' => '-');
$cLastRangeable = false;
$cLastType = 1;
}else{
$output[] = $closing ? array('chr' => '-') : array('chr-range' => '-');
}
}else{
$output[] = array('chr' => '-');
$cLastRangeable = ($cLastType !== 1);
}
}else{
$output[] = array('chr' => $cm);
$cLastRangeable = strlen($cm) > 1 || ($cLastType !== 1);
$lastCC = $cm[strlen($cm) - 1];
}
}
$output[] = array('chr' => $closing);
$lastIsQuant = true;
}elseif($m[0] === '('){
if(strlen($m) === 2)
throw new \Exception('Invalid or unsupported group type');
if(strlen($m) === 1)
$capturingGroupCount++;
$groupStyleDepth = ($groupStyleDepth !== 5) ? $groupStyleDepth + 1 : 1;
$openGroups[] = $m; // opening
$lastIsQuant = false;
$output[] = array("g{$groupStyleDepth}" => $m);
}elseif($m[0] === ')'){
if(!count($openGroups))
throw new \Exception('No matching opening parenthesis');
$output[] = array('g' . $groupStyleDepth => ')');
$prevGroup = $openGroups[count($openGroups) - 1];
$prevGroup = isset($prevGroup[2]) ? $prevGroup[2] : '';
$lastIsQuant = !preg_match('/^[=!]/', $prevGroup);
$lastStyle = "g{$groupStyleDepth}";
$lastType = 0;
$groupStyleDepth = ($groupStyleDepth !== 1) ? $groupStyleDepth - 1 : 5;
array_pop($openGroups);
continue;
}elseif($m[0] === '\\'){
if(isset($m[1]) && preg_match('/^[1-9]/', $m[1])){
$nonBackrefDigits = '';
$num = substr(+$m, 1);
while($num > $capturingGroupCount){
preg_match('/[0-9]$/', $num, $digits);
$nonBackrefDigits = $digits[0] . $nonBackrefDigits;
$num = floor($num / 10);
}
if($num > 0){
$output[] = array('meta' => "\\{$num}", 'text' => $nonBackrefDigits);
}else{
preg_match('/^\\\\([0-3][0-7]{0,2}|[4-7][0-7]?|[89])([0-9]*)/', $m, $pts);
$output[] = array('meta' => '\\' . $pts[1], 'text' => $pts[2]);
}
$lastIsQuant = true;
}elseif(isset($m[1]) && preg_match('/^[0bBcdDfnrsStuvwWx]/', $m[1])){
if(preg_match('/^\\\\[cux]$/', $m))
throw new \Exception('Incomplete regex token');
$output[] = array('meta' => $m);
$lastIsQuant = (strpos('bB', $m[1]) === false);
}elseif($m === '\\'){
throw new \Exception('Incomplete regex token');
}else{
$output[] = array('text' => $m);
$lastIsQuant = true;
}
}elseif(preg_match('/^(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??$/', $m)){
if(!$lastIsQuant)
throw new \Exception('Quantifiers must be preceded by a token that can be repeated');
preg_match('/^\{([0-9]+)(?:,([0-9]*))?/', $m, $interval);
if($interval && (+$interval[1] > 65535 || (isset($interval[2]) && (+$interval[2] > 65535))))
throw new \Exception('Interval quantifier cannot use value over 65,535');
if($interval && isset($interval[2]) && (+$interval[1] > +$interval[2]))
throw new \Exception('Interval quantifier range is reversed');
$output[] = array($lastStyle ? $lastStyle : 'meta' => $m);
$lastIsQuant = false;
}elseif($m === '|'){
if($lastType === 1 || ($lastType === 2 && !count($openGroups)))
throw new \Exception('Empty alternative effectively truncates the regex here');
$output[] = count($openGroups) ? array("g{$groupStyleDepth}" => '|') : array('meta' => '|');
$lastIsQuant = false;
$lastType = 2;
$lastStyle = '';
continue;
}elseif($m === '^' || $m === '$'){
$output[] = array('meta' => $m);
$lastIsQuant = false;
}elseif($m === '.'){
$output[] = array('meta' => '.');
$lastIsQuant = true;
}else{
$output[] = array('text' => $m);
$lastIsQuant = true;
}
$lastType = 0;
$lastStyle = '';
}
if($openGroups)
throw new \Exception('Unclosed grouping');
return $output;
}
/**
* Set or get configuration options
*
* @param string $key
* @param mixed|null $value
* @return mixed
*/
public static function config($key, $value = null){
if(!array_key_exists($key, static::$config))
throw new \Exception(sprintf('Unrecognized option: "%s". Valid options are: %s', $key, implode(', ', array_keys(static::$config))));
if($value === null)
return static::$config[$key];
if(is_array(static::$config[$key]))
return static::$config[$key] = (array)$value;
return static::$config[$key] = $value;
}
/**
* Get styles and javascript (only generated for the 1st call)
*
* @return string
*/
public static function getAssets(){
// tracks style/jscript inclusion state (html only)
static $didAssets = false;
// first call? include styles and javascript
if($didAssets)
return '';
ob_start();
if(static::$config['stylePath'] !== false){
?>
<style scoped>
<?php readfile(str_replace('{:dir}', __DIR__, static::$config['stylePath'])); ?>
</style>
<?php
}
if(static::$config['scriptPath'] !== false){
?>
<script>
<?php readfile(str_replace('{:dir}', __DIR__, static::$config['scriptPath'])); ?>
</script>
<?php
}
// normalize space and remove comments
$output = preg_replace('/\s+/', ' ', trim(ob_get_clean()));
$output = preg_replace('!/\*.*?\*/!s', '', $output);
$output = preg_replace('/\n\s*\n/', "\n", $output);
$didAssets = true;
return $output;
}
/**
* Total CPU time used by the class
*
* @param int precision
* @return double
*/
public static function getTime($precision = 4){
return round(static::$time, $precision);
}
/**
* Determines the input expression(s) passed to the shortcut function
*
* @param array &$options Optional, options to gather (from operators)
* @return array Array of string expressions
*/
public static function getInputExpressions(array &$options = null){
// used to determine the position of the current call,
// if more queries calls were made on the same line
static $lineInst = array();
// pull only basic info with php 5.3.6+ to save some memory
$trace = defined('DEBUG_BACKTRACE_IGNORE_ARGS') ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) : debug_backtrace();
while($callee = array_pop($trace)){
// extract only the information we neeed
$callee = array_intersect_key($callee, array_fill_keys(array('file', 'function', 'line'), false));
extract($callee);
// skip, if the called function doesn't match the shortcut function name
if(!$function || !preg_grep("/{$function}/i" , static::$config['shortcutFunc']))
continue;
if(!$line || !$file)
return array();
$code = file($file);
$code = $code[$line - 1]; // multiline expressions not supported!
$instIndx = 0;
$tokens = token_get_all("<?php {$code}");
// locate the caller position in the line, and isolate argument tokens
foreach($tokens as $i => $token){
// match token with our shortcut function name
if(is_string($token) || ($token[0] !== T_STRING) || (strcasecmp($token[1], $function) !== 0))
continue;
// is this some method that happens to have the same name as the shortcut function?
if(isset($tokens[$i - 1]) && is_array($tokens[$i - 1]) && in_array($tokens[$i - 1][0], array(T_DOUBLE_COLON, T_OBJECT_OPERATOR), true))
continue;
// find argument definition start, just after '('
if(isset($tokens[$i + 1]) && ($tokens[$i + 1][0] === '(')){
$instIndx++;
if(!isset($lineInst[$line]))
$lineInst[$line] = 0;
if($instIndx <= $lineInst[$line])
continue;
$lineInst[$line]++;
// gather options
if($options !== null){
$j = $i - 1;
while(isset($tokens[$j]) && is_string($tokens[$j]) && in_array($tokens[$j], array('@', '+', '-', '!', '~')))
$options[] = $tokens[$j--];
}
$lvl = $index = $curlies = 0;
$expressions = array();
// get the expressions
foreach(array_slice($tokens, $i + 2) as $token){
if(is_array($token)){
if($token[0] !== T_COMMENT)
$expressions[$index][] = ($token[0] !== T_WHITESPACE) ? $token[1] : ' ';
continue;
}
if($token === '{')
$curlies++;
if($token === '}')
$curlies--;
if($token === '(')
$lvl++;
if($token === ')')
$lvl--;
// assume next argument if a comma was encountered,
// and we're not insde a curly bracket or inner parentheses
if(($curlies < 1) && ($lvl === 0) && ($token === ',')){
$index++;
continue;
}
// negative parentheses count means we reached the end of argument definitions
if($lvl < 0){
foreach($expressions as &$expression)
$expression = trim(implode('', $expression));
return $expressions;
}
$expressions[$index][] = $token;
}
break;
}
}
}
}
/**
* Generates the output in plain text format
*
* @param string $element
* @param string|null $arg1
* @param string|null $arg2
* @param string|array|null $meta
* @return string
*/
protected function toText($element, $arg1 = null, $arg2 = null, $meta = null){
switch($element){
case 'sep':
return $arg1;
case 'text':
if($arg2 === null)
$arg2 = $arg1;
if($arg1 === 'specialString'){
$arg2 = strtr($arg2, array(
"\r" => '\r', // carriage return
"\t" => '\t', // horizontal tab
"\n" => '\n', // linefeed (new line)
"\v" => '\v', // vertical tab
"\e" => '\e', // escape
"\f" => '\f', // form feed
"\0" => '\0',
));
}
$formatMap = array(
'string' => '%3$s "%2$s"',
'integer' => 'int(%2$s)',
'double' => 'double(%2$s)',
'true' => 'bool(%2$s)',
'false' => 'bool(%2$s)',
'key' => '[%2$s]',
);
if(!is_string($meta))
$meta = '';
return isset($formatMap[$arg1]) ? sprintf($formatMap[$arg1], $arg1, $arg2, $meta) : $arg2;
case 'match':
return ($arg1 !== 'regex') ? "\n~~ {$arg1}: {$arg2}" : '';
case 'contain':
return ($arg1 !== 'regex') ? $arg2 : '';
case 'link':
return $arg1;
case 'group':
$prefix = ($arg2 !== null) ? $arg2 : '';
if($arg1){
$arg1 = $arg1 . "\n";
$prefix .= " \xe2\x96\xbc";
}
return "({$prefix}{$arg1})";
case 'section':
$output = '';
if($arg2 !== null)
$output .= "\n\n " . $arg2 . "\n " . str_repeat('-', static::strLen($arg2));
$lengths = array();
// determine maximum column width
foreach($arg1 as $item)
foreach($item as $colIdx => $c)
if(!isset($lengths[$colIdx]) || $lengths[$colIdx] < static::strLen($c))
$lengths[$colIdx] = static::strLen($c);
foreach($arg1 as $item){
$lastColIdx = count($item) - 1;
$padLen = 0;
$output .= "\n ";
foreach($item as $colIdx => $c){
// skip empty columns
if($lengths[$colIdx] < 1)
continue;
if($colIdx < $lastColIdx){
$output .= static::strPad($c, $lengths[$colIdx]) . ' ';
$padLen += $lengths[$colIdx] + 1;
continue;
}