-
Notifications
You must be signed in to change notification settings - Fork 59
/
ref.php
2967 lines (2236 loc) · 85.5 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
*
* @param mixed $args
* @return void|string
*/
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();
// names of the arguments that were passed to this function
$expressions = ref::getInputExpressions($options);
$capture = in_array('@', $options, true);
// 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 = null;
// use HTML formatter only if we're not in CLI mode, or if return was requested
$format = (php_sapi_name() !== 'cli') || $capture ? 'html' : 'cliText';
// IE goes funky if there's no doctype
if(!$capture && ($format === 'html') && !headers_sent() && (!ob_get_level() || ini_get('output_buffering')))
print '<!DOCTYPE HTML><html><head><title>REF</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>';
$ref = new ref($format);
if($capture)
ob_start();
foreach($args as $index => $arg)
$ref->query($arg, $expressions ? $expressions[$index] : null);
// return the results if this function was called with the error suppression operator
if($capture)
return ob_get_clean();
// stop the script if this function was called with the bitwise not operator
if(in_array('~', $options, true) && ($format === 'html')){
print '</body></html>';
exit(0);
}
}
/**
* Shortcut to ref, plain text mode
*
* @param mixed $args
* @return void|string
*/
function rt(){
$args = func_get_args();
$options = array();
$output = '';
$expressions = ref::getInputExpressions($options);
$capture = in_array('@', $options, true);
$ref = new ref((php_sapi_name() !== 'cli') || $capture ? 'text' : 'cliText');
if(func_num_args() !== count($expressions))
$expressions = null;
if(!headers_sent())
header('Content-Type: text/plain; charset=utf-8');
if($capture)
ob_start();
foreach($args as $index => $arg)
$ref->query($arg, $expressions ? $expressions[$index] : null);
if($capture)
return ob_get_clean();
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(
// initially expanded levels (for HTML mode only)
'expLvl' => 1,
// depth limit (0 = no limit);
// this is not related to recursion
'maxDepth' => 6,
// show the place where r() has been called from
'showBacktrace' => true,
// display iterator contents
'showIteratorContents' => false,
// display extra information about resources
'showResourceInfo' => true,
// display method and parameter list on objects
'showMethods' => true,
// display private properties / methods
'showPrivateMembers' => false,
// peform string matches (date, file, functions, classes, json, serialized data, regex etc.)
// note: seriously slows down queries on large amounts of data
'showStringMatches' => true,
// 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'),
// custom/external formatters (as associative array: format => className)
'formatters' => array(),
// 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',
// display url info via cURL
'showUrls' => false,
// stop evaluation after this amount of time (seconds)
'timeout' => 10,
// whether to produce W3c-valid HTML,
// or unintelligible, but optimized markup that takes less space
'validHtml' => false,
),
/**
* Some environment variables
* used to determine feature support
*
* @var array
*/
$env = array(),
/**
* Timeout point
*
* @var bool
*/
$timeout = -1,
$debug = array(
'cacheHits' => 0,
'objects' => 0,
'arrays' => 0,
'scalars' => 0,
);
protected
/**
* Output formatter of this instance
*
* @var RFormatter
*/
$fmt = null,
/**
* Start time of the current instance
*
* @var float
*/
$startTime = 0,
/**
* Internally created objects
*
* @var SplObjectStorage
*/
$intObjects = null;
/**
* Constructor
*
* @param string|RFormatter $format Output format ID, or formatter instance defaults to 'html'
*/
public function __construct($format = 'html'){
static $didIni = false;
if(!$didIni){
$didIni = true;
foreach(array_keys(static::$config) as $key){
$iniVal = get_cfg_var('ref.' . $key);
if($iniVal !== false)
static::$config[$key] = $iniVal;
}
}
if($format instanceof RFormatter){
$this->fmt = $format;
}else{
$format = isset(static::$config['formatters'][$format]) ? static::$config['formatters'][$format] : 'R' . ucfirst($format) . 'Formatter';
if(!class_exists($format, false))
throw new \Exception(sprintf('%s class not found', $format));
$this->fmt = new $format();
}
if(static::$env)
return;
static::$env = array(
// php 5.4+ ?
'is54' => version_compare(PHP_VERSION, '5.4') >= 0,
// php 5.4.6+ ?
'is546' => version_compare(PHP_VERSION, '5.4.6') >= 0,
// php 5.6+
'is56' => version_compare(PHP_VERSION, '5.6') >= 0,
// php 7.0+ ?
'is7' => version_compare(PHP_VERSION, '7.0') >= 0,
// curl extension running?
'curlActive' => function_exists('curl_version'),
// 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(sprintf('No such property: %s', $name));
}
/**
* Enforce proper use of this class
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value){
throw new \Exception(sprintf('Cannot set %s. Not allowed', $name));
}
/**
* Generate structured information about a variable/value/expression (subject)
*
* Output is flushed to the screen
*
* @param mixed $subject
* @param string $expression
*/
public function query($subject, $expression = null){
if(static::$timeout > 0)
return;
$this->startTime = microtime(true);
$this->intObjects = new \SplObjectStorage();
$this->fmt->startRoot();
$this->fmt->startExp();
$this->evaluateExp($expression);
$this->fmt->endExp();
$this->evaluate($subject);
$this->fmt->endRoot();
$this->fmt->flush();
static::$time += microtime(true) - $this->startTime;
}
/**
* 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);
}
/**
* Timer 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;
}
/**
* Total CPU time used by the class
*
* @param int precision
* @return double
*/
public static function getTime($precision = 4){
return round(static::$time, $precision);
}
/**
* Get relevant backtrace info for last ref call
*
* @return array|false
*/
public static function getBacktrace(){
// 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, EXTR_OVERWRITE);
// skip, if the called function doesn't match the shortcut function name
if(!$function || !in_array(mb_strtolower((string)$function), static::$config['shortcutFunc']))
continue;
return compact('file', 'function', 'line');
}
return false;
}
/**
* 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();
$trace = static::getBacktrace();
if(!$trace)
return array();
extract($trace);
$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;
}
}
return array();
}
/**
* Get all parent classes of a class
*
* @param Reflector $class Reflection object
* @return array Array of ReflectionClass objects (starts with the ancestor, ends with the given class)
*/
protected static function getParentClasses(\Reflector $class){
$parents = array($class);
while(($class = $class->getParentClass()) !== false)
$parents[] = $class;
return array_reverse($parents);
}
/**
* Generate class / function info
*
* @param Reflector $reflector Class name or reflection object
* @param string $single Skip parent classes
* @param Reflector|null $context Object context (for methods)
* @return string
*/
protected function fromReflector(\Reflector $reflector, $single = '', \Reflector $context = null){
// @todo: test this
$hash = var_export(func_get_args(), true);
//$hash = $reflector->getName() . ';' . $single . ';' . ($context ? $context->getName() : '');
if($this->fmt->didCache($hash)){
static::$debug['cacheHits']++;
return;
}
$items = array($reflector);
if(($single === '') && ($reflector instanceof \ReflectionClass))
$items = static::getParentClasses($reflector);
$first = true;
foreach($items as $item){
if(!$first)
$this->fmt->sep(' :: ');
$first = false;
$name = ($single !== '') ? $single : $item->getName();
$comments = $item->isInternal() ? array() : static::parseComment($item->getDocComment());
$meta = array('sub' => array());
$bubbles = array();
if($item->isInternal()){
$extension = $item->getExtension();