Completed
Pull Request — master (#451)
by Richard
10:55
created

Kint.class.php ➔ sd()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 3
nop 0
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 12 and the first side effect is on line 9.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Kint is a zero-setup debugging tool to output information about variables and stack traces prettily and comfortably.
4
 *
5
 * https://github.com/kint-php/kint
6
 */
7
8
9
if ( defined( 'KINT_DIR' ) ) return;
10
11
12
define( 'KINT_DIR', dirname( __FILE__ ) . '/' );
13
define( 'KINT_PHP53', version_compare( PHP_VERSION, '5.3.0' ) >= 0 );
14
15
require KINT_DIR . 'config.default.php';
16
require KINT_DIR . 'inc/kintVariableData.class.php';
17
require KINT_DIR . 'inc/kintParser.class.php';
18
require KINT_DIR . 'inc/kintObject.class.php';
19
require KINT_DIR . 'decorators/rich.php';
20
require KINT_DIR . 'decorators/plain.php';
21
22
if ( is_readable( KINT_DIR . 'config.php' ) ) {
23
	require KINT_DIR . 'config.php';
24
}
25
26
# init settings
27
if ( !empty( $GLOBALS['_kint_settings'] ) ) {
28
	Kint::enabled( $GLOBALS['_kint_settings']['enabled'] );
29
30
	foreach ( $GLOBALS['_kint_settings'] as $key => $val ) {
31
		property_exists( 'Kint', $key ) and Kint::$$key = $val;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
32
	}
33
34
	unset( $GLOBALS['_kint_settings'], $key, $val );
35
}
36
37
class Kint
38
{
39
	// these are all public and 1:1 config array keys so you can switch them easily
40
	private static $_enabledMode; # stores mode and active statuses
41
42
	public static $returnOutput;
43
	public static $fileLinkFormat;
44
	public static $displayCalledFrom;
45
	public static $charEncodings;
46
	public static $maxStrLength;
47
	public static $appRootDirs;
48
	public static $maxLevels;
49
	public static $theme;
50
	public static $expandedByDefault;
51
52
	public static $cliDetection;
53
	public static $cliColors;
54
55
	const MODE_RICH       = 'r';
56
	const MODE_WHITESPACE = 'w';
57
	const MODE_CLI        = 'c';
58
	const MODE_PLAIN      = 'p';
59
60
61
	public static $aliases = array(
62
		'methods'   => array(
63
			array( 'kint', 'dump' ),
64
			array( 'kint', 'trace' ),
65
		),
66
		'functions' => array(
67
			'd',
68
			'dd',
69
			'ddd',
70
			's',
71
			'sd',
72
		)
73
	);
74
75
	private static $_firstRun = true;
76
77
	/**
78
	 * Enables or disables Kint, can globally enforce the rendering mode. If called without parameters, returns the
79
	 * current mode.
80
	 *
81
	 * @param mixed $forceMode
82
	 *      null or void - return current mode
83
	 *      false        - disable (no output)
84
	 *      true         - enable and detect cli automatically
85
	 *      Kint::MODE_* - enable and force selected mode disregarding detection and function
86
	 *                     shorthand (s()/d()), note that you can still override this
87
	 *                     with the "~" modifier
88
	 *
89
	 * @return mixed        previously set value if a new one is passed
90
	 */
91
	public static function enabled( $forceMode = null )
92
	{
93
		# act both as a setter...
94
		if ( isset( $forceMode ) ) {
95
			$before             = self::$_enabledMode;
96
			self::$_enabledMode = $forceMode;
97
98
			return $before;
99
		}
100
101
		# ...and a getter
102
		return self::$_enabledMode;
103
	}
104
105
	/**
106
	 * Prints a debug backtrace, same as Kint::dump(1)
107
	 *
108
	 * @param array $trace [OPTIONAL] you can pass your own trace, otherwise, `debug_backtrace` will be called
109
	 *
110
	 * @return mixed
111
	 */
112
	public static function trace( $trace = null )
113
	{
114
		if ( !self::enabled() ) return '';
115
116
		return self::dump( isset( $trace ) ? $trace : debug_backtrace( true ) );
117
	}
118
119
120
	/**
121
	 * Dump information about variables, accepts any number of parameters, supports modifiers:
122
	 *
123
	 *  clean up any output before kint and place the dump at the top of page:
124
	 *   - Kint::dump()
125
	 *  *****
126
	 *  expand all nodes on display:
127
	 *   ! Kint::dump()
128
	 *  *****
129
	 *  dump variables disregarding their depth:
130
	 *   + Kint::dump()
131
	 *  *****
132
	 *  return output instead of displaying it:
133
	 *   @ Kint::dump()
134
	 *  *****
135
	 *  force output as plain text
136
	 *   ~ Kint::dump()
137
	 *
138
	 * Modifiers are supported by all dump wrapper functions, including Kint::trace(). Space is optional.
139
	 *
140
	 *
141
	 * You can also use the following shorthand to display debug_backtrace():
142
	 *   Kint::dump( 1 );
143
	 *
144
	 * Passing the result from debug_backtrace() to kint::dump() as a single parameter will display it as trace too:
145
	 *   $trace = debug_backtrace( true );
146
	 *   Kint::dump( $trace );
147
	 *  Or simply:
148
	 *   Kint::dump( debug_backtrace() );
149
	 *
150
	 *
151
	 * @param mixed $data
152
	 *
153
	 * @return void|string
154
	 */
155
	public static function dump( $data = null )
156
	{
157
		if ( !self::enabled() ) return '';
158
159
		list( $names, $modifiers, $callee, $previousCaller, $miniTrace ) = self::_getCalleeInfo(
160
			defined( 'DEBUG_BACKTRACE_IGNORE_ARGS' )
161
				? debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS )
162
				: debug_backtrace()
163
		);
164
		$modeOldValue     = self::enabled();
165
		$firstRunOldValue = self::$_firstRun;
166
167
		# process modifiers: @, +, !, ~ and -
168
		if ( strpos( $modifiers, '-' ) !== false ) {
169
			self::$_firstRun = true;
170
			while ( ob_get_level() ) {
171
				ob_end_clean();
172
			}
173
		}
174
		if ( strpos( $modifiers, '!' ) !== false ) {
175
			$expandedByDefaultOldValue = self::$expandedByDefault;
176
			self::$expandedByDefault   = true;
177
		}
178
		if ( strpos( $modifiers, '+' ) !== false ) {
179
			$maxLevelsOldValue = self::$maxLevels;
180
			self::$maxLevels   = false;
181
		}
182
		if ( strpos( $modifiers, '@' ) !== false ) {
183
			$returnOldValue     = self::$returnOutput;
184
			self::$returnOutput = true;
185
			self::$_firstRun    = true;
186
		}
187
		if ( strpos( $modifiers, '~' ) !== false ) {
188
			self::enabled( self::MODE_WHITESPACE );
189
		}
190
191
		# set mode for current run
192
		$mode = self::enabled();
193
		if ( $mode === true ) {
194
			$mode = (PHP_SAPI === 'cli' && self::$cliDetection === true)
195
				? self::MODE_CLI
196
				: self::MODE_RICH;
197
		}
198
		self::enabled( $mode );
199
200
		$decorator = self::enabled() === self::MODE_RICH
201
			? 'Kint_Decorators_Rich'
202
			: 'Kint_Decorators_Plain';
203
204
		$output = '';
205
		if ( self::$_firstRun ) {
206
			$output .= call_user_func( array( $decorator, 'init' ) );
207
		}
208
209
210
		$trace = false;
211
		if ( $names === array( null ) && func_num_args() === 1 && $data === 1 ) { # Kint::dump(1) shorthand
212
			$trace = KINT_PHP53 ? debug_backtrace( true ) : debug_backtrace();
213
		} elseif ( func_num_args() === 1 && is_array( $data ) ) {
214
			$trace = $data; # test if the single parameter is result of debug_backtrace()
215
		}
216
		$trace and $trace = self::_parseTrace( $trace );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
217
218
219
		$output .= call_user_func( array( $decorator, 'wrapStart' ) );
220
		if ( $trace ) {
221
			$output .= call_user_func( array( $decorator, 'decorateTrace' ), $trace );
222
		} else {
223
			$data = func_num_args() === 0
224
				? array( "[[no arguments passed]]" )
225
				: func_get_args();
226
227
			foreach ( $data as $k => $argument ) {
228
				kintParser::reset();
229
				# when the dump arguments take long to generate output, user might have changed the file and
230
				# Kint might not parse the arguments correctly, so check if names are set and while the
231
				# displayed names might be wrong, at least don't throw an error
232
				$output .= call_user_func(
233
					array( $decorator, 'decorate' ),
234
					kintParser::factory( $argument, isset( $names[ $k ] ) ? $names[ $k ] : '' )
235
				);
236
			}
237
		}
238
239
		$output .= call_user_func( array( $decorator, 'wrapEnd' ), $callee, $miniTrace, $previousCaller );
240
241
		self::enabled( $modeOldValue );
242
243
		self::$_firstRun = false;
244
		if ( strpos( $modifiers, '~' ) !== false ) {
245
			self::$_firstRun = $firstRunOldValue;
246
		} else {
247
			self::enabled( $modeOldValue );
248
		}
249
		if ( strpos( $modifiers, '!' ) !== false ) {
250
			self::$expandedByDefault = $expandedByDefaultOldValue;
0 ignored issues
show
Bug introduced by
The variable $expandedByDefaultOldValue does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
251
		}
252
		if ( strpos( $modifiers, '+' ) !== false ) {
253
			self::$maxLevels = $maxLevelsOldValue;
0 ignored issues
show
Bug introduced by
The variable $maxLevelsOldValue does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
254
		}
255
		if ( strpos( $modifiers, '@' ) !== false ) {
256
			self::$returnOutput = $returnOldValue;
0 ignored issues
show
Bug introduced by
The variable $returnOldValue does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
257
			self::$_firstRun    = $firstRunOldValue;
258
			return $output;
259
		}
260
261
		if ( self::$returnOutput ) return $output;
262
263
		echo $output;
264
		return '';
265
	}
266
267
268
	/**
269
	 * generic path display callback, can be configured in the settings; purpose is to show relevant path info and hide
270
	 * as much of the path as possible.
271
	 *
272
	 * @param string $file
273
	 *
274
	 * @return string
275
	 */
276
	public static function shortenPath( $file )
277
	{
278
		$file          = str_replace( '\\', '/', $file );
279
		$shortenedName = $file;
280
		$replaced      = false;
281
		if ( is_array( self::$appRootDirs ) ) foreach ( self::$appRootDirs as $path => $replaceString ) {
282
			if ( empty( $path ) ) continue;
283
284
			$path = str_replace( '\\', '/', $path );
285
286
			if ( strpos( $file, $path ) === 0 ) {
287
				$shortenedName = $replaceString . substr( $file, strlen( $path ) );
288
				$replaced      = true;
289
				break;
290
			}
291
		}
292
293
		# fallback to find common path with Kint dir
294
		if ( !$replaced ) {
295
			$pathParts = explode( '/', str_replace( '\\', '/', KINT_DIR ) );
296
			$fileParts = explode( '/', $file );
297
			$i         = 0;
298
			foreach ( $fileParts as $i => $filePart ) {
299
				if ( !isset( $pathParts[ $i ] ) || $pathParts[ $i ] !== $filePart ) break;
300
			}
301
302
			$shortenedName = ( $i ? '.../' : '' ) . implode( '/', array_slice( $fileParts, $i ) );
303
		}
304
305
		return $shortenedName;
306
	}
307
308
	public static function getIdeLink( $file, $line )
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
309
	{
310
		return str_replace( array( '%f', '%l' ), array( $file, $line ), self::$fileLinkFormat );
311
	}
312
313
	/**
314
	 * trace helper, shows the place in code inline
315
	 *
316
	 * @param string $file full path to file
317
	 * @param int    $lineNumber the line to display
318
	 * @param int    $padding surrounding lines to show besides the main one
319
	 *
320
	 * @return bool|string
321
	 */
322
	private static function _showSource( $file, $lineNumber, $padding = 7 )
323
	{
324
		if ( !$file OR !is_readable( $file ) ) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
325
			# continuing will cause errors
326
			return false;
327
		}
328
329
		# open the file and set the line position
330
		$file = fopen( $file, 'r' );
331
		$line = 0;
332
333
		# Set the reading range
334
		$range = array(
335
			'start' => $lineNumber - $padding,
336
			'end'   => $lineNumber + $padding
337
		);
338
339
		# set the zero-padding amount for line numbers
340
		$format = '% ' . strlen( $range['end'] ) . 'd';
341
342
		$source = '';
343
		while ( ( $row = fgets( $file ) ) !== false ) {
344
			# increment the line number
345
			if ( ++$line > $range['end'] ) {
346
				break;
347
			}
348
349
			if ( $line >= $range['start'] ) {
350
				# make the row safe for output
351
				$row = htmlspecialchars( $row, ENT_NOQUOTES, 'UTF-8' );
352
353
				# trim whitespace and sanitize the row
354
				$row = '<span>' . sprintf( $format, $line ) . '</span> ' . $row;
355
356
				if ( $line === $lineNumber ) {
357
					# apply highlighting to this row
358
					$row = '<div class="kint-highlight">' . $row . '</div>';
359
				} else {
360
					$row = '<div>' . $row . '</div>';
361
				}
362
363
				# add to the captured source
364
				$source .= $row;
365
			}
366
		}
367
368
		# close the file
369
		fclose( $file );
370
371
		return $source;
372
	}
373
374
375
	/**
376
	 * returns parameter names that the function was passed, as well as any predefined symbols before function
377
	 * call (modifiers)
378
	 *
379
	 * @param array $trace
380
	 *
381
	 * @return array( $parameters, $modifier, $callee, $previousCaller )
0 ignored issues
show
Documentation introduced by
The doc-type array( could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
382
	 */
383
	private static function _getCalleeInfo( $trace )
384
	{
385
		$previousCaller = array();
386
		$miniTrace      = array();
387
		$prevStep       = array();
388
389
		# go from back of trace to find first occurrence of call to Kint or its wrappers
390
		while ( $step = array_pop( $trace ) ) {
391
392
			if ( self::_stepIsInternal( $step ) ) {
393
				$previousCaller = $prevStep;
394
				break;
395
			} elseif ( isset( $step['file'], $step['line'] ) ) {
396
				unset( $step['object'], $step['args'] );
397
				array_unshift( $miniTrace, $step );
398
			}
399
400
			$prevStep = $step;
401
		}
402
		$callee = $step;
403
404
		if ( !isset( $callee['file'] ) || !is_readable( $callee['file'] ) )
405
			return array( null, null, $callee, $previousCaller, $miniTrace );
406
407
408
		# open the file and read it up to the position where the function call expression ended
409
		$file   = fopen( $callee['file'], 'r' );
410
		$line   = 0;
411
		$source = '';
412
		while ( ( $row = fgets( $file ) ) !== false ) {
413
			if ( ++$line > $callee['line'] ) break;
414
			$source .= $row;
415
		}
416
		fclose( $file );
417
		$source = self::_removeAllButCode( $source );
418
419
420
		if ( empty( $callee['class'] ) ) {
421
			$codePattern = $callee['function'];
422
		} else {
423
			if ( $callee['type'] === '::' ) {
424
				$codePattern = $callee['class'] . "\x07*" . $callee['type'] . "\x07*" . $callee['function'];;
425
			} else /*if ( $callee['type'] === '->' )*/ {
426
				$codePattern = ".*\x07*" . $callee['type'] . "\x07*" . $callee['function'];;
427
			}
428
		}
429
430
		// todo if more than one call in one line - not possible to determine variable names
431
		// todo does not recognize string concat
432
		# get the position of the last call to the function
433
		preg_match_all( "
434
            [
435
            # beginning of statement
436
            [\x07{(]
437
438
            # search for modifiers (group 1)
439
            ([-+!@~]*)?
440
441
            # spaces
442
            \x07*
443
444
            # check if output is assigned to a variable (group 2) todo: does not detect concat
445
            (
446
                \\$[a-z0-9_]+ # variable
447
                \x07*\\.?=\x07*  # assignment
448
            )?
449
450
            # possibly a namespace symbol
451
            \\\\?
452
453
			# spaces again
454
            \x07*
455
456
            # main call to Kint
457
            ({$codePattern})
458
459
			# spaces everywhere
460
            \x07*
461
462
            # find the character where kint's opening bracket resides (group 3)
463
            (\\()
464
465
            ]ix",
466
			$source,
467
			$matches,
468
			PREG_OFFSET_CAPTURE
469
		);
470
471
		$modifiers  = end( $matches[1] );
472
		$assignment = end( $matches[2] );
473
		$callToKint = end( $matches[3] );
474
		$bracket    = end( $matches[4] );
475
476
		if ( empty( $callToKint ) ) {
477
			# if a wrapper is misconfigured, don't display the whole file as variable name
478
			return array( array(), $modifiers, $callee, $previousCaller, $miniTrace );
479
		}
480
481
		$modifiers = $modifiers[0];
482
		if ( $assignment[1] !== -1 ) {
483
			$modifiers .= '@';
484
		}
485
486
		$paramsString = preg_replace( "[\x07+]", ' ', substr( $source, $bracket[1] + 1 ) );
487
		# we now have a string like this:
488
		# <parameters passed>); <the rest of the last read line>
489
490
		# remove everything in brackets and quotes, we don't need nested statements nor literal strings which would
491
		# only complicate separating individual arguments
492
		$c              = strlen( $paramsString );
493
		$inString       = $escaped = $openedBracket = $closingBracket = false;
494
		$i              = 0;
495
		$inBrackets     = 0;
496
		$openedBrackets = array();
497
498
		while ( $i < $c ) {
499
			$letter = $paramsString[ $i ];
500
501
			if ( !$inString ) {
502
				if ( $letter === '\'' || $letter === '"' ) {
503
					$inString = $letter;
504
				} elseif ( $letter === '(' || $letter === '[' ) {
505
					$inBrackets++;
506
					$openedBrackets[] = $openedBracket = $letter;
507
					$closingBracket   = $openedBracket === '(' ? ')' : ']';
508
				} elseif ( $inBrackets && $letter === $closingBracket ) {
509
					$inBrackets--;
510
					array_pop( $openedBrackets );
511
					$openedBracket  = end( $openedBrackets );
512
					$closingBracket = $openedBracket === '(' ? ')' : ']';
513
				} elseif ( !$inBrackets && $letter === ')' ) {
514
					$paramsString = substr( $paramsString, 0, $i );
515
					break;
516
				}
517
			} elseif ( $letter === $inString && !$escaped ) {
518
				$inString = false;
519
			}
520
521
			# replace whatever was inside quotes or brackets with untypeable characters, we don't
522
			# need that info. We'll later replace the whole string with '...'
523
			if ( $inBrackets > 0 ) {
524
				if ( $inBrackets > 1 || $letter !== $openedBracket ) {
525
					$paramsString[ $i ] = "\x07";
526
				}
527
			}
528
			if ( $inString ) {
529
				if ( $letter !== $inString || $escaped ) {
530
					$paramsString[ $i ] = "\x07";
531
				}
532
			}
533
534
			$escaped = !$escaped && ( $letter === '\\' );
535
			$i++;
536
		}
537
538
		# by now we have an un-nested arguments list, lets make it to an array for processing further
539
		$arguments = explode( ',', preg_replace( "[\x07+]", '...', $paramsString ) );
540
541
		# test each argument whether it was passed literary or was it an expression or a variable name
542
		$parameters = array();
543
		$blacklist  = array( 'null', 'true', 'false', 'array(...)', 'array()', '"..."', '[...]', 'b"..."', );
544
		foreach ( $arguments as $argument ) {
545
			$argument = trim( $argument );
546
547
			if ( is_numeric( $argument )
548
				|| in_array( str_replace( "'", '"', strtolower( $argument ) ), $blacklist, true )
549
			) {
550
				$parameters[] = null;
551
			} else {
552
				$parameters[] = $argument;
553
			}
554
		}
555
556
		return array( $parameters, $modifiers, $callee, $previousCaller, $miniTrace );
557
	}
558
559
	/**
560
	 * removes comments and zaps whitespace & <?php tags from php code, makes for easier further parsing
561
	 *
562
	 * @param string $source
563
	 *
564
	 * @return string
565
	 */
566
	private static function _removeAllButCode( $source )
567
	{
568
		$commentTokens    = array(
569
			T_COMMENT => true, T_INLINE_HTML => true, T_DOC_COMMENT => true
570
		);
571
		$whiteSpaceTokens = array(
572
			T_WHITESPACE => true, T_CLOSE_TAG => true,
573
			T_OPEN_TAG   => true, T_OPEN_TAG_WITH_ECHO => true,
574
		);
575
576
		$cleanedSource = '';
577
		foreach ( token_get_all( $source ) as $token ) {
578
			if ( is_array( $token ) ) {
579
				if ( isset( $commentTokens[ $token[0] ] ) ) continue;
580
581
				if ( isset( $whiteSpaceTokens[ $token[0] ] ) ) {
582
					$token = "\x07";
583
				} else {
584
					$token = $token[1];
585
				}
586
			} elseif ( $token === ';' ) {
587
				$token = "\x07";
588
			}
589
590
			$cleanedSource .= $token;
591
		}
592
		return $cleanedSource;
593
	}
594
595
	/**
596
	 * returns whether current trace step belongs to Kint or its wrappers
597
	 *
598
	 * @param $step
599
	 *
600
	 * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
601
	 */
602
	private static function _stepIsInternal( $step )
603
	{
604
		if ( isset( $step['class'] ) ) {
605
			foreach ( self::$aliases['methods'] as $alias ) {
606
				if ( $alias[0] === strtolower( $step['class'] ) && $alias[1] === strtolower( $step['function'] ) ) {
607
					return true;
608
				}
609
			}
610
			return false;
611
		} else {
612
			return in_array( strtolower( $step['function'] ), self::$aliases['functions'], true );
613
		}
614
	}
615
616
	private static function _parseTrace( array $data )
617
	{
618
		$trace       = array();
619
		$traceFields = array( 'file', 'line', 'args', 'class' );
620
		$fileFound   = false; # file element must exist in one of the steps
621
622
		# validate whether a trace was indeed passed
623
		while ( $step = array_pop( $data ) ) {
624
			if ( !is_array( $step ) || !isset( $step['function'] ) ) return false;
625
			if ( !$fileFound && isset( $step['file'] ) && file_exists( $step['file'] ) ) {
626
				$fileFound = true;
627
			}
628
629
			$valid = false;
630
			foreach ( $traceFields as $element ) {
631
				if ( isset( $step[ $element ] ) ) {
632
					$valid = true;
633
					break;
634
				}
635
			}
636
			if ( !$valid ) return false;
637
638
			if ( self::_stepIsInternal( $step ) ) {
639
				$step = array(
640
					'file'     => $step['file'],
641
					'line'     => $step['line'],
642
					'function' => '',
643
				);
644
				array_unshift( $trace, $step );
645
				break;
646
			}
647
			if ( $step['function'] !== 'spl_autoload_call' ) { # meaningless
648
				array_unshift( $trace, $step );
649
			}
650
		}
651
		if ( !$fileFound ) return false;
652
653
		$output = array();
654
		foreach ( $trace as $step ) {
655
			if ( isset( $step['file'] ) ) {
656
				$file = $step['file'];
657
658
				if ( isset( $step['line'] ) ) {
659
					$line = $step['line'];
660
					# include the source of this step
661
					if ( self::enabled() === self::MODE_RICH ) {
662
						$source = self::_showSource( $file, $line );
663
					}
664
				}
665
			}
666
667
			$function = $step['function'];
668
669
			if ( in_array( $function, array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
670
				if ( empty( $step['args'] ) ) {
671
					# no arguments
672
					$args = array();
673
				} else {
674
					# sanitize the included file path
675
					$args = array( 'file' => self::shortenPath( $step['args'][0] ) );
676
				}
677
			} elseif ( isset( $step['args'] ) ) {
678
				if ( empty( $step['class'] ) && !function_exists( $function ) ) {
679
					# introspection on closures or language constructs in a stack trace is impossible before PHP 5.3
680
					$params = null;
681
				} else {
682
					try {
683
						if ( isset( $step['class'] ) ) {
684
							if ( method_exists( $step['class'], $function ) ) {
685
								$reflection = new ReflectionMethod( $step['class'], $function );
686
							} else if ( isset( $step['type'] ) && $step['type'] == '::' ) {
687
								$reflection = new ReflectionMethod( $step['class'], '__callStatic' );
688
							} else {
689
								$reflection = new ReflectionMethod( $step['class'], '__call' );
690
							}
691
						} else {
692
							$reflection = new ReflectionFunction( $function );
693
						}
694
695
						# get the function parameters
696
						$params = $reflection->getParameters();
697
					} catch ( Exception $e ) { # avoid various PHP version incompatibilities
698
						$params = null;
699
					}
700
				}
701
702
				$args = array();
703
				foreach ( $step['args'] as $i => $arg ) {
704
					if ( isset( $params[ $i ] ) ) {
705
						# assign the argument by the parameter name
706
						$args[ $params[ $i ]->name ] = $arg;
707
					} else {
708
						# assign the argument by number
709
						$args[ '#' . ( $i + 1 ) ] = $arg;
710
					}
711
				}
712
			}
713
714
			if ( isset( $step['class'] ) ) {
715
				# Class->method() or Class::method()
716
				$function = $step['class'] . $step['type'] . $function;
717
			}
718
719
			// todo it's possible to parse the object name out from the source!
720
			$output[] = array(
721
				'function' => $function,
722
				'args'     => isset( $args ) ? $args : null,
723
				'file'     => isset( $file ) ? $file : null,
724
				'line'     => isset( $line ) ? $line : null,
725
				'source'   => isset( $source ) ? $source : null,
726
				'object'   => isset( $step['object'] ) ? $step['object'] : null,
727
			);
728
729
			unset( $function, $args, $file, $line, $source );
730
		}
731
732
		return $output;
733
	}
734
}
735
736
737 View Code Duplication
if ( !function_exists( 'd' ) ) {
738
	/**
739
	 * Alias of Kint::dump()
740
	 *
741
	 * @return string
742
	 */
743
	function d()
744
	{
745
		if ( !Kint::enabled() ) return '';
746
		$_ = func_get_args();
747
		return call_user_func_array( array( 'Kint', 'dump' ), $_ );
748
	}
749
}
750
751 View Code Duplication
if ( !function_exists( 'dd' ) ) {
752
	/**
753
	 * Alias of Kint::dump()
754
	 * [!!!] IMPORTANT: execution will halt after call to this function
755
	 *
756
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
757
	 * @deprecated
758
	 */
759
	function dd()
760
	{
761
		if ( !Kint::enabled() ) return '';
762
763
		echo "<pre>Kint: dd() is being deprecated, please use ddd() instead</pre>\n";
764
		$_ = func_get_args();
765
		call_user_func_array( array( 'Kint', 'dump' ), $_ );
766
		die;
0 ignored issues
show
Coding Style Compatibility introduced by
The function dd() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
767
	}
768
}
769
770 View Code Duplication
if ( !function_exists( 'ddd' ) ) {
771
	/**
772
	 * Alias of Kint::dump()
773
	 * [!!!] IMPORTANT: execution will halt after call to this function
774
	 *
775
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
776
	 */
777
	function ddd()
778
	{
779
		if ( !Kint::enabled() ) return '';
780
		$_ = func_get_args();
781
		call_user_func_array( array( 'Kint', 'dump' ), $_ );
782
		die;
0 ignored issues
show
Coding Style Compatibility introduced by
The function ddd() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
783
	}
784
}
785
786
if ( !function_exists( 's' ) ) {
787
	/**
788
	 * Alias of Kint::dump(), however the output is in plain htmlescaped text and some minor visibility enhancements
789
	 * added. If run in CLI mode, output is pure whitespace.
790
	 *
791
	 * To force rendering mode without autodetecting anything:
792
	 *
793
	 *  Kint::enabled( Kint::MODE_PLAIN );
794
	 *  Kint::dump( $variable );
795
	 *
796
	 * [!!!] IMPORTANT: execution will halt after call to this function
797
	 *
798
	 * @return string
799
	 */
800
	function s()
801
	{
802
		$enabled = Kint::enabled();
803
		if ( !$enabled ) return '';
804
805
		if ( $enabled === Kint::MODE_WHITESPACE ) { # if already in whitespace, don't elevate to plain
806
			$restoreMode = Kint::MODE_WHITESPACE;
807
		} else {
808
			$restoreMode = Kint::enabled( # remove cli colors in cli mode; remove rich interface in HTML mode
809
				PHP_SAPI === 'cli' ? Kint::MODE_WHITESPACE : Kint::MODE_PLAIN
810
			);
811
		}
812
813
		$params = func_get_args();
814
		$dump   = call_user_func_array( array( 'Kint', 'dump' ), $params );
815
		Kint::enabled( $restoreMode );
816
		return $dump;
817
	}
818
}
819
820
if ( !function_exists( 'sd' ) ) {
821
	/**
822
	 * @see s()
823
	 *
824
	 * [!!!] IMPORTANT: execution will halt after call to this function
825
	 *
826
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
827
	 */
828
	function sd()
829
	{
830
		$enabled = Kint::enabled();
831
		if ( !$enabled ) return '';
832
833
		if ( $enabled !== Kint::MODE_WHITESPACE ) {
834
			Kint::enabled(
835
				PHP_SAPI === 'cli' ? Kint::MODE_WHITESPACE : Kint::MODE_PLAIN
836
			);
837
		}
838
839
		$params = func_get_args();
840
		call_user_func_array( array( 'Kint', 'dump' ), $params );
841
		die;
0 ignored issues
show
Coding Style Compatibility introduced by
The function sd() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
842
	}
843
}
844