forked from kint-php/kint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKint.class.php
753 lines (629 loc) · 18.9 KB
/
Kint.class.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
<?php
/**
* Kint is a zero-setup debugging tool to output information about variables and stack traces prettily and comfortably.
*
* https://github.com/raveren/kint
*/
define( 'KINT_DIR', dirname( __FILE__ ) . '/' );
require KINT_DIR . 'config.default.php';
require KINT_DIR . 'parsers/parser.class.php';
if ( is_readable( KINT_DIR . 'config.php' ) ) {
require KINT_DIR . 'config.php';
}
class Kint
{
// these are all public and 1:1 config array keys so you can switch them easily
public static $traceCleanupCallback;
public static $fileLinkFormat;
public static $hideSequentialKeys;
public static $showClassConstants;
public static $keyFilterCallback;
public static $displayCalledFrom;
public static $maxStrLength;
public static $appRootDirs;
public static $maxLevels;
public static $enabled;
public static $theme;
public static $devel;
public static $modifier = null;
protected static $_firstRun = true;
/** @var Kint_Decorators_Rich */
protected static $_richDecorator;
/** @var Kint_Decorators_Plain */
protected static $_plainDecorator;
# non-standard function calls
protected static $_statements = array( 'include', 'include_once', 'require', 'require_once' );
/**
* getter/setter for the enabled parameter, called at the beginning of every public function as getter, also
* initializes the settings if te first time it's run.
*
* @param null $value
*
* @return void|bool
*/
public static function enabled( $value = null )
{
# act both as a setter...
if ( func_num_args() > 0 ) {
self::$enabled = $value;
return;
}
# ...and a getter
return self::$enabled;
}
public static function _init()
{
# init settings
if ( isset( $GLOBALS['_kint_settings'] ) ) {
foreach ( $GLOBALS['_kint_settings'] as $key => $val ) {
self::$$key = $val;
}
}
require KINT_DIR . 'decorators/rich.php';
self::$_richDecorator = new Kint_Decorators_Rich;
require KINT_DIR . 'decorators/plain.php';
self::$_plainDecorator = new Kint_Decorators_Plain;
require KINT_DIR . 'decorators/concise.php';
}
/**
* Prints a debug backtrace
*
* @param array $trace [OPTIONAL] you can pass your own trace, otherwise, `debug_backtrace` will be called
*
* @return void
*/
public static function trace( $trace = null )
{
if ( !Kint::enabled() ) return;
echo self::$_richDecorator->_css();
isset( $trace ) or $trace = debug_backtrace( true );
$output = array();
foreach ( $trace as $step ) {
self::$traceCleanupCallback and $step = call_user_func( self::$traceCleanupCallback, $step );
# if the user defined trace cleanup function returns null, skip this line
if ( $step === null ) {
continue;
}
if ( !isset( $step['function'] ) ) {
# invalid trace step
continue;
}
if ( isset( $step['file'] ) AND isset( $step['line'] ) ) {
# include the source of this step
$source = self::_showSource( $step['file'], $step['line'] );
}
if ( isset( $step['file'] ) ) {
$file = $step['file'];
if ( isset( $step['line'] ) ) {
$line = $step['line'];
}
}
$function = $step['function'];
if ( in_array( $step['function'], self::$_statements ) ) {
if ( empty( $step['args'] ) ) {
# no arguments
$args = array();
} else {
# sanitize the file path
$args = array( self::shortenPath( $step['args'][0] ) );
}
} elseif ( isset( $step['args'] ) ) {
if ( empty( $step['class'] ) && !function_exists( $step['function'] ) ) {
# introspection on closures or language constructs in a stack trace is impossible before PHP 5.3
$params = null;
} else {
try {
if ( isset( $step['class'] ) ) {
if ( method_exists( $step['class'], $step['function'] ) ) {
$reflection = new ReflectionMethod( $step['class'], $step['function'] );
} else if ( isset( $step['type'] ) && $step['type'] == '::' ) {
$reflection = new ReflectionMethod( $step['class'], '__callStatic' );
} else {
$reflection = new ReflectionMethod( $step['class'], '__call' );
}
} else {
$reflection = new ReflectionFunction( $step['function'] );
}
# get the function parameters
$params = $reflection->getParameters();
} catch ( Exception $e ) {
$params = null; # avoid various PHP version incompatibilities
}
}
$args = array();
foreach ( $step['args'] as $i => $arg ) {
if ( isset( $params[$i] ) ) {
# assign the argument by the parameter name
$args[$params[$i]->name] = $arg;
} else {
# assign the argument by number
$args[$i] = $arg;
}
}
}
if ( isset( $step['class'] ) ) {
# Class->method() or Class::method()
$function = $step['class'] . $step['type'] . $step['function'];
}
if ( isset( $step['object'] ) ) {
$function = $step['class'] . $step['type'] . $step['function'];
}
$output[] = array(
'function' => $function,
'args' => isset( $args ) ? $args : null,
'file' => isset( $file ) ? $file : null,
'line' => isset( $line ) ? $line : null,
'source' => isset( $source ) ? $source : null,
'object' => isset( $step['object'] ) ? $step['object'] : null,
);
unset( $function, $args, $file, $line, $source );
}
require KINT_DIR . 'view/trace.phtml';
}
/**
* dump information about variables
*
* @param mixed $data
*
* @return void|string
*/
public static function dump( $data = null )
{
if ( !Kint::enabled() ) return;
# find caller information
$trace = debug_backtrace();
list( $names, $modifier, $callee, $previousCaller ) = self::_getPassedNames( $trace );
if ( !is_null(self::$modifier) ) {
$modifier = self::$modifier;
self::$modifier = null;
}
if ( $names === array( null ) && func_num_args() === 1 && $data === 1 ) {
$call = reset( $trace );
if ( !isset( $call['file'] ) && isset( $call['class'] ) && $call['class'] === __CLASS__ ) {
array_shift( $trace );
$call = reset( $trace );
}
while ( isset( $call['file'] ) && $call['file'] === __FILE__ ) {
array_shift( $trace );
$call = reset( $trace );
}
self::trace( $trace );
return;
}
# process modifiers: @, + and -
switch ( $modifier ) {
case '-':
self::$_firstRun = true;
ob_clean();
break;
case '+':
$maxLevelsOldValue = self::$maxLevels;
self::$maxLevels = 0;
break;
case '@':
$firstRunOldValue = self::$maxLevels;
self::$_firstRun = true;
break;
}
$data = func_num_args() === 0
? array( "[[no arguments passed]]" )
: func_get_args();
$output = self::$_richDecorator->_css();
list( $wrapStart, $kintId ) = self::$_richDecorator->_wrapStart( $callee );
$output .= $wrapStart;
foreach ( $data as $k => $argument ) {
$output .= self::_dump( $argument, $names[$k] );
}
$output .= self::$_richDecorator->_wrapEnd( $callee, $previousCaller );
self::$_firstRun = false;
switch ( $modifier ) {
case '!':
echo $output;
echo "<script>kintExpandOnLoad.{$kintId}=1</script>";
break;
case '+':
self::$maxLevels = $maxLevelsOldValue;
break;
case '@':
self::$_firstRun = $firstRunOldValue;
return $output;
break;
default:
echo $output;
break;
}
return '';
}
protected static function _dump( $var, $name = '' )
{
kintParser::reset();
return Kint_Decorators_Rich::decorate(
kintParser::factory( $var, $name )
);
}
/**
* generic path display callback, can be configured in the settings
*
* @param string $file
* @param int $line [OPTIONAL]
*
* @return string
*/
public static function shortenPath( $file, $line = null )
{
$file = str_replace( '\\', '/', $file );
$shortenedName = $file;
foreach ( self::$appRootDirs as $path => $replaceString ) {
$path = str_replace( '\\', '/', $path );
if ( strpos( $file, $path ) === 0 ) {
$shortenedName = $replaceString . substr( $file, strlen( $path ) );
break;
}
}
if ( !$line ) { # means this is called from resource type dump
return $shortenedName;
}
if ( !self::$fileLinkFormat ) {
return "{$shortenedName} line <i>{$line}</i>";
}
$url = str_replace( array( '%f', '%l' ), array( $file, $line ), self::$fileLinkFormat );
$class = ( strpos( $url, 'http://' ) === 0 ) ? 'class="kint-ide-link"' : '';
return "<u><a {$class} href=\"{$url}\">{$shortenedName}</a></u> line <i>{$line}</i>";
}
/**
* trace helper, shows the place in code inline
*
* @param string $file full path to file
* @param int $lineNumber the line to display
* @param int $padding surrounding lines to show besides the main one
*
* @return bool|string
*/
private static function _showSource( $file, $lineNumber, $padding = 7 )
{
if ( !$file OR !is_readable( $file ) ) {
# continuing will cause errors
return false;
}
# open the file and set the line position
$file = fopen( $file, 'r' );
$line = 0;
# Set the reading range
$range = array(
'start' => $lineNumber - $padding,
'end' => $lineNumber + $padding
);
# set the zero-padding amount for line numbers
$format = '% ' . strlen( $range['end'] ) . 'd';
$source = '';
while ( ( $row = fgets( $file ) ) !== false ) {
# increment the line number
if ( ++$line > $range['end'] ) {
break;
}
if ( $line >= $range['start'] ) {
# make the row safe for output
$row = htmlspecialchars( $row, ENT_NOQUOTES );
# trim whitespace and sanitize the row
$row = '<span>' . sprintf( $format, $line ) . '</span> ' . $row;
if ( $line === $lineNumber ) {
# apply highlighting to this row
$row = '<div class="kint-highlight">' . $row . '</div>';
} else {
$row = '<div>' . $row . '</div>';
}
# add to the captured source
$source .= $row;
}
}
# close the file
fclose( $file );
return $source;
}
/**
* returns parameter names that the function was passed, as well as any predefined symbols before function
* call (modifiers)
*
* @param array $trace
*
* @return array( $parameters, $modifier, $callee, $previousCaller )
*/
private static function _getPassedNames( $trace )
{
$previousCaller = array();
while ( $callee = array_pop( $trace ) ) {
if ( strtolower( $callee['function'] ) === 'd' ||
strtolower( $callee['function'] ) === 'dd' ||
( isset( $callee['class'] ) && strtolower( $callee['class'] ) === strtolower( __CLASS__ )
&& strtolower( $callee['function'] ) === 'dump' )
) {
break;
} else {
$previousCaller = $callee;
}
}
if ( !isset( $callee['file'] ) || !is_readable( $callee['file'] ) ) {
return false;
}
# open the file and read it up to the position where the function call expression ended
$file = fopen( $callee['file'], 'r' );
$line = 0;
$source = '';
while ( ( $row = fgets( $file ) ) !== false ) {
if ( ++$line > $callee['line'] ) break;
$source .= $row;
}
fclose( $file );
$source = self::_removeAllButCode( $source );
$codePattern = empty( $callee['class'] )
? $callee['function']
: $callee['class'] . "\x07*" . $callee['type'] . "\x07*" . $callee['function'];
# get the position of the last call to the function
preg_match_all( "#[\x07{(](\\+|-|!|@)?{$codePattern}\x07*(\\()#i", $source, $matches, PREG_OFFSET_CAPTURE );
$match = end( $matches[2] );
$modifier = end( $matches[1] );
$modifier = $modifier[0];
$passedParameters = str_replace( "\x07", '', substr( $source, $match[1] + 1 ) );
# we now have a string like this:
# <parameters passed>); <the rest of the last read line>
# remove everything in brackets and quotes, we don't need nested statements nor literal strings which would
# only complicate separating individual arguments
$c = strlen( $passedParameters );
$inString = $escaped = false;
$i = 0;
$inBrackets = 0;
while ( $i < $c ) {
$letter = $passedParameters[$i];
if ( $inString === false ) {
if ( $letter === '\'' || $letter === '"' ) {
$inString = $letter;
} elseif ( $letter === '(' ) {
$inBrackets++;
} elseif ( $letter === ')' ) {
$inBrackets--;
if ( $inBrackets === -1 ) { # this means we are out of the brackets that denote passed parameters
$passedParameters = substr( $passedParameters, 0, $i );
break;
}
}
} elseif ( $letter === $inString && !$escaped ) {
$inString = false;
}
# place an untype-able character instead of whatever was inside quotes or brackets, we don't
# need that info. We'll later replace it with '...'
if ( $inBrackets > 0 ) {
if ( $inBrackets > 1 || $letter !== '(' ) {
$passedParameters[$i] = "\x07";
}
}
if ( $inString !== false ) {
if ( $letter !== $inString || $escaped ) {
$passedParameters[$i] = "\x07";
}
}
$escaped = !$escaped && ( $letter === '\\' );
$i++;
}
# by now we have an unnested arguments list, lets make it to an array for processing further
$arguments = explode( ',', preg_replace( "#\x07+#", '...', $passedParameters ) );
# test each argument whether it was passed literary or was it an expression or a variable name
$parameters = array();
$blacklist = array( 'null', 'true', 'false', 'array(...)', 'array()', '"..."', 'b"..."', );
foreach ( $arguments as $argument ) {
if ( is_numeric( $argument )
|| in_array( str_replace( "'", '"', strtolower( $argument ) ), $blacklist, true )
) {
$parameters[] = null;
} else {
$parameters[] = trim( $argument );
}
}
return array( $parameters, $modifier, $callee, $previousCaller );
}
/**
* removes comments and zaps whitespace & <?php tags from php code, makes for easier further parsing
*
* @param string $source
*
* @return string
*/
private static function _removeAllButCode( $source )
{
$newStr = '';
$tokens = token_get_all( $source );
$commentTokens = array( T_COMMENT => true, T_INLINE_HTML => true, );
if ( defined( 'T_DOC_COMMENT' ) ) {
$commentTokens[constant( 'T_DOC_COMMENT' )] = true;
}
if ( defined( 'T_ML_COMMENT' ) ) {
$commentTokens[constant( 'T_ML_COMMENT' )] = true;
}
$whiteSpaceTokens = array(
T_WHITESPACE => true, T_CLOSE_TAG => true, T_OPEN_TAG => true, T_OPEN_TAG_WITH_ECHO => true,
);
foreach ( $tokens as $token ) {
if ( is_array( $token ) ) {
if ( isset( $commentTokens[$token[0]] ) ) continue;
if ( $token[0] === T_NEW ) {
$token = 'new ';
} elseif ( isset( $whiteSpaceTokens[$token[0]] ) ) {
$token = "\x07";
} else {
$token = $token[1];
}
} elseif ( $token === ';' ) {
$token = "\x07";
}
$newStr .= $token;
}
return $newStr;
}
}
if ( !function_exists( 'd' ) ) {
/**
* Alias of Kint::dump()
*
* @return string
*/
function d()
{
if ( !Kint::enabled() ) return null;
$args = func_get_args();
return call_user_func_array( array( 'Kint', 'dump' ), $args );
}
}
if ( !function_exists( 'dd' ) ) {
/**
* Alias of Kint::dump()
* [!!!] IMPORTANT: execution will halt after call to this function
*
* @return string
*/
function dd()
{
if ( !Kint::enabled() ) return;
$args = func_get_args();
call_user_func_array( array( 'Kint', 'dump' ), $args );
die;
}
}
if ( !function_exists( 's' ) ) {
/**
* Alias of kintLite()
*
* @return string
*/
function s()
{
if ( !Kint::enabled() ) return;
$argv = func_get_args();
echo '<pre>';
foreach ( $argv as $k => $v ) {
$k && print( "\n\n" );
echo kintLite( $v );
}
echo '</pre>';
}
/**
* Alias of kintLite()
* [!!!] IMPORTANT: execution will halt after call to this function
*
* @return string
*/
function sd()
{
if ( !Kint::enabled() ) return;
echo '<pre>';
foreach ( func_get_args() as $k => $v ) {
$k && print( "\n\n" );
echo kintLite( $v );
}
echo '</pre>';
die;
}
}
/**
* lightweight version of Kint::dump(). Uses whitespace for formatting instead of html
* sadly not DRY yet
*
* @param $var
* @param int $level
*
* @return string
*/
function kintLite( &$var, $level = 0 )
{
// initialize function names into variables for prettier string output (html and implode are also DRY)
$html = "htmlspecialchars";
$implode = "implode";
$strlen = "strlen";
$count = "count";
$getClass = "get_class";
if ( $var === null ) {
return 'NULL';
} elseif ( is_bool( $var ) ) {
return 'bool ' . ( $var ? 'TRUE' : 'FALSE' );
} elseif ( is_float( $var ) ) {
return 'float ' . $var;
} elseif ( is_int( $var ) ) {
return 'integer ' . $var;
} elseif ( is_resource( $var ) ) {
if ( ( $type = get_resource_type( $var ) ) === 'stream' AND $meta = stream_get_meta_data( $var ) ) {
if ( isset( $meta['uri'] ) ) {
$file = $meta['uri'];
return "resource ({$type}) {$html( $file, 0 )}";
} else {
return "resource ({$type})";
}
} else {
return "resource ({$type})";
}
} elseif ( is_string( $var ) ) {
return "string ({$strlen( $var )}) \"{$html( $var )}\"";
} elseif ( is_array( $var ) ) {
$output = array();
$space = str_repeat( $s = ' ', $level );
static $marker;
if ( $marker === null ) {
// Make a unique marker
$marker = uniqid( "\x00" );
}
if ( empty( $var ) ) {
return "array()";
} elseif ( isset( $var[$marker] ) ) {
$output[] = "[\n$space$s*RECURSION*\n$space]";
} elseif ( $level < 7 ) {
$isSeq = array_keys( $var ) === range( 0, count( $var ) - 1 );
$output[] = "[";
$var[$marker] = true;
foreach ( $var as $key => &$val ) {
if ( $key === $marker ) continue;
$key = $space . $s . ( $isSeq ? "" : "'{$html( $key, 0 )}' => " );
$dump = kintLite( $val, $level + 1 );
$output[] = "{$key}{$dump}";
}
unset( $var[$marker] );
$output[] = "$space]";
} else {
$output[] = "[\n$space$s*depth too great*\n$space]";
}
return "array({$count( $var )}) {$implode( "\n", $output )}";
} elseif ( is_object( $var ) ) {
if ( $var instanceof SplFileInfo ) {
return "object SplFileInfo " . $var->getRealPath();
}
// Copy the object as an array
$array = (array)$var;
$output = array();
$space = str_repeat( $s = ' ', $level );
$hash = spl_object_hash( $var );
// Objects that are being dumped
static $objects = array();
if ( empty( $array ) ) {
return "object {$getClass( $var )} {}";
} elseif ( isset( $objects[$hash] ) ) {
$output[] = "{\n$space$s*RECURSION*\n$space}";
} elseif ( $level < 7 ) {
$output[] = "{";
$objects[$hash] = true;
foreach ( $array as $key => & $val ) {
if ( $key[0] === "\x00" ) {
$access = $key[1] === "*" ? "protected" : "private";
// Remove the access level from the variable name
$key = substr( $key, strrpos( $key, "\x00" ) + 1 );
} else {
$access = "public";
}
$output[] = "$space$s$access $key -> " . kintLite( $val, $level + 1 );
}
unset( $objects[$hash] );
$output[] = "$space}";
} else {
$output[] = "{\n$space$s*depth too great*\n$space}";
}
return "object {$getClass( $var )} ({$count( $array )}) {$implode( "\n", $output )}";
} else {
return gettype( $var ) . htmlspecialchars( var_export( $var, true ), ENT_NOQUOTES );
}
}
Kint::_init();