Created
January 20, 2012 22:34
-
-
Save nacin/1650009 to your computer and use it in GitHub Desktop.
Find Unset Local Variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$path_to_file = '...'; | |
$file = explode( "\n", file_get_contents( $path_to_file ) ); | |
// Finds local variables that are undeclared. | |
// | |
// Doesn't understand foreach() variables, dockblocks, sprintf arguments, | |
// variables returned by reference from a function like preg_match() or parse_str(), | |
// assignments that don't start a line, and a few other things. | |
$set_variables = array(); | |
foreach ( $file as $num => $line ) { | |
if ( 0 === strpos( $line, 'function ' ) || $line === '}' ) { | |
if ( $line === '}' && $found ) | |
echo "----------------------------\n\n"; | |
$found = false; | |
$set_variables = array( '$_POST', '$_GET', '$_REQUEST', '$_SERVER', '$GLOBALS' ); | |
if ( false !== strpos( $line, ' $action ' ) ) | |
$set_variables[] = '$action'; | |
} | |
if ( preg_match( '/^\s+global (\$[a-zA-Z_\x7f-\xff][, \$a-zA-Z0-9_\x7f-\xff,]*);/', $line, $match ) ) | |
$set_variables = array_merge( $set_variables, explode( ", ", $match[1] ) ); | |
if ( preg_match( '/^\s+(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s+=/', $line, $match ) ) | |
$set_variables[] = $match[1]; | |
if ( preg_match_all( '/\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $line, $variables ) ) { | |
foreach ( $variables[0] as $variable ) { | |
if ( ! in_array( $variable, $set_variables ) ) { | |
$found = true; | |
echo "[ $num ] $variable\n $line\n\n"; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is probably easier to use the tokenizer for. That way, you can check if a variable is declared within a block properly.