Skip to content

Commit

Permalink
Fix bug in function name comparison.
Browse files Browse the repository at this point in the history
AbstractFunctionRestrictionsSniff did not allow for case-insensitive comparison of function names.

> **Note**: Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.

Ref: http://php.net/manual/en/functions.user-defined.php

Also:
* Better be safe than sorry, so `preg_quote()`-ing the function names passed to this class.
* Minor memory management improvement: no need to remember the matched function name.
  • Loading branch information
jrfnl committed Jul 16, 2016
1 parent b5c13f1 commit 0b29cff
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions WordPress/AbstractFunctionRestrictionsSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) {
continue;
}

$functions = implode( '|', $group['functions'] );
$functions = preg_replace( '#[^\.]\*#', '.*', $functions ); // So you can use * instead of .*
$functions = array_map( array( $this, 'prepare_functionname_for_regex' ), $group['functions'] );
$functions = implode( '|', $functions );

if ( preg_match( '#\b(' . $functions . ')\b#', $token['content'] ) < 1 ) {
if ( preg_match( '`\b(?:' . $functions . ')\b`i', $token['content'] ) < 1 ) {
continue;
}

Expand All @@ -130,4 +130,22 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) {

} // end process()

/**
* Prepare the function name for use in a regular expression.
*
* The getGroups() method allows for providing function with a wildcard * to target
* a group of functions. This prepare routine takes that into account while still safely
* escaping the function name for use in a regular expression.
*
* @param string $function Function name.
* @return string Regex escaped lowercase function name.
*/
protected function prepare_functionname_for_regex( $function ) {
$function = str_replace( array( '.*', '*' ) , '#', $function ); // Replace wildcards with placeholder.
$function = preg_quote( $function, '`' );
$function = str_replace( '#', '.*', $function ); // Replace placeholder with regex wildcard.

return $function;
}

} // end class

0 comments on commit 0b29cff

Please sign in to comment.