From 600d5c718a069e0f8bffd68d63062f9602d20617 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 23 Sep 2018 01:20:14 +0200 Subject: [PATCH] Sniff::get_declared_namespace_name(): improve code-style independence A namespace declaration can contain whitespace and comments and PHP will just ignore the whitespace and comments when reading the code. Also see: squizlabs/PHP_CodeSniffer 2150 While it is rare to encounter such code, this utility method should handle it correctly. As for the `$namespaceName` to be returned by the method, this should not contain any whitespace or comments encountered. That way the namespace name will be "clean" for examination by sniffs. Includes unit test via the `GlobalVariablesOverride` sniff. --- WordPress/Sniff.php | 14 ++++++++------ .../Tests/WP/GlobalVariablesOverrideUnitTest.4.inc | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 WordPress/Tests/WP/GlobalVariablesOverrideUnitTest.4.inc diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index 24d599da3a..f6cfec7462 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -2369,12 +2369,12 @@ public function get_declared_namespace_name( $stackPtr ) { return false; } - if ( \T_NS_SEPARATOR === $this->tokens[ ( $stackPtr + 1 ) ]['code'] ) { + $nextToken = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); + if ( \T_NS_SEPARATOR === $this->tokens[ $nextToken ]['code'] ) { // Not a namespace declaration, but use of, i.e. `namespace\someFunction();`. return false; } - $nextToken = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $nextToken ]['code'] ) { // Declaration for global namespace when using multiple namespaces in a file. // I.e.: `namespace {}`. @@ -2382,16 +2382,18 @@ public function get_declared_namespace_name( $stackPtr ) { } // Ok, this should be a namespace declaration, so get all the parts together. - $validTokens = array( + $acceptedTokens = array( \T_STRING => true, \T_NS_SEPARATOR => true, - \T_WHITESPACE => true, ); + $validTokens = $acceptedTokens + Tokens::$emptyTokens; $namespaceName = ''; while ( isset( $validTokens[ $this->tokens[ $nextToken ]['code'] ] ) ) { - $namespaceName .= trim( $this->tokens[ $nextToken ]['content'] ); - $nextToken++; + if ( isset( $acceptedTokens[ $this->tokens[ $nextToken ]['code'] ] ) ) { + $namespaceName .= trim( $this->tokens[ $nextToken ]['content'] ); + } + ++$nextToken; } return $namespaceName; diff --git a/WordPress/Tests/WP/GlobalVariablesOverrideUnitTest.4.inc b/WordPress/Tests/WP/GlobalVariablesOverrideUnitTest.4.inc new file mode 100644 index 0000000000..02817b7ba0 --- /dev/null +++ b/WordPress/Tests/WP/GlobalVariablesOverrideUnitTest.4.inc @@ -0,0 +1,14 @@ +