Skip to content

Commit

Permalink
GlobalVariablesOverride: improve the error message when an assignment…
Browse files Browse the repository at this point in the history
… to $GLOBALS is found

Previously, the error message would just show the rather non-descript `$GLOBALS`, now it will show `$GLOBALS['array_key']`.
  • Loading branch information
jrfnl committed Aug 19, 2018
1 parent 7c5443b commit d6e4782
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 ) {
Expand Down Expand Up @@ -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 . '\']';
}

/*
Expand Down Expand Up @@ -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 );
}

/**
Expand Down Expand Up @@ -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
);
}

Expand Down

0 comments on commit d6e4782

Please sign in to comment.