From d6e478239afacca2ddc06c5827d4633051c48f17 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 19 Aug 2018 07:25:50 +0200 Subject: [PATCH] GlobalVariablesOverride: improve the error message when an assignment to $GLOBALS is found Previously, the error message would just show the rather non-descript `$GLOBALS`, now it will show `$GLOBALS['array_key']`. --- .../WP/GlobalVariablesOverrideSniff.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php b/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php index 3280d6f3c9..1d628bbab3 100644 --- a/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php +++ b/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php @@ -153,6 +153,7 @@ protected function process_variable_assignment( $stackPtr ) { $token = $this->tokens[ $stackPtr ]; $var_name = substr( $token['content'], 1 ); // Strip the dollar sign. + $data = array(); // Determine the variable name for `$GLOBALS['array_key']`. if ( 'GLOBALS' === $var_name ) { @@ -186,6 +187,9 @@ protected function process_variable_assignment( $stackPtr ) { // Shouldn't happen, but just in case. return; } + + // Set up the data for the error message. + $data[] = '$GLOBALS[\'' . $var_name . '\']'; } /* @@ -228,7 +232,7 @@ protected function process_variable_assignment( $stackPtr ) { } // Still here ? In that case, the WP global variable is being tampered with. - $this->add_error( $stackPtr ); + $this->add_error( $stackPtr, $data ); } /** @@ -359,16 +363,23 @@ protected function maybe_add_error( $stackPtr ) { * * @since 1.1.0 * - * @param int $stackPtr The position of the token to throw the error for. + * @param int $stackPtr The position of the token to throw the error for. + * @param array $data Optional. Array containing one entry holding the + * name of the variable being overruled. + * Defaults to the 'content' of the $stackPtr token. * * @return void */ - protected function add_error( $stackPtr ) { + protected function add_error( $stackPtr, $data = array() ) { + if ( empty( $data ) ) { + $data[] = $this->tokens[ $stackPtr ]['content']; + } + $this->phpcsFile->addError( 'Overriding WordPress globals is prohibited. Found assignment to %s', $stackPtr, 'OverrideProhibited', - array( $this->tokens[ $stackPtr ]['content'] ) + $data ); }