From 242c05f265810756f5c0b0ca30d31792746d3557 Mon Sep 17 00:00:00 2001 From: Shady Sharaf Date: Thu, 12 Dec 2013 06:56:59 +0200 Subject: [PATCH 001/122] Ensure translatable strings, and string domains are not dynamic, fixes #50 --- Sniffs/WP/I18nSniff.php | 93 +++++++++++++++++++++++++++++++++++++++ Tests/WP/I18nUnitTest.inc | 9 ++++ Tests/WP/I18nUnitTest.php | 49 +++++++++++++++++++++ 3 files changed, 151 insertions(+) create mode 100644 Sniffs/WP/I18nSniff.php create mode 100644 Tests/WP/I18nUnitTest.inc create mode 100644 Tests/WP/I18nUnitTest.php diff --git a/Sniffs/WP/I18nSniff.php b/Sniffs/WP/I18nSniff.php new file mode 100644 index 0000000000..cb15b06003 --- /dev/null +++ b/Sniffs/WP/I18nSniff.php @@ -0,0 +1,93 @@ + + */ +class WordPress_Sniffs_WP_I18nSniff implements PHP_CodeSniffer_Sniff +{ + + public $i18n_functions = array( + 'translate', + 'translate_with_gettext_context', + '__', + 'esc_attr__', + 'esc_html__', + '_e', + 'esc_attr_e', + 'esc_html_e', + '_x', + '_ex', + 'esc_attr_x', + 'esc_html_x', + '_n', + '_nx', + '_n_noop', + '_nx_noop', + ); + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return array( + T_STRING, + ); + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + if ( ! in_array( $token['content'], $this->i18n_functions ) ) { + return; + } + + if ( $nextToken = $phpcsFile->findNext( T_WHITESPACE, $stackPtr + 1, null, true ) ) { + if ( $tokens[$nextToken]['code'] != T_OPEN_PARENTHESIS ) { + return; + } + } + + // Get arguments + for ( $i = $nextToken + 1; $i < $tokens[$nextToken]['parenthesis_closer'] - 1; $i++ ) { + if ( in_array( $tokens[$i]['code'], array( T_WHITESPACE, T_COMMA,T_CONSTANT_ENCAPSED_STRING ) ) ) { + continue; + } + + if ( $tokens[$i]['code'] === T_DOUBLE_QUOTED_STRING ) { + $string = $tokens[$i]['content']; + if ( preg_match( '#\$#', $string ) > 0 ) { + $phpcsFile->addError( 'Translatable strings should not contain variables, found ' . $tokens[$i]['content'], $i ); + return; + } + continue; + } + + $phpcsFile->addError( sprintf( 'Translatable string expected, but found "%s"', $tokens[$i]['content'] ), $i ); + return; + } + + }//end process() + + +}//end class diff --git a/Tests/WP/I18nUnitTest.inc b/Tests/WP/I18nUnitTest.inc new file mode 100644 index 0000000000..9eadf7a145 --- /dev/null +++ b/Tests/WP/I18nUnitTest.inc @@ -0,0 +1,9 @@ + + */ +class WordPress_Tests_WP_I18nUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() + { + return array( + 3 => 1, + 7 => 1, + 9 => 1, + ); + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() + { + return array(); + + }//end getWarningList() + + +}//end class From 94c0030445be3e6cf8508b7c626fde8d33cbbbaa Mon Sep 17 00:00:00 2001 From: Cory Simmons Date: Tue, 2 Feb 2016 00:17:06 -0500 Subject: [PATCH 002/122] Add Atom Linter instructions to README :rainbow: Hope you like pictures! :rainbow: --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index d22bcac6a6..26ab047c3d 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,17 @@ Please see “[PHP Code Sniffer with WordPress Coding Standards Integration](htt Install the [sublime-phpcs package](https://github.com/benmatselby/sublime-phpcs), then use the "Switch coding standard" command in the Command Palette to switch between coding standards. +### Atom + +- Install PHP Sniffer and WordPress Coding Standards per above +- Install [linter-phpcs](https://atom.io/packages/linter-phpcs) via Atom's package manager +- Run `which phpcs` to get your `phpcs` executable path +- Enter your `phpcs` executable path and one of the coding standards specified above (e.g. `WordPress`, `WordPress-VIP`, etc.) + +![Atom Linter WordPress Coding Standards configuration](https://cloud.githubusercontent.com/assets/224636/12740504/ce4e97b8-c941-11e5-8d83-c77a2470d58e.png) + +![Atom Linter in action using WordPress Coding Standards](https://cloud.githubusercontent.com/assets/224636/12740542/131c5894-c942-11e5-9e31-5e020c993224.png) + ## Standards subsets The project encompasses a super–set of the sniffs that the WordPress community may need. If you use the `WordPress` standard you will get all the checks. Some of them might be unnecessary for your environment, for example those specific to WordPress VIP coding requirements. From e4b706e041c659dbf31dace209eaf97b9472b92b Mon Sep 17 00:00:00 2001 From: Wes Moberly Date: Thu, 4 Feb 2016 23:50:45 -0500 Subject: [PATCH 003/122] Add whitelisting comment for tax query Fixes #479 --- .../ArrayAssignmentRestrictionsSniff.php | 18 ++++++++--------- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index ded6018dd8..ec4843a325 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -6,15 +6,15 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff implements PHP_CodeSniffer_Sniff +class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_Sniff { /** * Exclude groups * * Example: 'foo,bar' - * - * @var string Comma-delimited group list + * + * @var string Comma-delimited group list */ public $exclude = ''; @@ -22,7 +22,7 @@ class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff implements PHP_Co * Groups of variable data to check against. * Don't use this in extended classes, override getGroups() instead. * This is only used for Unit tests. - * + * * @var array */ public static $groups = array(); @@ -132,7 +132,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) foreach ( $groups as $groupName => $group ) { - + if ( in_array( $groupName, $exclude ) ) { continue; } @@ -165,9 +165,9 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) call_user_func( $addWhat, - $message, - $stackPtr, - $groupName, + $message, + $stackPtr, + $groupName, array( $key, $val ) ); } @@ -183,7 +183,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) /** * Callback to process each confirmed key, to check value * This must be extended to add the logic to check assignment value - * + * * @param string $key Array index / key * @param mixed $val Assigned value * @param int $line Token line diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index 3912301748..06eaf46058 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -39,4 +39,24 @@ public function getGroups() { ) ); } + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + + $this->init( $phpcsFile ); + + if ( $this->has_whitelist_comment( 'tax_query', $stackPtr ) ) { + return; + } + + parent::process( $phpcsFile, $stackPtr ); + } }//end class From 20df378acf65304fe3c89fd5c702c64980fb2fb8 Mon Sep 17 00:00:00 2001 From: Wes Moberly Date: Fri, 5 Feb 2016 14:08:28 -0500 Subject: [PATCH 004/122] Updated unit test to check whitelisting comment. --- WordPress/Tests/VIP/SlowDBQueryUnitTest.inc | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc b/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc index 3d0857780f..dda39302cc 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc @@ -21,3 +21,20 @@ $query = 'foo=bar&meta_key=foo&meta_value=bar'; if ( ! isset( $widget['params'][0] ) ) { $widget['params'][0] = array(); } + + +// Testing whitelisting comments. +$test = array( + + // Single-line statements. + 'tax_query' => array(), // Bad. + 'tax_query' => array(), // WPCS: tax_query ok. + + // Multi-line statement. + 'tax_query' => array( // WPCS: tax_query ok. + array( + 'taxonomy' => 'foo', + ), + ), + ), +); From b44d7b3cef8c8c7cbb4817cde7d6fed98c504814 Mon Sep 17 00:00:00 2001 From: Wes Moberly Date: Fri, 5 Feb 2016 14:17:51 -0500 Subject: [PATCH 005/122] Updated unit test with new expected warning line --- WordPress/Tests/VIP/SlowDBQueryUnitTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php index 74b5755dd2..651640d6b7 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php @@ -42,6 +42,7 @@ public function getWarningList() 15 => 1, 16 => 1, 19 => 2, + 30 => 1, ); }//end getWarningList() From a996a0a4349ceaa4a66fd69f3f40110dd040af7f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 5 Feb 2016 11:30:03 -0800 Subject: [PATCH 006/122] Remove extra right paren from unit test Introduced with #524 --- WordPress/Tests/VIP/SlowDBQueryUnitTest.inc | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc b/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc index dda39302cc..cf40bacb62 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.inc @@ -5,16 +5,16 @@ new WP_Query( array( array( 'key' => 'foo', 'value' => 'bar', - ), ), + ), 'tax_query' => array( array( 'taxonomy' => 'foo', - ), ), + ), 'meta_key' => 'foo', 'meta_value' => 'bar', - ) ); +) ); $query = 'foo=bar&meta_key=foo&meta_value=bar'; @@ -34,7 +34,6 @@ $test = array( 'tax_query' => array( // WPCS: tax_query ok. array( 'taxonomy' => 'foo', - ), ), ), ); From 95dd49e2a23daed9a7b4a94a510afa55e223c2fa Mon Sep 17 00:00:00 2001 From: "J.D. Grimes" Date: Fri, 5 Feb 2016 17:03:57 -0500 Subject: [PATCH 007/122] Note about some issues coming from upstream Explains how to check whether one of our sniffs is the one flagging a piece of code. --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 047aa132fb..e049262d3b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,7 @@ +# Upstream Issues + +Since WPCS employs many sniffs that are part of PHPCS, sometimes an issue will be caused by a bug in PHPCS and not in WPCS itself. Before reporting a bug, you should check what sniff an error is coming from. Running `phpcs` with the `-s` flag, which will show the names of the sniffs with each error. If the error message in question doesn't come from a sniff whose name starts with `WordPress`, the issue is probably a bug in PHPCS itself, and should be [reported there](https://github.com/squizlabs/PHP_CodeSniffer/issues). + # Branches Ongoing development will be done in the `develop` with merges done into `master` once considered stable. From 882ff3a8f62c870fc8262577438d0aed9acaef2d Mon Sep 17 00:00:00 2001 From: Cory Simmons Date: Wed, 10 Feb 2016 06:44:30 -0500 Subject: [PATCH 008/122] Update README.md --- README.md | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 26ab047c3d..eb0548aae9 100644 --- a/README.md +++ b/README.md @@ -91,14 +91,30 @@ Please see “[PHP Code Sniffer with WordPress Coding Standards Integration](htt ### Sublime Text +##### sublime-phpcs package Install the [sublime-phpcs package](https://github.com/benmatselby/sublime-phpcs), then use the "Switch coding standard" command in the Command Palette to switch between coding standards. +##### SublimeLinter-phpcs +sublime-phpcs is insanely powerful, but if you'd prefer automatic linting, [SublimeLinter-phpcs](https://github.com/SublimeLinter/SublimeLinter-phpcs/) can do that. + +- Install PHP Sniffer and WordPress Coding Standards per above. +- Use [Package Control](https://packagecontrol.io/) to search for and install [SublimeLinter](http://www.sublimelinter.com) then [SublimeLinter-phpcs](https://github.com/SublimeLinter/SublimeLinter-phpcs/). +- From the command palette, select `Preferences: SublimeLinter Settings - User` and change `user.linters.phpcs.standard` to the phpcs standard of your choice (e.g. `WordPress`, `WordPress-VIP`, etc.). + +![SublimeLinter-phpcs user settings](https://cloud.githubusercontent.com/assets/224636/12946250/068776ba-cfc1-11e5-816b-109e4e32d21b.png) + +- You may need to restart Sublime for these settings to take effect. Error messages appear in the bottom of the editor. + +![SublimeLinter-phpcs linting](https://cloud.githubusercontent.com/assets/224636/12946326/75986c3a-cfc1-11e5-8537-1243554bbab6.png) + +![SublimeLinter-phpcs error](https://cloud.githubusercontent.com/assets/224636/12946335/8bee5a30-cfc1-11e5-8b5f-b10e8e4a4909.png) + ### Atom -- Install PHP Sniffer and WordPress Coding Standards per above -- Install [linter-phpcs](https://atom.io/packages/linter-phpcs) via Atom's package manager -- Run `which phpcs` to get your `phpcs` executable path -- Enter your `phpcs` executable path and one of the coding standards specified above (e.g. `WordPress`, `WordPress-VIP`, etc.) +- Install PHP Sniffer and WordPress Coding Standards per above. +- Install [linter-phpcs](https://atom.io/packages/linter-phpcs) via Atom's package manager. +- Run `which phpcs` to get your `phpcs` executable path. +- Enter your `phpcs` executable path and one of the coding standards specified above (e.g. `WordPress`, `WordPress-VIP`, etc.). ![Atom Linter WordPress Coding Standards configuration](https://cloud.githubusercontent.com/assets/224636/12740504/ce4e97b8-c941-11e5-8d83-c77a2470d58e.png) From 1be8127436661bebc3752ad797099dda0ba84801 Mon Sep 17 00:00:00 2001 From: Sam Wilson Date: Wed, 9 Mar 2016 09:53:55 +0800 Subject: [PATCH 009/122] Use ConcatenationSpacing rule. --- WordPress-Core/ruleset.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 12bb1afad7..9570c06bf0 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -55,6 +55,12 @@ + + + + + + From 0fc4f46da52d5b9dd49b755ef1eefe992cbbda28 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 14 Mar 2016 15:23:37 -0700 Subject: [PATCH 010/122] Add unit tests from @GaryJones; use WP coding standards --- WordPress/Sniffs/WP/I18nSniff.php | 142 +++++++++++++--------------- WordPress/Tests/WP/I18nUnitTest.inc | 32 +++++++ WordPress/Tests/WP/I18nUnitTest.php | 83 ++++++++-------- 3 files changed, 143 insertions(+), 114 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index cb15b06003..a2ca839a8e 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -8,86 +8,78 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_WP_I18nSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_WP_I18nSniff implements PHP_CodeSniffer_Sniff { - public $i18n_functions = array( - 'translate', - 'translate_with_gettext_context', - '__', - 'esc_attr__', - 'esc_html__', - '_e', - 'esc_attr_e', - 'esc_html_e', - '_x', - '_ex', - 'esc_attr_x', - 'esc_html_x', - '_n', - '_nx', - '_n_noop', - '_nx_noop', - ); + public $i18n_functions = array( + 'translate', + 'translate_with_gettext_context', + '__', + 'esc_attr__', + 'esc_html__', + '_e', + 'esc_attr_e', + 'esc_html_e', + '_x', + '_ex', + 'esc_attr_x', + 'esc_html_x', + '_n', + '_nx', + '_n_noop', + '_nx_noop', + ); - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array( - T_STRING, - ); + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_STRING, + ); + } - }//end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param int $stack_ptr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { + $tokens = $phpcs_file->getTokens(); + $token = $tokens[ $stack_ptr ]; + if ( ! in_array( $token['content'], $this->i18n_functions ) ) { + return; + } - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - $token = $tokens[$stackPtr]; + if ( $next_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ) ) { + if ( T_OPEN_PARENTHESIS !== $tokens[ $next_token ]['code'] ) { + return; + } + } - if ( ! in_array( $token['content'], $this->i18n_functions ) ) { - return; - } + // Get arguments + for ( $i = $next_token + 1; $i < $tokens[ $next_token ]['parenthesis_closer'] - 1; $i += 1 ) { + if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMA, T_CONSTANT_ENCAPSED_STRING ) ) ) { + continue; + } - if ( $nextToken = $phpcsFile->findNext( T_WHITESPACE, $stackPtr + 1, null, true ) ) { - if ( $tokens[$nextToken]['code'] != T_OPEN_PARENTHESIS ) { - return; - } - } + if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { + $string = $tokens[ $i ]['content']; + if ( preg_match( '#\$#', $string ) > 0 ) { + $phpcs_file->addError( 'Translatable strings should not contain variables, found ' . $tokens[ $i ]['content'], $i ); + return; + } + continue; + } - // Get arguments - for ( $i = $nextToken + 1; $i < $tokens[$nextToken]['parenthesis_closer'] - 1; $i++ ) { - if ( in_array( $tokens[$i]['code'], array( T_WHITESPACE, T_COMMA,T_CONSTANT_ENCAPSED_STRING ) ) ) { - continue; - } - - if ( $tokens[$i]['code'] === T_DOUBLE_QUOTED_STRING ) { - $string = $tokens[$i]['content']; - if ( preg_match( '#\$#', $string ) > 0 ) { - $phpcsFile->addError( 'Translatable strings should not contain variables, found ' . $tokens[$i]['content'], $i ); - return; - } - continue; - } - - $phpcsFile->addError( sprintf( 'Translatable string expected, but found "%s"', $tokens[$i]['content'] ), $i ); - return; - } - - }//end process() - - -}//end class + $phpcs_file->addError( sprintf( 'Translatable string expected, but found "%s"', $tokens[ $i ]['content'] ), $i ); + return; + } + } +} diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 9eadf7a145..05a637f243 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -7,3 +7,35 @@ __( "hell\$varo", 'domain' ); // Bad, shouldn't use a string with variables __( $var, 'domain' ); // Bad, shouldn't use variables __( 'string', SOMETHING ); // Bad, shouldn't use CONSTANTS + +__( 'string' . $var, 'domain' ); // Bad, shouldn't use variable for string + +__( $var . 'string', 'domain' ); // Bad, shouldn't use variable for string + +__( SOMETHING, 'domain' ); // Bad, shouldn't use constant for string + +__( 'string' . SOMETHING, 'domain' ); // Bad, shouldn't use constant for string + +__( SOMETHING . 'string', 'domain' ); // Bad, shouldn't use variable for string + +__( 'string', $domain ); // Bad, shouldn't use variable for domain + +__( 'string', 'my' . $domain ); // Bad, shouldn't use variable for domain + +__( 'string', $domain . 'domain' ); // Bad, shouldn't use variable for domain + +__( 'string', 'domain' ); // Good + +_x( 'string', 'context', 'domain' ); // Good + +_x( 'string', $var, 'domain' ); // Bad, shouldn't use variable for context + +_x( 'string', 'context' . $var, 'domain' ); // Bad, shouldn't use variable for context + +_x( 'string', $var . 'context', 'domain' ); // Bad, shouldn't use variable for context + +_x( 'string', SOMETHING, 'domain' ); // Bad, shouldn't use constant for context + +_x( 'string', SOMETHING . 'context', 'domain' ); // Bad, shouldn't use constant for context + +_x( 'string', 'context' . SOMETHING, 'domain' ); // Bad, shouldn't use constant for context diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 01c3edadc9..4242150a90 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -8,42 +8,47 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_WP_I18nUnitTest extends AbstractSniffUnitTest -{ - - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 7 => 1, - 9 => 1, - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - - }//end getWarningList() - - -}//end class +class WordPress_Tests_WP_I18nUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 7 => 1, + 9 => 1, + 11 => 1, + 13 => 1, + 15 => 1, + 17 => 1, + 19 => 1, + 21 => 1, + 23 => 1, + 25 => 1, + 31 => 1, + 33 => 1, + 35 => 1, + 37 => 1, + 39 => 1, + 41 => 1, + ); + } + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + } +} From d02511ed7ed89d2ac7adda99a978114e4f35d69d Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 14 Mar 2016 15:23:54 -0700 Subject: [PATCH 011/122] Add WordPress.WP.I18n to WordPres-Extra --- WordPress-Extra/ruleset.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress-Extra/ruleset.xml b/WordPress-Extra/ruleset.xml index ec60af9cec..f7853ab8c2 100644 --- a/WordPress-Extra/ruleset.xml +++ b/WordPress-Extra/ruleset.xml @@ -33,6 +33,7 @@ + From 022444a01e1432dc04d93fb3172bdb1a94feb0ed Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 14 Mar 2016 15:55:41 -0700 Subject: [PATCH 012/122] Improve checks for interpolated vars --- WordPress/Sniffs/WP/I18nSniff.php | 23 ++++++++++++----------- WordPress/Tests/WP/I18nUnitTest.inc | 4 +++- WordPress/Tests/WP/I18nUnitTest.php | 7 ++++--- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index a2ca839a8e..ab623b14f4 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -8,7 +8,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_WP_I18nSniff implements PHP_CodeSniffer_Sniff { +class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { public $i18n_functions = array( 'translate', @@ -57,23 +57,24 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { return; } - if ( $next_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ) ) { - if ( T_OPEN_PARENTHESIS !== $tokens[ $next_token ]['code'] ) { - return; - } + $next_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); + if ( ! $next_token || T_OPEN_PARENTHESIS !== $tokens[ $next_token ]['code'] ) { + return; } - // Get arguments + // Look at arguments. for ( $i = $next_token + 1; $i < $tokens[ $next_token ]['parenthesis_closer'] - 1; $i += 1 ) { - if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMA, T_CONSTANT_ENCAPSED_STRING ) ) ) { + if ( T_CONSTANT_ENCAPSED_STRING === $tokens[ $i ]['code'] ) { + continue; + } + if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMA ), true ) ) { continue; } if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { - $string = $tokens[ $i ]['content']; - if ( preg_match( '#\$#', $string ) > 0 ) { - $phpcs_file->addError( 'Translatable strings should not contain variables, found ' . $tokens[ $i ]['content'], $i ); - return; + $interpolated_variables = $this->get_interpolated_variables( $tokens[ $i ]['content'] ); + foreach ( $interpolated_variables as $interpolated_variable ) { + $phpcs_file->addError( "Translatable strings cannot contain interpolated variables. Found $interpolated_variable.", $i, 'InterpolatedVariable' ); } continue; } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 05a637f243..9ae22c4d76 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -2,7 +2,9 @@ __( "hell$varo", 'domain' ); // Bad, shouldn't use a string with variables -__( "hell\$varo", 'domain' ); // Bad, shouldn't use a string with variables +__( "hell\$varo", 'domain' ); // OK, Variable is not interpolated. +__( "hell\\$varo", 'domain' ); // Bad, is interpolated. +__( "hell\\\$varo", 'domain' ); // OK, variable is escaped. __( $var, 'domain' ); // Bad, shouldn't use variables diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 4242150a90..73df21cfa7 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -21,7 +21,7 @@ class WordPress_Tests_WP_I18nUnitTest extends AbstractSniffUnitTest { public function getErrorList() { return array( 3 => 1, - 7 => 1, + 6 => 1, 9 => 1, 11 => 1, 13 => 1, @@ -31,13 +31,14 @@ public function getErrorList() { 21 => 1, 23 => 1, 25 => 1, - 31 => 1, + 27 => 1, 33 => 1, 35 => 1, 37 => 1, 39 => 1, 41 => 1, - ); + 43 => 1, + ); } /** From 6f21e41be088ecf11e08e4bd05da56d86f0ac454 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 14 Mar 2016 16:03:00 -0700 Subject: [PATCH 013/122] Add intentionally-failing tests for _n() functions --- WordPress/Tests/WP/I18nUnitTest.inc | 24 ++++++++++++++++++++++++ WordPress/Tests/WP/I18nUnitTest.php | 14 ++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 9ae22c4d76..897715a194 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -41,3 +41,27 @@ _x( 'string', SOMETHING, 'domain' ); // Bad, shouldn't use constant for context _x( 'string', SOMETHING . 'context', 'domain' ); // Bad, shouldn't use constant for context _x( 'string', 'context' . SOMETHING, 'domain' ); // Bad, shouldn't use constant for context + +_n( 'I have a cat.', 'I have cats.', $number ); // OK. +_n( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. +_n( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. +_n( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. + +_n_noop( 'I have a cat.', 'I have cats.', $number ); // OK. +_n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. +_n_noop( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. +_n_noop( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. + +_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // OK. +_nx( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. +_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. +_nx( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. +_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. +_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. + +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // OK. +_nx_noop( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. +_nx_noop( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 73df21cfa7..aab7b73f81 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -38,6 +38,20 @@ public function getErrorList() { 39 => 1, 41 => 1, 43 => 1, + + // Begin _n() checks: + 47 => 1, + 48 => 1, + 52 => 1, + 53 => 1, + 56 => 1, + 58 => 1, + 59 => 1, + 60 => 1, + 63 => 1, + 65 => 1, + 66 => 1, + 67 => 1, ); } From baa4b9ecee613896ee4077b7b62b598a7c57d6f4 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 15 Mar 2016 00:01:18 -0700 Subject: [PATCH 014/122] Implement translation function-specific arg checking --- WordPress/Sniffs/WP/I18nSniff.php | 188 ++++++++++++++++++++++++++-- WordPress/Tests/WP/I18nUnitTest.inc | 10 +- WordPress/Tests/WP/I18nUnitTest.php | 35 +++--- 3 files changed, 200 insertions(+), 33 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index ab623b14f4..627b7836a8 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -53,34 +53,196 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $tokens = $phpcs_file->getTokens(); $token = $tokens[ $stack_ptr ]; - if ( ! in_array( $token['content'], $this->i18n_functions ) ) { + if ( ! in_array( $token['content'], $this->i18n_functions, true ) ) { return; } - $next_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); - if ( ! $next_token || T_OPEN_PARENTHESIS !== $tokens[ $next_token ]['code'] ) { + $translation_function = $token['content']; + + $func_open_paren_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); + if ( ! $func_open_paren_token || T_OPEN_PARENTHESIS !== $tokens[ $func_open_paren_token ]['code'] ) { return; } + $arguments_tokens = array(); + $argument_tokens = array(); + // Look at arguments. - for ( $i = $next_token + 1; $i < $tokens[ $next_token ]['parenthesis_closer'] - 1; $i += 1 ) { - if ( T_CONSTANT_ENCAPSED_STRING === $tokens[ $i ]['code'] ) { + for ( $i = $func_open_paren_token + 1; $i < $tokens[ $func_open_paren_token ]['parenthesis_closer'] - 1; $i += 1 ) { + $this_token = $tokens[ $i ]; + $this_token['token_index'] = $i; + if ( in_array( $this_token['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { continue; } - if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMA ), true ) ) { + if ( T_COMMA === $this_token['code'] ) { + $arguments_tokens[] = $argument_tokens; + $argument_tokens = array(); continue; } + $argument_tokens[] = $this_token; - if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { - $interpolated_variables = $this->get_interpolated_variables( $tokens[ $i ]['content'] ); - foreach ( $interpolated_variables as $interpolated_variable ) { - $phpcs_file->addError( "Translatable strings cannot contain interpolated variables. Found $interpolated_variable.", $i, 'InterpolatedVariable' ); + // Include everything up to and including the parenthesis_closer if this token has one. + if ( ! empty( $this_token['parenthesis_closer'] ) ) { + for ( $j = $i + 1; $j <= $this_token['parenthesis_closer']; $j += 1 ) { + $tokens[ $j ]['token_index'] = $j; + $argument_tokens[] = $tokens[ $j ]; } - continue; + $i = $this_token['parenthesis_closer']; } + } + if ( ! empty( $argument_tokens ) ) { + $arguments_tokens[] = $argument_tokens; + } + unset( $argument_tokens ); - $phpcs_file->addError( sprintf( 'Translatable string expected, but found "%s"', $tokens[ $i ]['content'] ), $i ); - return; + $argument_assertions = array(); + if ( in_array( $translation_function, array( '__', 'esc_attr__', 'esc_html__', '_e', 'esc_attr_e', 'esc_html_e' ) ) ) { + $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + } else if ( in_array( $translation_function, array( '_x', '_ex', 'esc_attr_x', 'esc_html_x' ) ) ) { + $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); + $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + } else if ( in_array( $translation_function, array( '_n', '_n_noop' ) ) ) { + $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$number', 'check_number_tokens' ); + $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + } else if ( in_array( $translation_function, array( '_nx', '_nx_noop' ) ) ) { + $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); + $argument_assertions[] = array( '$number', 'check_number_tokens' ); + $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); + $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + } + + $argument_stack_ptr = $func_open_paren_token; + foreach ( $argument_assertions as $argument_assertion ) { + $argument_tokens = array_shift( $arguments_tokens ); + if ( ! $argument_tokens ) { + $argument_tokens = array(); + } else { + $argument_stack_ptr = $argument_tokens[0]['token_index']; + } + $method_name = $argument_assertion[1]; + $arg_name = $argument_assertion[0]; + call_user_func( array( $this, $method_name ), $phpcs_file, $arg_name, $argument_stack_ptr, $argument_tokens ); + } + } + + /** + * Check if supplied tokens represent a translation text string literal. + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param string $arg_name + * @param int $stack_ptr + * @param array $tokens + * @return bool + */ + protected function check_literal_string_text_tokens( $phpcs_file, $arg_name = '$text', $stack_ptr, $tokens = array() ) { + if ( 0 === count( $tokens ) ) { + $phpcs_file->addError( "Missing translatable text (%s arg).", $stack_ptr, 'MissingText', array( $arg_name ) ); + return false; + } + if ( count( $tokens ) > 1 ) { + $contents = ''; + foreach ( $tokens as $token ) { + $contents .= $token['content']; + } + $phpcs_file->addError( 'Translatable text (%s arg) must be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $contents ) ); + return false; + } + if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { + return true; + } + if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { + $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); + foreach ( $interpolated_variables as $interpolated_variable ) { + $phpcs_file->addError( 'Translatable text (%s arg) must not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableText', array( $arg_name, $interpolated_variable ) ); + } + return false; + } + $phpcs_file->addError( 'Trnslatable text (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $tokens[0]['content'] ) ); + return false; + } + + /** + * The $number argument can be anything, so this is a no-op. + * + * @return bool + */ + protected function check_number_tokens() { + return true; + } + + /** + * Check if supplied tokens are a literal string context. + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param int $stack_ptr + * @param array $tokens + * @return bool + */ + protected function check_literal_string_context_tokens( $phpcs_file, $arg_name = '$context', $stack_ptr, $tokens = array() ) { + if ( 0 === count( $tokens ) ) { + $phpcs_file->addError( "Missing context (%s arg).", $stack_ptr, 'MissingContext', array( $arg_name ) ); + return false; + } + if ( count( $tokens ) > 1 ) { + $contents = ''; + foreach ( $tokens as $token ) { + $contents .= $token['content']; + } + $phpcs_file->addError( 'Context (%s arg) should be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralContext', array( $arg_name, $contents ) ); + return false; + } + if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { + return true; + } + if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { + $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); + foreach ( $interpolated_variables as $interpolated_variable ) { + $phpcs_file->addError( 'Context strings (%s arg) should not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableContext', array( $arg_name, $interpolated_variable ) ); + } + return false; + } + $phpcs_file->addError( 'Context (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralContext', array( $arg_name, $tokens[0]['content'] ) ); + return false; + } + + /** + * Check if supplied tokens are a valid text domain. + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param string $arg_name + * @param int $stack_ptr + * @param array $tokens + * @return bool + */ + protected function check_string_domain_tokens( $phpcs_file, $arg_name = '$domain', $stack_ptr, $tokens = array() ) { + if ( 0 === count( $tokens ) ) { + $phpcs_file->addWarning( "Missing text domain (%s arg).", $stack_ptr, 'MissingTextDomain', array( $arg_name ) ); + return false; + } + if ( count( $tokens ) > 1 ) { + $contents = ''; + foreach ( $tokens as $token ) { + $contents .= $token['content']; + } + $phpcs_file->addWarning( 'Text domain (%s arg) should be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralTextDomain', array( $arg_name, $contents ) ); + return false; + } + if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { + return true; + } + if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { + $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); + foreach ( $interpolated_variables as $interpolated_variable ) { + $phpcs_file->addWarning( 'Text domain strings (%s arg) should not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableTextDomain', array( $arg_name, $interpolated_variable ) ); + } + return false; } + $phpcs_file->addWarning( 'Text domain (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralTextDomain', array( $arg_name, $tokens[0]['content'] ) ); + return false; } } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 897715a194..86f1eed97d 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -42,25 +42,25 @@ _x( 'string', SOMETHING . 'context', 'domain' ); // Bad, shouldn't use constant _x( 'string', 'context' . SOMETHING, 'domain' ); // Bad, shouldn't use constant for context -_n( 'I have a cat.', 'I have cats.', $number ); // OK. +_n( 'I have a cat.', 'I have cats.', $number ); // Bad, no text domain. _n( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. _n( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. _n( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. -_n_noop( 'I have a cat.', 'I have cats.', $number ); // OK. +_n_noop( 'I have a cat.', 'I have cats.', $number ); // Bad, no text domain. _n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. _n_noop( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. _n_noop( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. -_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // OK. +_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // Bad, no text domain. _nx( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. _nx( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // OK. -_nx_noop( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // Bad, no text domain. +_nx_noop( 'I have a cat.', 'I have cats.', $number, $context ); // Bad, no text domain, variable context. _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. _nx_noop( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index aab7b73f81..baf542295c 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -23,35 +23,21 @@ public function getErrorList() { 3 => 1, 6 => 1, 9 => 1, - 11 => 1, 13 => 1, 15 => 1, 17 => 1, 19 => 1, 21 => 1, - 23 => 1, - 25 => 1, - 27 => 1, 33 => 1, 35 => 1, 37 => 1, 39 => 1, 41 => 1, 43 => 1, - - // Begin _n() checks: - 47 => 1, - 48 => 1, - 52 => 1, - 53 => 1, 56 => 1, 58 => 1, - 59 => 1, - 60 => 1, 63 => 1, 65 => 1, - 66 => 1, - 67 => 1, ); } @@ -64,6 +50,25 @@ public function getErrorList() { * @return array(int => int) */ public function getWarningList() { - return array(); + return array( + 11 => 1, + 23 => 1, + 25 => 1, + 27 => 1, + 45 => 1, + 47 => 1, + 48 => 1, + 50 => 1, + 52 => 1, + 53 => 1, + 55 => 1, + 56 => 1, + 59 => 1, + 60 => 1, + 62 => 1, + 63 => 1, + 66 => 1, + 67 => 1, + ); } } From 3f2c69511fb8e4266806fdc2aa34e5281d58b7c1 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 15 Mar 2016 00:09:04 -0700 Subject: [PATCH 015/122] Warn against using translate() and translate_with_gettext_context() --- WordPress/Sniffs/WP/I18nSniff.php | 12 ++++++++++-- WordPress/Tests/WP/I18nUnitTest.inc | 3 +++ WordPress/Tests/WP/I18nUnitTest.php | 2 ++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 627b7836a8..594493aa0d 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -53,10 +53,18 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $tokens = $phpcs_file->getTokens(); $token = $tokens[ $stack_ptr ]; + if ( in_array( $token['content'], array( 'translate', 'translate_with_gettext_context' ), true ) ) { + $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for .', $stack_ptr, 'LowLevelTranslationFunction', array( $token['content'] ) ); + } + if ( ! in_array( $token['content'], $this->i18n_functions, true ) ) { return; } + if ( in_array( $token['content'], array( 'translate', 'translate_with_gettext_context' ), true ) ) { + $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stack_ptr, 'LowLevelTranslationFunction', array( $token['content'] ) ); + } + $translation_function = $token['content']; $func_open_paren_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); @@ -96,10 +104,10 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { unset( $argument_tokens ); $argument_assertions = array(); - if ( in_array( $translation_function, array( '__', 'esc_attr__', 'esc_html__', '_e', 'esc_attr_e', 'esc_html_e' ) ) ) { + if ( in_array( $translation_function, array( '__', 'esc_attr__', 'esc_html__', '_e', 'esc_attr_e', 'esc_html_e', 'translate' ) ) ) { $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); - } else if ( in_array( $translation_function, array( '_x', '_ex', 'esc_attr_x', 'esc_html_x' ) ) ) { + } else if ( in_array( $translation_function, array( '_x', '_ex', 'esc_attr_x', 'esc_html_x', 'translate_with_gettext_context' ) ) ) { $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 86f1eed97d..0c88621fdd 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -65,3 +65,6 @@ _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); _nx_noop( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. + +translate( 'foo', 'bar' ); // Bad, low-level API function. +translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index baf542295c..4508ea054f 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -69,6 +69,8 @@ public function getWarningList() { 63 => 1, 66 => 1, 67 => 1, + 69 => 1, + 70 => 1, ); } } From eada3e7c6e735573a1d589742957344aa01369d0 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 15 Mar 2016 00:13:40 -0700 Subject: [PATCH 016/122] Forbid using single-underscore _() --- WordPress/Sniffs/WP/I18nSniff.php | 4 ++-- WordPress/Tests/WP/I18nUnitTest.inc | 2 ++ WordPress/Tests/WP/I18nUnitTest.php | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 594493aa0d..93ddc2cc58 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -53,8 +53,8 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $tokens = $phpcs_file->getTokens(); $token = $tokens[ $stack_ptr ]; - if ( in_array( $token['content'], array( 'translate', 'translate_with_gettext_context' ), true ) ) { - $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for .', $stack_ptr, 'LowLevelTranslationFunction', array( $token['content'] ) ); + if ( '_' === $token['content'] ) { + $phpcs_file->addError( 'Found single-underscore "_()" function when double-underscore expected.', $stack_ptr, 'SingleUnderscoreGetTextFunction' ); } if ( ! in_array( $token['content'], $this->i18n_functions, true ) ) { diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 0c88621fdd..da18bd5063 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -68,3 +68,5 @@ _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); translate( 'foo', 'bar' ); // Bad, low-level API function. translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. + +_( 'foo', 'bar' ); diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 4508ea054f..85b6a7418c 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -38,6 +38,7 @@ public function getErrorList() { 58 => 1, 63 => 1, 65 => 1, + 72 => 1, ); } From f2312fa7ac467fa70596ade6a812f334f63a559e Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 15 Mar 2016 00:25:39 -0700 Subject: [PATCH 017/122] Fix some coding style and spelling [ci skip] --- WordPress/Sniffs/WP/I18nSniff.php | 8 ++++---- WordPress/Tests/WP/I18nUnitTest.inc | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 93ddc2cc58..f98a47b09b 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -149,7 +149,7 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { */ protected function check_literal_string_text_tokens( $phpcs_file, $arg_name = '$text', $stack_ptr, $tokens = array() ) { if ( 0 === count( $tokens ) ) { - $phpcs_file->addError( "Missing translatable text (%s arg).", $stack_ptr, 'MissingText', array( $arg_name ) ); + $phpcs_file->addError( 'Missing translatable text (%s arg).', $stack_ptr, 'MissingText', array( $arg_name ) ); return false; } if ( count( $tokens ) > 1 ) { @@ -170,7 +170,7 @@ protected function check_literal_string_text_tokens( $phpcs_file, $arg_name = '$ } return false; } - $phpcs_file->addError( 'Trnslatable text (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $tokens[0]['content'] ) ); + $phpcs_file->addError( 'Translatable text (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $tokens[0]['content'] ) ); return false; } @@ -193,7 +193,7 @@ protected function check_number_tokens() { */ protected function check_literal_string_context_tokens( $phpcs_file, $arg_name = '$context', $stack_ptr, $tokens = array() ) { if ( 0 === count( $tokens ) ) { - $phpcs_file->addError( "Missing context (%s arg).", $stack_ptr, 'MissingContext', array( $arg_name ) ); + $phpcs_file->addError( 'Missing context (%s arg).', $stack_ptr, 'MissingContext', array( $arg_name ) ); return false; } if ( count( $tokens ) > 1 ) { @@ -229,7 +229,7 @@ protected function check_literal_string_context_tokens( $phpcs_file, $arg_name = */ protected function check_string_domain_tokens( $phpcs_file, $arg_name = '$domain', $stack_ptr, $tokens = array() ) { if ( 0 === count( $tokens ) ) { - $phpcs_file->addWarning( "Missing text domain (%s arg).", $stack_ptr, 'MissingTextDomain', array( $arg_name ) ); + $phpcs_file->addWarning( 'Missing text domain (%s arg).', $stack_ptr, 'MissingTextDomain', array( $arg_name ) ); return false; } if ( count( $tokens ) > 1 ) { diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index da18bd5063..1861725eaa 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -69,4 +69,4 @@ _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); translate( 'foo', 'bar' ); // Bad, low-level API function. translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. -_( 'foo', 'bar' ); +_( 'foo', 'bar' ); // Bad. From 9ebd183257aaa859c9c06b558edfdab878a136eb Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 18 Mar 2016 12:37:16 -0700 Subject: [PATCH 018/122] Let i18n function types be defined in array --- WordPress/Sniffs/WP/I18nSniff.php | 49 +++++++++++++++---------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index f98a47b09b..3902547c81 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -11,22 +11,22 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { public $i18n_functions = array( - 'translate', - 'translate_with_gettext_context', - '__', - 'esc_attr__', - 'esc_html__', - '_e', - 'esc_attr_e', - 'esc_html_e', - '_x', - '_ex', - 'esc_attr_x', - 'esc_html_x', - '_n', - '_nx', - '_n_noop', - '_nx_noop', + 'translate' => 'simple', + '__' => 'simple', + 'esc_attr__' => 'simple', + 'esc_html__' => 'simple', + '_e' => 'simple', + 'esc_attr_e' => 'simple', + 'esc_html_e' => 'simple', + 'translate_with_gettext_context' => 'context', + '_x' => 'context', + '_ex' => 'context', + 'esc_attr_x' => 'context', + 'esc_html_x' => 'context', + '_n' => 'number', + '_nx' => 'number_context', + '_n_noop' => 'number', + '_nx_noop' => 'number_context', ); /** @@ -57,16 +57,15 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $phpcs_file->addError( 'Found single-underscore "_()" function when double-underscore expected.', $stack_ptr, 'SingleUnderscoreGetTextFunction' ); } - if ( ! in_array( $token['content'], $this->i18n_functions, true ) ) { + if ( ! isset( $this->i18n_functions[ $token['content'] ] ) ) { return; } + $translation_function = $token['content']; - if ( in_array( $token['content'], array( 'translate', 'translate_with_gettext_context' ), true ) ) { - $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stack_ptr, 'LowLevelTranslationFunction', array( $token['content'] ) ); + if ( in_array( $translation_function, array( 'translate', 'translate_with_gettext_context' ), true ) ) { + $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stack_ptr, 'LowLevelTranslationFunction', array( $translation_function ) ); } - $translation_function = $token['content']; - $func_open_paren_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); if ( ! $func_open_paren_token || T_OPEN_PARENTHESIS !== $tokens[ $func_open_paren_token ]['code'] ) { return; @@ -104,19 +103,19 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { unset( $argument_tokens ); $argument_assertions = array(); - if ( in_array( $translation_function, array( '__', 'esc_attr__', 'esc_html__', '_e', 'esc_attr_e', 'esc_html_e', 'translate' ) ) ) { + if ( 'simple' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); - } else if ( in_array( $translation_function, array( '_x', '_ex', 'esc_attr_x', 'esc_html_x', 'translate_with_gettext_context' ) ) ) { + } else if ( 'context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); - } else if ( in_array( $translation_function, array( '_n', '_n_noop' ) ) ) { + } else if ( 'number' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$number', 'check_number_tokens' ); $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); - } else if ( in_array( $translation_function, array( '_nx', '_nx_noop' ) ) ) { + } else if ( 'number_context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); $argument_assertions[] = array( '$number', 'check_number_tokens' ); From 375bb1fd29e9f4096866504d002ed75b3f0b7d93 Mon Sep 17 00:00:00 2001 From: Dominik Schilling Date: Sun, 20 Mar 2016 17:10:33 +0100 Subject: [PATCH 019/122] Include PSR2.ControlStructures.ElseIfDeclaration in WordPress-Core --- WordPress-Core/ruleset.xml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 9570c06bf0..4d7a6e696f 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -9,6 +9,9 @@ 0 + + + @@ -38,7 +41,7 @@ 0 - + From a47029e7af7902174f1b77ce3e27339bc5522bb4 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 22 Mar 2016 17:38:50 -0700 Subject: [PATCH 020/122] Refactor methods to reduce duplication; add too-many-args check --- WordPress/Sniffs/WP/I18nSniff.php | 147 +++++++--------------------- WordPress/Tests/WP/I18nUnitTest.inc | 6 ++ WordPress/Tests/WP/I18nUnitTest.php | 5 + 3 files changed, 48 insertions(+), 110 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 3902547c81..e7a7baa771 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -104,131 +104,55 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $argument_assertions = array(); if ( 'simple' === $this->i18n_functions[ $translation_function ] ) { - $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); } else if ( 'context' === $this->i18n_functions[ $translation_function ] ) { - $argument_assertions[] = array( '$text', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); - $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); } else if ( 'number' === $this->i18n_functions[ $translation_function ] ) { - $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$number', 'check_number_tokens' ); - $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); + array_shift( $arguments_tokens ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); } else if ( 'number_context' === $this->i18n_functions[ $translation_function ] ) { - $argument_assertions[] = array( '$single', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$plural', 'check_literal_string_text_tokens' ); - $argument_assertions[] = array( '$number', 'check_number_tokens' ); - $argument_assertions[] = array( '$context', 'check_literal_string_context_tokens' ); - $argument_assertions[] = array( '$domain', 'check_string_domain_tokens' ); + $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); + array_shift( $arguments_tokens ); + $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); } - $argument_stack_ptr = $func_open_paren_token; - foreach ( $argument_assertions as $argument_assertion ) { - $argument_tokens = array_shift( $arguments_tokens ); - if ( ! $argument_tokens ) { - $argument_tokens = array(); - } else { - $argument_stack_ptr = $argument_tokens[0]['token_index']; - } - $method_name = $argument_assertion[1]; - $arg_name = $argument_assertion[0]; - call_user_func( array( $this, $method_name ), $phpcs_file, $arg_name, $argument_stack_ptr, $argument_tokens ); + if ( ! empty( $arguments_tokens ) ) { + $phpcs_file->addError( 'Too many arguments for function "%s".', $func_open_paren_token, 'TooManyFunctionArgs', array( $translation_function ) ); } - } - /** - * Check if supplied tokens represent a translation text string literal. - * - * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param string $arg_name - * @param int $stack_ptr - * @param array $tokens - * @return bool - */ - protected function check_literal_string_text_tokens( $phpcs_file, $arg_name = '$text', $stack_ptr, $tokens = array() ) { - if ( 0 === count( $tokens ) ) { - $phpcs_file->addError( 'Missing translatable text (%s arg).', $stack_ptr, 'MissingText', array( $arg_name ) ); - return false; - } - if ( count( $tokens ) > 1 ) { - $contents = ''; - foreach ( $tokens as $token ) { - $contents .= $token['content']; - } - $phpcs_file->addError( 'Translatable text (%s arg) must be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $contents ) ); - return false; - } - if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { - return true; - } - if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { - $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); - foreach ( $interpolated_variables as $interpolated_variable ) { - $phpcs_file->addError( 'Translatable text (%s arg) must not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableText', array( $arg_name, $interpolated_variable ) ); + foreach ( $argument_assertions as $argument_assertion_context ) { + if ( empty( $argument_assertion_context['tokens'][0] ) ) { + $argument_assertion_context['stack_ptr'] = $func_open_paren_token; + } else { + $argument_assertion_context['stack_ptr'] = $argument_assertion_context['tokens'][0]['token_index']; } - return false; + call_user_func( array( $this, 'check_argument_tokens' ), $phpcs_file, $argument_assertion_context ); } - $phpcs_file->addError( 'Translatable text (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralText', array( $arg_name, $tokens[0]['content'] ) ); - return false; - } - - /** - * The $number argument can be anything, so this is a no-op. - * - * @return bool - */ - protected function check_number_tokens() { - return true; } /** - * Check if supplied tokens are a literal string context. + * Check if supplied tokens represent a translation text string literal. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param int $stack_ptr - * @param array $tokens + * @param array $context * @return bool */ - protected function check_literal_string_context_tokens( $phpcs_file, $arg_name = '$context', $stack_ptr, $tokens = array() ) { - if ( 0 === count( $tokens ) ) { - $phpcs_file->addError( 'Missing context (%s arg).', $stack_ptr, 'MissingContext', array( $arg_name ) ); - return false; - } - if ( count( $tokens ) > 1 ) { - $contents = ''; - foreach ( $tokens as $token ) { - $contents .= $token['content']; - } - $phpcs_file->addError( 'Context (%s arg) should be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralContext', array( $arg_name, $contents ) ); - return false; - } - if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { - return true; - } - if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { - $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); - foreach ( $interpolated_variables as $interpolated_variable ) { - $phpcs_file->addError( 'Context strings (%s arg) should not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableContext', array( $arg_name, $interpolated_variable ) ); - } - return false; - } - $phpcs_file->addError( 'Context (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralContext', array( $arg_name, $tokens[0]['content'] ) ); - return false; - } + protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $context ) { + $stack_ptr = $context['stack_ptr']; + $tokens = $context['tokens']; + $arg_name = $context['arg_name']; + $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; - /** - * Check if supplied tokens are a valid text domain. - * - * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param string $arg_name - * @param int $stack_ptr - * @param array $tokens - * @return bool - */ - protected function check_string_domain_tokens( $phpcs_file, $arg_name = '$domain', $stack_ptr, $tokens = array() ) { if ( 0 === count( $tokens ) ) { - $phpcs_file->addWarning( 'Missing text domain (%s arg).', $stack_ptr, 'MissingTextDomain', array( $arg_name ) ); + $code = 'MissingArg' . ucfirst( $arg_name ); + $phpcs_file->$method( 'Missing $%s arg.', $stack_ptr, $code, array( $arg_name ) ); return false; } if ( count( $tokens ) > 1 ) { @@ -236,7 +160,8 @@ protected function check_string_domain_tokens( $phpcs_file, $arg_name = '$domain foreach ( $tokens as $token ) { $contents .= $token['content']; } - $phpcs_file->addWarning( 'Text domain (%s arg) should be a single string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralTextDomain', array( $arg_name, $contents ) ); + $code = 'NonSingularStringLiteral' . ucfirst( $arg_name ); + $phpcs_file->$method( 'The $%s arg must be a single string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $contents ) ); return false; } if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { @@ -245,11 +170,13 @@ protected function check_string_domain_tokens( $phpcs_file, $arg_name = '$domain if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); foreach ( $interpolated_variables as $interpolated_variable ) { - $phpcs_file->addWarning( 'Text domain strings (%s arg) should not contain interpolated variables. Found "$%s".', $stack_ptr, 'InterpolatedVariableTextDomain', array( $arg_name, $interpolated_variable ) ); + $code = 'InterpolatedVariable' . ucfirst( $arg_name ); + $phpcs_file->$method( 'The $%s arg must not contain interpolated variables. Found "$%s".', $stack_ptr, $code, array( $arg_name, $interpolated_variable ) ); } return false; } - $phpcs_file->addWarning( 'Text domain (%s arg) should be single a string literal, not "%s".', $stack_ptr, 'NonSingularStringLiteralTextDomain', array( $arg_name, $tokens[0]['content'] ) ); + $code = 'NonSingularStringLiteral' . ucfirst( $arg_name ); + $phpcs_file->$method( 'The $%s arg should be single a string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $tokens[0]['content'] ) ); return false; } } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 1861725eaa..d4c4b2b45e 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -70,3 +70,9 @@ translate( 'foo', 'bar' ); // Bad, low-level API function. translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. _( 'foo', 'bar' ); // Bad. + +__( 'foo', 'bar', 'too-many-args' ); // Bad. +_x( 'string', 'context', 'domain', 'too-many-args' ); // Bad +_n( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad +_n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug', 'too-many-args' ); // Bad. diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 85b6a7418c..6e0f6b27d8 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -39,6 +39,11 @@ public function getErrorList() { 63 => 1, 65 => 1, 72 => 1, + 74 => 1, + 75 => 1, + 76 => 1, + 77 => 1, + 78 => 1, ); } From c459f670720b7906f0345fd0f65d3de3d42e8de1 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Thu, 24 Mar 2016 16:13:38 -0700 Subject: [PATCH 021/122] Merge multi-line string literal tokens into single token Fixes #50. --- WordPress/Sniffs/WP/I18nSniff.php | 19 ++++++++++++++++--- WordPress/Tests/WP/I18nUnitTest.inc | 7 +++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index e7a7baa771..bc311b9b47 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -86,6 +86,18 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $argument_tokens = array(); continue; } + + // Merge consecutive single or double quoted strings (when they span multiple lines). + if ( T_CONSTANT_ENCAPSED_STRING === $this_token['code'] || T_DOUBLE_QUOTED_STRING === $this_token['code'] ) { + for ( $j = $i + 1; $j < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $j += 1 ) { + if ( $this_token['code'] === $tokens[ $j ]['code'] ) { + $this_token['content'] .= $tokens[ $j ]['content']; + $i = $j; + } else { + break; + } + } + } $argument_tokens[] = $this_token; // Include everything up to and including the parenthesis_closer if this token has one. @@ -106,16 +118,16 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { if ( 'simple' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); - } else if ( 'context' === $this->i18n_functions[ $translation_function ] ) { + } elseif ( 'context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); - } else if ( 'number' === $this->i18n_functions[ $translation_function ] ) { + } elseif ( 'number' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); array_shift( $arguments_tokens ); $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); - } else if ( 'number_context' === $this->i18n_functions[ $translation_function ] ) { + } elseif ( 'number_context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); array_shift( $arguments_tokens ); @@ -175,6 +187,7 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con } return false; } + $code = 'NonSingularStringLiteral' . ucfirst( $arg_name ); $phpcs_file->$method( 'The $%s arg should be single a string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $tokens[0]['content'] ) ); return false; diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index d4c4b2b45e..d7d340504f 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -76,3 +76,10 @@ _x( 'string', 'context', 'domain', 'too-many-args' ); // Bad _n( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad _n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad. _nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug', 'too-many-args' ); // Bad. + +// Make sure that multi-line string literals are accepted. +_nx( 'I have +a cat.', 'I have +cats.', $number, 'Not +really.', 'my- +slug' ); // OK. From 684bb8d4544b3839c20a75460b69f580ae7558be Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:20:04 -0700 Subject: [PATCH 022/122] Honor whitelisted_mixed_case_member_var_names for variables (NotSnakeCase error) --- .../Sniffs/NamingConventions/ValidVariableNameSniff.php | 2 +- .../Tests/NamingConventions/ValidVariableNameUnitTest.inc | 8 ++++---- .../Tests/NamingConventions/ValidVariableNameUnitTest.php | 4 ---- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 355d2877d7..a0a528f2a5 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -132,7 +132,7 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr } } - if ( self::isSnakeCase( $var_name ) === false ) { + if ( self::isSnakeCase( $var_name ) === false && ! in_array( $var_name, $this->whitelisted_mixed_case_member_var_names, true ) ) { $error = 'Variable "%s" is not in valid snake_case format'; $data = array( $original_var_name ); $phpcs_file->addError( $error, $stack_ptr, 'NotSnakeCase', $data ); diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index 61234a9334..a94fc7de8d 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -77,13 +77,13 @@ $myXML = 'hello'; // Bad $XMLParser = 'hello'; // Bad $xmlParser = 'hello'; // Bad -$ID = 1; // Bad +$ID = 1; $post = get_post( $x ); echo $post->ID; -echo $comment_ID; // Bad -echo $comment_post_ID; // Bad -echo $comment_author_IP; // Bad +echo $comment_ID; +echo $comment_post_ID; +echo $comment_author_IP; $comment = get_comment( 1 ); echo $comment->comment_ID; diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index ed46bf07d6..aa395745e2 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -69,10 +69,6 @@ public function getErrorList() { 76 => 1, 77 => 1, 78 => 1, - 80 => 1, - 84 => 1, - 85 => 1, - 86 => 1, ); return $errors; From bd5109c4b2a0e37e5abea742e4559ef375fb835d Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:21:48 -0700 Subject: [PATCH 023/122] Include cat_ID among whitelisted var names for ValidVariableName --- .../Sniffs/NamingConventions/ValidVariableNameSniff.php | 1 + .../Tests/NamingConventions/ValidVariableNameUnitTest.inc | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index a0a528f2a5..f2f1c6ffd4 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -67,6 +67,7 @@ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_Code 'comment_post_ID', 'post_ID', 'comment_author_IP', + 'cat_ID', ); /** diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index a94fc7de8d..38a2d1e3fa 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -94,3 +94,8 @@ class Foo { public $_public_leading_underscore; private $private_no_underscore_loading; } + +if ( is_category() ) { + $category = get_queried_object(); + $cat_ID = $category->cat_ID; +} From cbf73912072474f4861ade893bd1c129b6129e1b Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:29:22 -0700 Subject: [PATCH 024/122] Ignore Squiz.Commenting.FunctionComment.ScalarTypeHintMissing --- WordPress-Core/ruleset.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 4d7a6e696f..c882a5ab9a 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -102,4 +102,7 @@ + + 0 + From 4753fb14d446348fd7444707885eac3264ca8c5f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:31:08 -0700 Subject: [PATCH 025/122] Revert "Honor whitelisted_mixed_case_member_var_names for variables (NotSnakeCase error)" This reverts commit 684bb8d4544b3839c20a75460b69f580ae7558be. --- .../Sniffs/NamingConventions/ValidVariableNameSniff.php | 2 +- .../Tests/NamingConventions/ValidVariableNameUnitTest.inc | 8 ++++---- .../Tests/NamingConventions/ValidVariableNameUnitTest.php | 4 ++++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index f2f1c6ffd4..2f613eb5e8 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -133,7 +133,7 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr } } - if ( self::isSnakeCase( $var_name ) === false && ! in_array( $var_name, $this->whitelisted_mixed_case_member_var_names, true ) ) { + if ( self::isSnakeCase( $var_name ) === false ) { $error = 'Variable "%s" is not in valid snake_case format'; $data = array( $original_var_name ); $phpcs_file->addError( $error, $stack_ptr, 'NotSnakeCase', $data ); diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index 38a2d1e3fa..0fae06d039 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -77,13 +77,13 @@ $myXML = 'hello'; // Bad $XMLParser = 'hello'; // Bad $xmlParser = 'hello'; // Bad -$ID = 1; +$ID = 1; // Bad $post = get_post( $x ); echo $post->ID; -echo $comment_ID; -echo $comment_post_ID; -echo $comment_author_IP; +echo $comment_ID; // Bad +echo $comment_post_ID; // Bad +echo $comment_author_IP; // Bad $comment = get_comment( 1 ); echo $comment->comment_ID; diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index aa395745e2..ed46bf07d6 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -69,6 +69,10 @@ public function getErrorList() { 76 => 1, 77 => 1, 78 => 1, + 80 => 1, + 84 => 1, + 85 => 1, + 86 => 1, ); return $errors; From d8d7942da1516c78e76eddee43ad44c0b48210a5 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:35:10 -0700 Subject: [PATCH 026/122] Improve error message for NotSnakeCaseMemberVar to indicate object property --- WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 2f613eb5e8..870a2dbed4 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -106,7 +106,7 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr } if ( ! in_array( $obj_var_name, $this->whitelisted_mixed_case_member_var_names, true ) && self::isSnakeCase( $obj_var_name ) === false ) { - $error = 'Variable "%s" is not in valid snake_case format'; + $error = 'Object property "%s" is not in valid snake_case format'; $data = array( $original_var_name ); $phpcs_file->addError( $error, $var, 'NotSnakeCaseMemberVar', $data ); } From 623040ef0b2d17d34d3f7567ad6298ff1e8ec913 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 12:35:39 -0700 Subject: [PATCH 027/122] Add test case to show variable use of cat_ID is bad, but object var ok --- .../Tests/NamingConventions/ValidVariableNameUnitTest.inc | 3 ++- .../Tests/NamingConventions/ValidVariableNameUnitTest.php | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index 0fae06d039..0a165bf079 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -97,5 +97,6 @@ class Foo { if ( is_category() ) { $category = get_queried_object(); - $cat_ID = $category->cat_ID; + $cat_id = $category->cat_ID; + $cat_ID = $category->cat_ID; // Bad. } diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index ed46bf07d6..49f1cc8478 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -73,6 +73,7 @@ public function getErrorList() { 84 => 1, 85 => 1, 86 => 1, + 101 => 1, ); return $errors; From c1af3a9e8d61eb014bfa702496afac1e98a092db Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 1 Apr 2016 13:14:04 -0700 Subject: [PATCH 028/122] Move ScalarTypeHintMissing exclude from WordPress-Core to WordPress-Docs --- WordPress-Core/ruleset.xml | 3 --- WordPress-Docs/ruleset.xml | 3 +++ 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index c882a5ab9a..4d7a6e696f 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -102,7 +102,4 @@ - - 0 - diff --git a/WordPress-Docs/ruleset.xml b/WordPress-Docs/ruleset.xml index 1a07a36fa6..96a68eac13 100644 --- a/WordPress-Docs/ruleset.xml +++ b/WordPress-Docs/ruleset.xml @@ -74,6 +74,9 @@ + + + From 139155ba81c576c74be806ef726cd20c3f64e88e Mon Sep 17 00:00:00 2001 From: Stephen Edgar Date: Thu, 7 Apr 2016 22:15:26 +1000 Subject: [PATCH 029/122] Fix type docs description in /Tests/WhiteSpace/CastStructureSpacingUnitTest.php --- WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php index 0c3d35d3e8..64c470a249 100644 --- a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php @@ -1,6 +1,6 @@ Date: Fri, 8 Apr 2016 09:02:00 -0700 Subject: [PATCH 030/122] Fix checks for _nx_noop and _n_noop which lack number args --- WordPress/Sniffs/WP/I18nSniff.php | 13 +++++++++++-- WordPress/Tests/WP/I18nUnitTest.inc | 24 ++++++++++++------------ 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index bc311b9b47..aa31c16ea3 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -25,8 +25,8 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { 'esc_html_x' => 'context', '_n' => 'number', '_nx' => 'number_context', - '_n_noop' => 'number', - '_nx_noop' => 'number_context', + '_n_noop' => 'noopnumber', + '_nx_noop' => 'noopnumber_context', ); /** @@ -133,6 +133,15 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { array_shift( $arguments_tokens ); $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + } elseif ( 'noopnumber' === $this->i18n_functions[ $translation_function ] ) { + $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + } elseif ( 'noopnumber_context' === $this->i18n_functions[ $translation_function ] ) { + $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); } if ( ! empty( $arguments_tokens ) ) { diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index d7d340504f..1c16d381b9 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -47,10 +47,10 @@ _n( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. _n( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. _n( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. -_n_noop( 'I have a cat.', 'I have cats.', $number ); // Bad, no text domain. -_n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. -_n_noop( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. -_n_noop( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. +_n_noop( 'I have a cat.', 'I have cats.' ); // Bad, no text domain. +_n_noop( 'I have a cat.', 'I have cats.', 'my-slug' ); // OK. +_n_noop( 'I have a cat.', 'I have cats.', "illegal $string" ); // Bad. +_n_noop( 'I have a cat.', 'I have cats.', SOMETHING ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // Bad, no text domain. _nx( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. @@ -59,12 +59,12 @@ _nx( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. _nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // Bad, no text domain. -_nx_noop( 'I have a cat.', 'I have cats.', $number, $context ); // Bad, no text domain, variable context. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. -_nx_noop( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.' ); // Bad, no text domain. +_nx_noop( 'I have a cat.', 'I have cats.', $context ); // Bad, no text domain, variable context. +_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', 'my-slug' ); // OK. +_nx_noop( 'I have a cat.', 'I have cats.', $context, 'my-slug' ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', "illegal $string" ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', SOMETHING ); // Bad. translate( 'foo', 'bar' ); // Bad, low-level API function. translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. @@ -74,8 +74,8 @@ _( 'foo', 'bar' ); // Bad. __( 'foo', 'bar', 'too-many-args' ); // Bad. _x( 'string', 'context', 'domain', 'too-many-args' ); // Bad _n( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad -_n_noop( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug', 'too-many-args' ); // Bad. +_n_noop( 'I have a cat.', 'I have cats.', 'my-slug', 'too-many-args' ); // Bad. +_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', 'my-slug', 'too-many-args' ); // Bad. // Make sure that multi-line string literals are accepted. _nx( 'I have From 8dfa23e76c5df5334f06f72a7f87345ff892ca50 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Fri, 8 Apr 2016 09:06:32 -0700 Subject: [PATCH 031/122] Fix error where arguments_tokens would miss last token --- WordPress/Sniffs/WP/I18nSniff.php | 2 +- WordPress/Tests/WP/I18nUnitTest.inc | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index aa31c16ea3..a282fd5119 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -75,7 +75,7 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $argument_tokens = array(); // Look at arguments. - for ( $i = $func_open_paren_token + 1; $i < $tokens[ $func_open_paren_token ]['parenthesis_closer'] - 1; $i += 1 ) { + for ( $i = $func_open_paren_token + 1; $i < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $i += 1 ) { $this_token = $tokens[ $i ]; $this_token['token_index'] = $i; if ( in_array( $this_token['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 1c16d381b9..ec7cde6158 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -83,3 +83,6 @@ a cat.', 'I have cats.', $number, 'Not really.', 'my- slug' ); // OK. + +// Ensure lack of spaces doesn't cause i18n error. +_n_noop('I have a cat.', 'I have cats.', 'my-slug'); // OK. From d8ecf5f86a03f5c59addf7aec2f627c31c5f8c8d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 11 Apr 2016 02:05:10 +0200 Subject: [PATCH 032/122] [VariableName Sniff] Add ability to add to the whitelisted variables list. Usage example: ```xml ``` --- .../ValidVariableNameSniff.php | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 870a2dbed4..bec059071d 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -70,6 +70,24 @@ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_Code 'cat_ID', ); + /** + * Custom list of variables which can have mixed case. + * + * @since 0.10.0 + * + * @var string[] + */ + public $customVariablesWhitelist = array(); + + /** + * Whether the custom whitelisted variables were added to the default list yet. + * + * @since 0.10.0 + * + * @var bool + */ + public static $addedCustomVariables = false; + /** * Processes this test, when one of its tokens is encountered. * @@ -80,6 +98,14 @@ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_Code * @return void */ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { + + // Merge any custom variables with the defaults, if we haven't already. + if ( ! self::$addedCustomVariables ) { + $this->whitelisted_mixed_case_member_var_names = array_merge( $this->whitelisted_mixed_case_member_var_names, $this->customVariablesWhitelist ); + + self::$addedCustomVariables = true; + } + $tokens = $phpcs_file->getTokens(); $var_name = ltrim( $tokens[ $stack_ptr ]['content'], '$' ); From 79b2170cd02a2e21acf6f0c647c5049c589e4d80 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 11 Apr 2016 02:53:18 +0200 Subject: [PATCH 033/122] [VariableName Sniff] Improve error message differentiation in the sniff. Ensures that static class properties get the `Object property... ` version of the error message rather than the `Variable ... ` version. Includes additional unit tests to verify that the differentiation works properly. Also: - Slightly simplifies the `in_class` check - Fixes one `// Bad` on the wrong line issue in the unit test file - Fixes one inconsistent error message (missing "valid" in the sentence). Closes #555 --- .../ValidVariableNameSniff.php | 40 +++++++++++-------- .../ValidVariableNameUnitTest.inc | 24 ++++++++++- .../ValidVariableNameUnitTest.php | 25 ++++++++---- 3 files changed, 62 insertions(+), 27 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 870a2dbed4..809651cab3 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -114,29 +114,35 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr }//end if }//end if + $in_class = false; + $obj_operator = $phpcs_file->findPrevious( array( T_WHITESPACE ), ( $stack_ptr - 1 ), null, true ); + if ( T_DOUBLE_COLON === $tokens[ $obj_operator ]['code'] || T_OBJECT_OPERATOR === $tokens[ $obj_operator ]['code'] ) { + // The variable lives within a class, and is referenced like + // this: MyClass::$_variable or $class->variable. + $in_class = true; + } + // There is no way for us to know if the var is public or private, // so we have to ignore a leading underscore if there is one and just // check the main part of the variable name. $original_var_name = $var_name; - if ( substr( $var_name, 0, 1 ) === '_' ) { - $obj_operator = $phpcs_file->findPrevious( array( T_WHITESPACE ), ( $stack_ptr - 1 ), null, true ); - if ( T_DOUBLE_COLON === $tokens[ $obj_operator ]['code'] ) { - // The variable lives within a class, and is referenced like - // this: MyClass::$_variable, so we don't know its scope. - $in_class = true; - } else { - $in_class = $phpcs_file->hasCondition( $stack_ptr, array( T_CLASS, T_INTERFACE, T_TRAIT ) ); - } - - if ( true === $in_class ) { - $var_name = substr( $var_name, 1 ); - } + if ( substr( $var_name, 0, 1 ) === '_' && true === $in_class ) { + $var_name = substr( $var_name, 1 ); } if ( self::isSnakeCase( $var_name ) === false ) { - $error = 'Variable "%s" is not in valid snake_case format'; - $data = array( $original_var_name ); - $phpcs_file->addError( $error, $stack_ptr, 'NotSnakeCase', $data ); + if ( $in_class && ! in_array( $var_name, $this->whitelisted_mixed_case_member_var_names, true ) ) { + $error = 'Object property "%s" is not in valid snake_case format'; + $error_name = 'NotSnakeCaseMemberVar'; + } elseif ( ! $in_class ) { + $error = 'Variable "%s" is not in valid snake_case format'; + $error_name = 'NotSnakeCase'; + } + + if ( isset( $error, $error_name ) ) { + $data = array( $original_var_name ); + $phpcs_file->addError( $error, $stack_ptr, $error_name, $data ); + } } } @@ -193,7 +199,7 @@ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $s } if ( self::isSnakeCase( $var_name ) === false ) { - $error = 'Variable "%s" is not in snake_case format'; + $error = 'Variable "%s" is not in valid snake_case format'; $data = array( $var_name ); $phpcs_file->addError( $error, $stack_ptr, 'StringNotSnakeCase', $data ); } diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index 0a165bf079..3dc603c39c 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -1,6 +1,6 @@ varName2; // Bad echo $this->var_name2; @@ -61,6 +62,7 @@ echo $object->varName2; // Bad echo $object->var_name2; echo $object_name->varname2; echo $object_name->_varName2; // Bad +echo $object_name->VAR_name; // Bad echo $this->myFunction($one, $two); echo $object->myFunction($one_two); @@ -93,6 +95,24 @@ echo $comment->comment_author_IP; class Foo { public $_public_leading_underscore; private $private_no_underscore_loading; + + function Bar( $VARname ) { // Bad + $localVariable = false; // Bad + echo Some_Class::$VarName; // Bad + echo $this->VAR_name; // Bad + $_localVariable = false; // Bad + echo Some_Class::$_VarName; // Bad + echo $this->_VAR_name; // Bad + } + + function Baz( $var_name ) { // Ok + $local_variable = false; // Ok + echo Some_Class::$var_name; // Ok + echo $this->var_name; // Ok + $_local_variable = false; // Ok + echo Some_Class::$_var_name; // Ok + echo $this->_var_name; // Ok + } } if ( is_category() ) { diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index 49f1cc8478..8429922e21 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -60,20 +60,29 @@ public function getErrorList() { 43 => 1, 51 => 1, 54 => 1, - 56 => 1, - 59 => 1, + 55 => 1, + 57 => 1, 60 => 1, - 63 => 1, - 68 => 1, - 75 => 1, - 76 => 1, + 61 => 1, + 64 => 1, + 65 => 1, + 70 => 1, 77 => 1, 78 => 1, + 79 => 1, 80 => 1, - 84 => 1, - 85 => 1, + 82 => 1, 86 => 1, + 87 => 1, + 88 => 1, + 99 => 1, + 100 => 1, 101 => 1, + 102 => 1, + 103 => 1, + 104 => 1, + 105 => 1, + 121 => 1, ); return $errors; From c4dc927a9ba409de3b33bfc27fea11b9e108348c Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Wed, 20 Apr 2016 11:58:47 -0700 Subject: [PATCH 034/122] Add placeholders to numeric i18n functions to align with usage --- WordPress/Tests/WP/I18nUnitTest.inc | 61 +++++++++++++++-------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index ec7cde6158..422fe2da51 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -42,29 +42,29 @@ _x( 'string', SOMETHING . 'context', 'domain' ); // Bad, shouldn't use constant _x( 'string', 'context' . SOMETHING, 'domain' ); // Bad, shouldn't use constant for context -_n( 'I have a cat.', 'I have cats.', $number ); // Bad, no text domain. -_n( 'I have a cat.', 'I have cats.', $number, 'my-slug' ); // OK. -_n( 'I have a cat.', 'I have cats.', $number, "illegal $string" ); // Bad. -_n( 'I have a cat.', 'I have cats.', $number, SOMETHING ); // Bad. - -_n_noop( 'I have a cat.', 'I have cats.' ); // Bad, no text domain. -_n_noop( 'I have a cat.', 'I have cats.', 'my-slug' ); // OK. -_n_noop( 'I have a cat.', 'I have cats.', "illegal $string" ); // Bad. -_n_noop( 'I have a cat.', 'I have cats.', SOMETHING ); // Bad. - -_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.' ); // Bad, no text domain. -_nx( 'I have a cat.', 'I have cats.', $number, $context ); // Bad. -_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', 'my-slug' ); // OK. -_nx( 'I have a cat.', 'I have cats.', $number, $context, 'my-slug' ); // Bad. -_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', "illegal $string" ); // Bad. -_nx( 'I have a cat.', 'I have cats.', $number, 'Not really.', SOMETHING ); // Bad. - -_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.' ); // Bad, no text domain. -_nx_noop( 'I have a cat.', 'I have cats.', $context ); // Bad, no text domain, variable context. -_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', 'my-slug' ); // OK. -_nx_noop( 'I have a cat.', 'I have cats.', $context, 'my-slug' ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', "illegal $string" ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', SOMETHING ); // Bad. +_n( 'I have %d cat.', 'I have %d cats.', $number ); // Bad, no text domain. +_n( 'I have %d cat.', 'I have %d cats.', $number, 'my-slug' ); // OK. +_n( 'I have %d cat.', 'I have %d cats.', $number, "illegal $string" ); // Bad. +_n( 'I have %d cat.', 'I have %d cats.', $number, SOMETHING ); // Bad. + +_n_noop( 'I have %d cat.', 'I have %d cats.' ); // Bad, no text domain. +_n_noop( 'I have %d cat.', 'I have %d cats.', 'my-slug' ); // OK. +_n_noop( 'I have %d cat.', 'I have %d cats.', "illegal $string" ); // Bad. +_n_noop( 'I have %d cat.', 'I have %d cats.', SOMETHING ); // Bad. + +_nx( 'I have %d cat.', 'I have %d cats.', $number, 'Not really.' ); // Bad, no text domain. +_nx( 'I have %d cat.', 'I have %d cats.', $number, $context ); // Bad. +_nx( 'I have %d cat.', 'I have %d cats.', $number, 'Not really.', 'my-slug' ); // OK. +_nx( 'I have %d cat.', 'I have %d cats.', $number, $context, 'my-slug' ); // Bad. +_nx( 'I have %d cat.', 'I have %d cats.', $number, 'Not really.', "illegal $string" ); // Bad. +_nx( 'I have %d cat.', 'I have %d cats.', $number, 'Not really.', SOMETHING ); // Bad. + +_nx_noop( 'I have %d cat.', 'I have %d cats.', 'Not really.' ); // Bad, no text domain. +_nx_noop( 'I have %d cat.', 'I have %d cats.', $context ); // Bad, no text domain, variable context. +_nx_noop( 'I have %d cat.', 'I have %d cats.', 'Not really.', 'my-slug' ); // OK. +_nx_noop( 'I have %d cat.', 'I have %d cats.', $context, 'my-slug' ); // Bad. +_nx_noop( 'I have %d cat.', 'I have %d cats.', 'Not really.', "illegal $string" ); // Bad. +_nx_noop( 'I have %d cat.', 'I have %d cats.', 'Not really.', SOMETHING ); // Bad. translate( 'foo', 'bar' ); // Bad, low-level API function. translate_with_gettext_context( 'foo', 'bar', 'baz' ); // Bad, low-level API function. @@ -73,16 +73,19 @@ _( 'foo', 'bar' ); // Bad. __( 'foo', 'bar', 'too-many-args' ); // Bad. _x( 'string', 'context', 'domain', 'too-many-args' ); // Bad -_n( 'I have a cat.', 'I have cats.', $number, 'my-slug', 'too-many-args' ); // Bad -_n_noop( 'I have a cat.', 'I have cats.', 'my-slug', 'too-many-args' ); // Bad. -_nx_noop( 'I have a cat.', 'I have cats.', 'Not really.', 'my-slug', 'too-many-args' ); // Bad. +_n( 'I have %d cat.', 'I have %d cats.', $number, 'my-slug', 'too-many-args' ); // Bad +_n_noop( 'I have %d cat.', 'I have %d cats.', 'my-slug', 'too-many-args' ); // Bad. +_nx_noop( 'I have %d cat.', 'I have %d cats.', 'Not really.', 'my-slug', 'too-many-args' ); // Bad. // Make sure that multi-line string literals are accepted. _nx( 'I have -a cat.', 'I have -cats.', $number, 'Not +%d cat.', 'I have +%d cats.', $number, 'Not really.', 'my- slug' ); // OK. // Ensure lack of spaces doesn't cause i18n error. -_n_noop('I have a cat.', 'I have cats.', 'my-slug'); // OK. +_n_noop('I have %d cat.', 'I have %d cats.', 'my-slug'); // OK. + +// Dollar sign in literal string is not interpolated, so OK. +_n_noop( 'I have %d cat.', 'I have %d cats.', 'literal-string-so-$variable-not-interpolated' ); // OK. From 173a89ab7a5d425fee6b8f16eea4be0cb5fbecbf Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 25 Apr 2016 22:56:43 -0700 Subject: [PATCH 035/122] Introduce WordPress_Sniffs_WP_I18nSniff::$text_domain property Change i18n to report error instead of warning for $domain missing or mismatch if $text_domain is supplied --- WordPress/Sniffs/WP/I18nSniff.php | 52 +++++++++++++++++++++++----- WordPress/Tests/WP/I18nUnitTest.inc | 53 ++++++++++++++--------------- WordPress/Tests/WP/I18nUnitTest.php | 45 +++++++++++++----------- 3 files changed, 95 insertions(+), 55 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index a282fd5119..aa88a73895 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -10,6 +10,25 @@ */ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { + /** + * Text domain. + * + * @todo Eventually this should be able to be auto-supplied via looking at $phpcs_file->getFilename() + * @link https://youtrack.jetbrains.com/issue/WI-17740 + * + * @var string + */ + public $text_domain; + + /** + * Allow unit tests to override the supplied text_domain. + * + * @todo While it doesn't work, ideally this should be able to be done in \WordPress_Tests_WP_I18nUnitTest::setUp() + * + * @var string + */ + static $text_domain_override; + public $i18n_functions = array( 'translate' => 'simple', '__' => 'simple', @@ -53,6 +72,10 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $tokens = $phpcs_file->getTokens(); $token = $tokens[ $stack_ptr ]; + if ( ! empty( self::$text_domain_override ) ) { + $this->text_domain = self::$text_domain_override; + } + if ( '_' === $token['content'] ) { $phpcs_file->addError( 'Found single-underscore "_()" function when double-underscore expected.', $stack_ptr, 'SingleUnderscoreGetTextFunction' ); } @@ -117,31 +140,31 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $argument_assertions = array(); if ( 'simple' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } elseif ( 'context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'text', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } elseif ( 'number' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); array_shift( $arguments_tokens ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } elseif ( 'number_context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); array_shift( $arguments_tokens ); $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } elseif ( 'noopnumber' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } elseif ( 'noopnumber_context' === $this->i18n_functions[ $translation_function ] ) { $argument_assertions[] = array( 'arg_name' => 'single', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'plural', 'tokens' => array_shift( $arguments_tokens ) ); $argument_assertions[] = array( 'arg_name' => 'context', 'tokens' => array_shift( $arguments_tokens ) ); - $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ), 'warning' => true ); + $argument_assertions[] = array( 'arg_name' => 'domain', 'tokens' => array_shift( $arguments_tokens ) ); } if ( ! empty( $arguments_tokens ) ) { @@ -173,7 +196,9 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con if ( 0 === count( $tokens ) ) { $code = 'MissingArg' . ucfirst( $arg_name ); - $phpcs_file->$method( 'Missing $%s arg.', $stack_ptr, $code, array( $arg_name ) ); + if ( 'domain' !== $arg_name || ! empty( $this->text_domain ) ) { + $phpcs_file->$method( 'Missing $%s arg.', $stack_ptr, $code, array( $arg_name ) ); + } return false; } if ( count( $tokens ) > 1 ) { @@ -186,6 +211,10 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con return false; } if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { + if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $tokens[0]['content'], '\'""' ) !== $this->text_domain ) { + $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $tokens[0]['content'] ) ); + return false; + } return true; } if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { @@ -194,7 +223,14 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $code = 'InterpolatedVariable' . ucfirst( $arg_name ); $phpcs_file->$method( 'The $%s arg must not contain interpolated variables. Found "$%s".', $stack_ptr, $code, array( $arg_name, $interpolated_variable ) ); } - return false; + if ( ! empty( $interpolated_variables ) ) { + return false; + } + if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $tokens[0]['content'], '\'""' ) !== $this->text_domain ) { + $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $tokens[0]['content'] ) ); + return false; + } + return true; } $code = 'NonSingularStringLiteral' . ucfirst( $arg_name ); diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 422fe2da51..e75bb6a48b 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -1,46 +1,46 @@ setSniffProperty( 'WordPress_Sniffs_WP_I18nSniff', 'text_domain', 'my-slug' ); + WordPress_Sniffs_WP_I18nSniff::$text_domain_override = 'my-slug'; + parent::setUp(); + } + /** * Returns the lines where errors should occur. * @@ -23,27 +29,44 @@ public function getErrorList() { 3 => 1, 6 => 1, 9 => 1, + 11 => 1, 13 => 1, 15 => 1, 17 => 1, 19 => 1, 21 => 1, + 23 => 1, + 25 => 1, + 27 => 1, 33 => 1, 35 => 1, 37 => 1, 39 => 1, 41 => 1, 43 => 1, - 56 => 1, + 45 => 1, + 47 => 1, + 48 => 1, + 50 => 1, + 52 => 1, + 53 => 1, + 55 => 1, + 56 => 2, 58 => 1, - 63 => 1, + 59 => 1, + 60 => 1, + 62 => 1, + 63 => 2, 65 => 1, + 66 => 1, + 67 => 1, 72 => 1, 74 => 1, 75 => 1, 76 => 1, 77 => 1, 78 => 1, + ); } @@ -57,24 +80,6 @@ public function getErrorList() { */ public function getWarningList() { return array( - 11 => 1, - 23 => 1, - 25 => 1, - 27 => 1, - 45 => 1, - 47 => 1, - 48 => 1, - 50 => 1, - 52 => 1, - 53 => 1, - 55 => 1, - 56 => 1, - 59 => 1, - 60 => 1, - 62 => 1, - 63 => 1, - 66 => 1, - 67 => 1, 69 => 1, 70 => 1, ); From d21367bd2d1fb32dc45c703e56a864e8c248e5ed Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 25 Apr 2016 22:57:31 -0700 Subject: [PATCH 036/122] Add WordPress.WP.I18n to WordPress-Core --- WordPress-Core/ruleset.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 4d7a6e696f..35db8e6dbd 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -101,5 +101,6 @@ + From 0eabc71e9d832ced10e4fe55c400ece377a70a99 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 2 May 2016 23:12:29 +0200 Subject: [PATCH 037/122] Allow `translators:` comments. A bugfix upstream now causes `Doc comment short description must start with a capital letter` errors for `/* translators: ... */` comments. Excluding the offending rule to continue to allow these type of comments. --- WordPress-Docs/ruleset.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WordPress-Docs/ruleset.xml b/WordPress-Docs/ruleset.xml index 96a68eac13..df28928a6c 100644 --- a/WordPress-Docs/ruleset.xml +++ b/WordPress-Docs/ruleset.xml @@ -61,6 +61,8 @@ + + From e7707b2338e7823a2d14cfbdca8bdc88488d6081 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane?= Date: Tue, 3 May 2016 00:26:32 -0400 Subject: [PATCH 038/122] Update with latest VIP checks added check for get_intermediate_image_sizes() serialize() / unserialize() error_log(), var_dump(), trigger_error(), set_error_handler() wp_redirect(), wp_is_mobile() urlencode() --- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index d7deb3c7ef..a979fd6317 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -227,7 +227,9 @@ public function getGroups() { 'functions' => array( 'get_adjacent_post', 'get_previous_post', + 'get_previous_post_link', 'get_next_post', + 'get_next_post_link', ), ), @@ -239,6 +241,59 @@ public function getGroups() { ), ), + 'get_intermediate_image_sizes' => array( + 'type' => 'error', + 'message' => 'Intermediate images do not exist on the VIP platform, and thus get_intermediate_image_sizes() returns an empty array() on the platform. This behavior is intentional to prevent WordPress from generating multiple thumbnails when images are uploaded.', + 'functions' => array( + 'get_intermediate_image_sizes', + ), + ), + + 'serialize' => array( + 'type' => 'warning', + 'message' => '%s Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data.', + 'functions' => array( + 'serialize', + 'unserialize', + ), + ), + + 'error_log' => array( + 'type' => 'error', + 'message' => '%s Debug code is not allowed on VIP Production', + 'functions' => array( + 'error_log', + 'var_dump', + 'print_r', + 'trigger_error', + 'set_error_handler', + ), + ), + + 'wp_redirect' => array( + 'type' => 'warning', + 'message' => '%s Using wp_safe_redirect(), along with the allowed_redirect_hosts filter, can help avoid any chances of malicious redirects within code. It’s also important to remember to call exit() after a redirect so that no other unwanted code is executed.', + 'functions' => array( + 'wp_redirect', + ), + ), + + 'wp_is_mobile' => array( + 'type' => 'error', + 'message' => '%s When targeting mobile visitors, jetpack_is_mobile() should be used instead of wp_is_mobile. It is more robust and works better with full page caching.', + 'functions' => array( + 'wp_is_mobile', + ), + ), + + 'urlencode' => array( + 'type' => 'warning', + 'message' => '%s urlencode should only be used when dealing with legacy applications rawurlencode should now de used instead. See http://php.net/manual/en/function.rawurlencode.php and http://www.faqs.org/rfcs/rfc3986.html', + 'functions' => array( + 'rawurlencode', + ), + ), + ); } }//end class From 3eb1faa9ee02d1dccfa026038bb4497eaab51fb7 Mon Sep 17 00:00:00 2001 From: David Herrera Date: Mon, 9 May 2016 13:26:34 -0400 Subject: [PATCH 039/122] Allow 'posts_per_page' of up to 100 on VIP See https://vip.wordpress.com/documentation/code-review-what-we-look-for/#no-limit-queries. --- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index ce01a3ae0a..d97d1a9a6f 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -61,7 +61,7 @@ public function callback( $key, $val, $line, $group ) { in_array( $key, array( 'posts_per_page', 'numberposts' ) ) ) { - if ( $val > 50 ) { + if ( $val > 100 ) { return 'Detected high pagination limit, `%s` is set to `%s`'; } } From b7b615c2bd24ff8a05629e93a82fb9e569571ea1 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 8 Jun 2016 14:14:41 +1000 Subject: [PATCH 040/122] Add rule to check that multiple placeholders are ordered --- WordPress/Sniffs/WP/I18nSniff.php | 26 ++++++++++++++++++++++++++ WordPress/Tests/WP/I18nUnitTest.inc | 6 ++++++ WordPress/Tests/WP/I18nUnitTest.php | 3 ++- 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index aa88a73895..a4ba979189 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -210,6 +210,32 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $phpcs_file->$method( 'The $%s arg must be a single string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $contents ) ); return false; } + + // Check for multiple unordered placeholders. + // Regex copied from http://php.net/manual/en/function.sprintf.php#93552 + $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; + + if ( in_array( $arg_name, array( 'text', 'single', 'plural' ) ) ) { + preg_match_all( $unordered_sprintf_placeholder_regex, $tokens[0]['content'], $unordered_matches ); + $unordered_matches = $unordered_matches[0]; + + if ( count( $unordered_matches ) >= 2 ) { + $code = 'UnorderedPlaceholders' . ucfirst( $arg_name ); + + $suggestions = array(); + for ( $i = 0; $i < count( $unordered_matches ); $i++ ) { + $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], ( $i + 1 ) . '$', 1, 0 ); + } + + $phpcs_file->$method( + 'Multiple placeholders should be ordered. Expected \'%s\', but got %s.', + $stack_ptr, + 'UnorderedPlaceholders', + array( join( ', ', $suggestions ), join( ',', $unordered_matches ) ) + ); + } + } + if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $tokens[0]['content'], '\'""' ) !== $this->text_domain ) { $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $tokens[0]['content'] ) ); diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index e75bb6a48b..78777c7eec 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -88,3 +88,9 @@ _n_noop('I have %d cat.', 'I have %d cats.', 'my-slug'); // OK. // Dollar sign in literal string is not interpolated, so OK. _n_noop( 'I have %d cat.', 'I have %d cats literal-string-so-$variable-not-interpolated.', 'my-slug' ); // OK. + +// Multiple placeholders should have orderable +__( 'There are %d monkeys in the %s', 'my-slug' ); // Multiple arguments should be numbered +__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK +_n( 'There is %d monkey in the %s', 'There are %d monkeys in the %s', $number, 'my-slug' ); // Multiple arguments should be numbered +_n( 'There is %1$d monkey in the %2$s', 'In the %2$s are There are %1$d monkeys', $number, 'my-slug' ); // OK diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index ba54a42d18..35a66ba909 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -66,7 +66,8 @@ public function getErrorList() { 76 => 1, 77 => 1, 78 => 1, - + 93 => 1, + 95 => 2, ); } From 0523c41fa318de2dc348b4885c48b1ac90423136 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 8 Jun 2016 14:16:45 +1000 Subject: [PATCH 041/122] Pull out content once in check_argument_tokens() --- WordPress/Sniffs/WP/I18nSniff.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index a4ba979189..6a86d8540f 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -193,6 +193,7 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $tokens = $context['tokens']; $arg_name = $context['arg_name']; $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; + $content = $tokens[0]['content']; if ( 0 === count( $tokens ) ) { $code = 'MissingArg' . ucfirst( $arg_name ); @@ -216,7 +217,7 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; if ( in_array( $arg_name, array( 'text', 'single', 'plural' ) ) ) { - preg_match_all( $unordered_sprintf_placeholder_regex, $tokens[0]['content'], $unordered_matches ); + preg_match_all( $unordered_sprintf_placeholder_regex, $content, $unordered_matches ); $unordered_matches = $unordered_matches[0]; if ( count( $unordered_matches ) >= 2 ) { @@ -237,14 +238,14 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con } if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { - if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $tokens[0]['content'], '\'""' ) !== $this->text_domain ) { - $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $tokens[0]['content'] ) ); + if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $content, '\'""' ) !== $this->text_domain ) { + $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $content ) ); return false; } return true; } if ( T_DOUBLE_QUOTED_STRING === $tokens[0]['code'] ) { - $interpolated_variables = $this->get_interpolated_variables( $tokens[0]['content'] ); + $interpolated_variables = $this->get_interpolated_variables( $content ); foreach ( $interpolated_variables as $interpolated_variable ) { $code = 'InterpolatedVariable' . ucfirst( $arg_name ); $phpcs_file->$method( 'The $%s arg must not contain interpolated variables. Found "$%s".', $stack_ptr, $code, array( $arg_name, $interpolated_variable ) ); @@ -252,15 +253,15 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con if ( ! empty( $interpolated_variables ) ) { return false; } - if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $tokens[0]['content'], '\'""' ) !== $this->text_domain ) { - $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $tokens[0]['content'] ) ); + if ( 'domain' === $arg_name && ! empty( $this->text_domain ) && trim( $content, '\'""' ) !== $this->text_domain ) { + $phpcs_file->$method( 'Mismatch text domain. Expected \'%s\' but got %s.', $stack_ptr, 'TextDomainMismatch', array( $this->text_domain, $content ) ); return false; } return true; } $code = 'NonSingularStringLiteral' . ucfirst( $arg_name ); - $phpcs_file->$method( 'The $%s arg should be single a string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $tokens[0]['content'] ) ); + $phpcs_file->$method( 'The $%s arg should be single a string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $content ) ); return false; } } From c11c6fc209484c56af3003b39c122cef4c4d7077 Mon Sep 17 00:00:00 2001 From: alexiskulash Date: Sat, 11 Jun 2016 14:45:02 -0500 Subject: [PATCH 042/122] Added support for catching functions that will be deprecated once php7 updates --- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index a979fd6317..5a476025b9 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -294,6 +294,38 @@ public function getGroups() { ), ), + 'ereg' => array( + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_match() instead. See http://php.net/manual/en/function.ereg.php', + 'functions' => array( + 'ereg', + ), + ), + + 'eregi' => array( + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_match() with i modifier instead. See http://php.net/manual/en/function.eregi.php', + 'functions' => array( + 'eregi', + ), + ), + + 'ereg_replace' => array( + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_replace() instead. See http://php.net/manual/en/function.ereg-replace.php', + 'functions' => array( + 'ereg_replace', + ), + ), + + 'split' => array( + 'type' => 'error', + 'message' => '%s is prohibited, please use explode() or preg_split() instead. See http://php.net/manual/en/function.split.php', + 'functions' => array( + 'split', + ), + ), + ); } }//end class From 880e2fdc2de817c9079b45c715b13a6f484fb490 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 8 Jun 2016 14:41:54 +1000 Subject: [PATCH 043/122] Add fixer for unordered placeholder --- WordPress/Sniffs/WP/I18nSniff.php | 11 ++- WordPress/Tests/WP/I18nUnitTest.inc | 2 +- WordPress/Tests/WP/I18nUnitTest.inc.fixed | 96 +++++++++++++++++++++++ 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 WordPress/Tests/WP/I18nUnitTest.inc.fixed diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 6a86d8540f..34de3aab6f 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -194,6 +194,7 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $arg_name = $context['arg_name']; $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; $content = $tokens[0]['content']; + $fixable_method = empty( $context['warning'] ) ? 'addFixableError' : 'addFixableWarning'; if ( 0 === count( $tokens ) ) { $code = 'MissingArg' . ucfirst( $arg_name ); @@ -228,12 +229,20 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], ( $i + 1 ) . '$', 1, 0 ); } - $phpcs_file->$method( + $fix = $phpcs_file->$fixable_method( 'Multiple placeholders should be ordered. Expected \'%s\', but got %s.', $stack_ptr, 'UnorderedPlaceholders', array( join( ', ', $suggestions ), join( ',', $unordered_matches ) ) ); + + if ( true === $fix ) { + $fixed_str = str_replace( $unordered_matches, $suggestions, $content ); + + $phpcs_file->fixer->beginChangeset(); + $phpcs_file->fixer->replaceToken( $stack_ptr, $fixed_str ); + $phpcs_file->fixer->endChangeset(); + } } } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 78777c7eec..72f8292002 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -89,7 +89,7 @@ _n_noop('I have %d cat.', 'I have %d cats.', 'my-slug'); // OK. // Dollar sign in literal string is not interpolated, so OK. _n_noop( 'I have %d cat.', 'I have %d cats literal-string-so-$variable-not-interpolated.', 'my-slug' ); // OK. -// Multiple placeholders should have orderable +// Multiple placeholders should have orderable placeholders __( 'There are %d monkeys in the %s', 'my-slug' ); // Multiple arguments should be numbered __( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK _n( 'There is %d monkey in the %s', 'There are %d monkeys in the %s', $number, 'my-slug' ); // Multiple arguments should be numbered diff --git a/WordPress/Tests/WP/I18nUnitTest.inc.fixed b/WordPress/Tests/WP/I18nUnitTest.inc.fixed new file mode 100644 index 0000000000..7df3b8ff9b --- /dev/null +++ b/WordPress/Tests/WP/I18nUnitTest.inc.fixed @@ -0,0 +1,96 @@ + Date: Thu, 9 Jun 2016 12:51:08 +1000 Subject: [PATCH 044/122] Add check for mismatched placeholders --- WordPress/Sniffs/WP/I18nSniff.php | 47 +++++++++++++++++++++++ WordPress/Tests/WP/I18nUnitTest.inc | 17 +++++--- WordPress/Tests/WP/I18nUnitTest.inc.fixed | 17 +++++--- WordPress/Tests/WP/I18nUnitTest.php | 8 ++++ 4 files changed, 79 insertions(+), 10 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 34de3aab6f..6bc04af81a 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -179,6 +179,14 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { } call_user_func( array( $this, 'check_argument_tokens' ), $phpcs_file, $argument_assertion_context ); } + + // For _n*() calls, compare the singular and plural strings. + if ( false !== strpos( $this->i18n_functions[ $translation_function ], 'number' ) ) { + $single_context = $argument_assertions[0]; + $plural_context = $argument_assertions[1]; + + $this->compare_single_and_plural_arguments( $phpcs_file, $stack_ptr, $single_context, $plural_context ); + } } /** @@ -273,4 +281,43 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $phpcs_file->$method( 'The $%s arg should be single a string literal, not "%s".', $stack_ptr, $code, array( $arg_name, $content ) ); return false; } + + /** + * Check for inconsistencies between single and plural arguments. + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param array $single_context + * @param array $plural_context + * @return void + */ + protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $phpcs_file, $stack_ptr, $single_context, $plural_context ) { + $single_content = $single_context['tokens'][0]['content']; + $plural_content = $plural_context['tokens'][0]['content']; + + // Regex copied from http://php.net/manual/en/function.sprintf.php#93552 + $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; + + preg_match_all( $sprintf_placeholder_regex, $single_content, $single_placeholders ); + $single_placeholders = $single_placeholders[0]; + + preg_match_all( $sprintf_placeholder_regex, $plural_content, $plural_placeholders ); + $plural_placeholders = $plural_placeholders[0]; + + // English conflates "singular" with "only one", described in the codex: + // https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals + if ( count( $single_placeholders ) < count( $plural_placeholders ) ) { + $error_string = 'Missing singular placeholder, needed for some languages. See https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals'; + $single_index = $single_context['tokens'][0]['token_index']; + + $phpcs_file->addError( $error_string, $single_index, 'MissingSingularPlaceholder' ); + } + + // Reordering is fine, but mismatched placeholders is probably wrong. + sort( $single_placeholders ); + sort( $plural_placeholders ); + + if ( $single_placeholders !== $plural_placeholders ) { + $phpcs_file->addWarning( 'Mismatched placeholders is probably an error', $stack_ptr, 'MismatchedPlaceholders' ); + } + } } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 72f8292002..d5929c916a 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -89,8 +89,15 @@ _n_noop('I have %d cat.', 'I have %d cats.', 'my-slug'); // OK. // Dollar sign in literal string is not interpolated, so OK. _n_noop( 'I have %d cat.', 'I have %d cats literal-string-so-$variable-not-interpolated.', 'my-slug' ); // OK. -// Multiple placeholders should have orderable placeholders -__( 'There are %d monkeys in the %s', 'my-slug' ); // Multiple arguments should be numbered -__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK -_n( 'There is %d monkey in the %s', 'There are %d monkeys in the %s', $number, 'my-slug' ); // Multiple arguments should be numbered -_n( 'There is %1$d monkey in the %2$s', 'In the %2$s are There are %1$d monkeys', $number, 'my-slug' ); // OK +// Multiple placeholders should have orderable placeholders. +__( 'There are %d monkeys in the %s', 'my-slug' ); // Multiple arguments should be numbered. +__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK. +_n( 'There is %d monkey in the %s', 'There are %d monkeys in the %s', $number, 'my-slug' ); // Multiple arguments should be numbered. +_n( 'There is %1$d monkey in the %2$s', 'In the %2$s there are %1$d monkeys', $number, 'my-slug' ); // OK. + +// The singular form should use placeholders if the plural does. +// https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals +_n( 'I have a cat.', 'I have %d cats.', $number, 'my-slug' ); // Bad, singular should have placeholder. +_n_noop( 'I have a cat.', 'I have %d cats.', 'my-slug' ); // Bad, singular should have placeholder. +_nx( 'I have a cat.', 'I have %d cats.', $number, 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. +_nx_noop( 'I have a cat.', 'I have %d cats.', 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. diff --git a/WordPress/Tests/WP/I18nUnitTest.inc.fixed b/WordPress/Tests/WP/I18nUnitTest.inc.fixed index 7df3b8ff9b..0618202aec 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc.fixed +++ b/WordPress/Tests/WP/I18nUnitTest.inc.fixed @@ -89,8 +89,15 @@ _n_noop('I have %d cat.', 'I have %d cats.', 'my-slug'); // OK. // Dollar sign in literal string is not interpolated, so OK. _n_noop( 'I have %d cat.', 'I have %d cats literal-string-so-$variable-not-interpolated.', 'my-slug' ); // OK. -// Multiple placeholders should have orderable placeholders -__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // Multiple arguments should be numbered -__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK -_n( 'There is %1$d monkey in the %2$s', 'There are %1$d monkeys in the %2$s', $number, 'my-slug' ); // Multiple arguments should be numbered -_n( 'There is %1$d monkey in the %2$s', 'In the %2$s are There are %1$d monkeys', $number, 'my-slug' ); // OK +// Multiple placeholders should have orderable placeholders. +__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // Multiple arguments should be numbered. +__( 'There are %1$d monkeys in the %2$s', 'my-slug' ); // OK. +_n( 'There is %1$d monkey in the %2$s', 'There are %1$d monkeys in the %2$s', $number, 'my-slug' ); // Multiple arguments should be numbered. +_n( 'There is %1$d monkey in the %2$s', 'In the %2$s there are %1$d monkeys', $number, 'my-slug' ); // OK. + +// The singular form should use placeholders if the plural does. +// https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals +_n( 'I have a cat.', 'I have %d cats.', $number, 'my-slug' ); // Bad, singular should have placeholder. +_n_noop( 'I have a cat.', 'I have %d cats.', 'my-slug' ); // Bad, singular should have placeholder. +_nx( 'I have a cat.', 'I have %d cats.', $number, 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. +_nx_noop( 'I have a cat.', 'I have %d cats.', 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 35a66ba909..a5faa22d51 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -68,6 +68,10 @@ public function getErrorList() { 78 => 1, 93 => 1, 95 => 2, + 100 => 1, + 101 => 1, + 102 => 1, + 103 => 1, ); } @@ -83,6 +87,10 @@ public function getWarningList() { return array( 69 => 1, 70 => 1, + 100 => 1, + 101 => 1, + 102 => 1, + 103 => 1, ); } } From 9f88d3944d687278260f1b943974fec6deaeb3ff Mon Sep 17 00:00:00 2001 From: David Page Date: Mon, 13 Jun 2016 09:40:29 +0100 Subject: [PATCH 045/122] Remove `get_pages()` from uncached functions in WordPress.VIP.RestrictedFunctions It is cached and is no longer on the VIP restricted list. --- WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 5a476025b9..0857f7ffb7 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -177,12 +177,11 @@ public function getGroups() { ), ), - 'get_pages' => array( + 'get_children' => array( 'type' => 'error', 'message' => '%s is highly discouraged in favor of creating a new WP_Query() so that Advanced Post Cache will cache the query.', 'functions' => array( 'get_children', - 'get_pages', ), ), From aad1ebf7ccf2fd95c65629f9dd703f1af6d3399e Mon Sep 17 00:00:00 2001 From: David Page Date: Tue, 14 Jun 2016 11:47:10 +0100 Subject: [PATCH 046/122] Merge `get_children` group with `get_posts` group No need to have a separate group as `get_children()` is a wrapper for `get_posts()` --- WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 0857f7ffb7..8f5b1e9ab9 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -174,13 +174,6 @@ public function getGroups() { 'functions' => array( 'get_posts', 'wp_get_recent_posts', - ), - ), - - 'get_children' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged in favor of creating a new WP_Query() so that Advanced Post Cache will cache the query.', - 'functions' => array( 'get_children', ), ), From 24cf416a2ff705badc2599ed0f2bf03028045b81 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 15 Jun 2016 12:35:57 +1000 Subject: [PATCH 047/122] Move sprintf placeholder regexes into WP_I18nSniff class --- WordPress/Sniffs/WP/I18nSniff.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 6bc04af81a..08562ec6f6 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -48,6 +48,11 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { '_nx_noop' => 'noopnumber_context', ); + // These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552 + static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; + // "Unordered" means there's no position specifier: '%s', not '%2$s' + static $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; + /** * Returns an array of tokens this test wants to listen for. * @@ -222,11 +227,9 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con } // Check for multiple unordered placeholders. - // Regex copied from http://php.net/manual/en/function.sprintf.php#93552 - $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; if ( in_array( $arg_name, array( 'text', 'single', 'plural' ) ) ) { - preg_match_all( $unordered_sprintf_placeholder_regex, $content, $unordered_matches ); + preg_match_all( self::$unordered_sprintf_placeholder_regex, $content, $unordered_matches ); $unordered_matches = $unordered_matches[0]; if ( count( $unordered_matches ) >= 2 ) { @@ -294,13 +297,10 @@ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $ph $single_content = $single_context['tokens'][0]['content']; $plural_content = $plural_context['tokens'][0]['content']; - // Regex copied from http://php.net/manual/en/function.sprintf.php#93552 - $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; - - preg_match_all( $sprintf_placeholder_regex, $single_content, $single_placeholders ); + preg_match_all( self::$sprintf_placeholder_regex, $single_content, $single_placeholders ); $single_placeholders = $single_placeholders[0]; - preg_match_all( $sprintf_placeholder_regex, $plural_content, $plural_placeholders ); + preg_match_all( self::$sprintf_placeholder_regex, $plural_content, $plural_placeholders ); $plural_placeholders = $plural_placeholders[0]; // English conflates "singular" with "only one", described in the codex: From 888356ee74d3da7fe3ef2fb1f6d6b189f41f9033 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 15 Jun 2016 13:13:56 +1000 Subject: [PATCH 048/122] Factor out i18n test that focuses on the string itself --- WordPress/Sniffs/WP/I18nSniff.php | 75 ++++++++++++++++++------------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 08562ec6f6..cfc4c4af48 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -49,7 +49,7 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { ); // These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552 - static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; + static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; // "Unordered" means there's no position specifier: '%s', not '%2$s' static $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; @@ -207,7 +207,6 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con $arg_name = $context['arg_name']; $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; $content = $tokens[0]['content']; - $fixable_method = empty( $context['warning'] ) ? 'addFixableError' : 'addFixableWarning'; if ( 0 === count( $tokens ) ) { $code = 'MissingArg' . ucfirst( $arg_name ); @@ -226,35 +225,8 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con return false; } - // Check for multiple unordered placeholders. - if ( in_array( $arg_name, array( 'text', 'single', 'plural' ) ) ) { - preg_match_all( self::$unordered_sprintf_placeholder_regex, $content, $unordered_matches ); - $unordered_matches = $unordered_matches[0]; - - if ( count( $unordered_matches ) >= 2 ) { - $code = 'UnorderedPlaceholders' . ucfirst( $arg_name ); - - $suggestions = array(); - for ( $i = 0; $i < count( $unordered_matches ); $i++ ) { - $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], ( $i + 1 ) . '$', 1, 0 ); - } - - $fix = $phpcs_file->$fixable_method( - 'Multiple placeholders should be ordered. Expected \'%s\', but got %s.', - $stack_ptr, - 'UnorderedPlaceholders', - array( join( ', ', $suggestions ), join( ',', $unordered_matches ) ) - ); - - if ( true === $fix ) { - $fixed_str = str_replace( $unordered_matches, $suggestions, $content ); - - $phpcs_file->fixer->beginChangeset(); - $phpcs_file->fixer->replaceToken( $stack_ptr, $fixed_str ); - $phpcs_file->fixer->endChangeset(); - } - } + $this->check_text( $phpcs_file, $context ); } if ( T_CONSTANT_ENCAPSED_STRING === $tokens[0]['code'] ) { @@ -320,4 +292,47 @@ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $ph $phpcs_file->addWarning( 'Mismatched placeholders is probably an error', $stack_ptr, 'MismatchedPlaceholders' ); } } + + /** + * Check the string itself for problems + * + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param array $single_context + * @param array $plural_context + * @return void + */ + protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { + $stack_ptr = $context['stack_ptr']; + $arg_name = $context['arg_name']; + $content = $context['tokens'][0]['content']; + $fixable_method = empty( $context['warning'] ) ? 'addFixableError' : 'addFixableWarning'; + + // UnorderedPlaceholders: Check for multiple unordered placeholders. + preg_match_all( self::$unordered_sprintf_placeholder_regex, $content, $unordered_matches ); + $unordered_matches = $unordered_matches[0]; + + if ( count( $unordered_matches ) >= 2 ) { + $code = 'UnorderedPlaceholders' . ucfirst( $arg_name ); + + $suggestions = array(); + for ( $i = 0; $i < count( $unordered_matches ); $i++ ) { + $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], ( $i + 1 ) . '$', 1, 0 ); + } + + $fix = $phpcs_file->$fixable_method( + 'Multiple placeholders should be ordered. Expected \'%s\', but got %s.', + $stack_ptr, + 'UnorderedPlaceholders', + array( join( ', ', $suggestions ), join( ',', $unordered_matches ) ) + ); + + if ( true === $fix ) { + $fixed_str = str_replace( $unordered_matches, $suggestions, $content ); + + $phpcs_file->fixer->beginChangeset(); + $phpcs_file->fixer->replaceToken( $stack_ptr, $fixed_str ); + $phpcs_file->fixer->endChangeset(); + } + } + } } From 08aa148ed97336b1a03079d84861e7b792360707 Mon Sep 17 00:00:00 2001 From: Julian de Bhal Date: Wed, 15 Jun 2016 13:38:50 +1000 Subject: [PATCH 049/122] Add WP.I18n.NoEmptyStrings --- WordPress/Sniffs/WP/I18nSniff.php | 10 ++++++++++ WordPress/Tests/WP/I18nUnitTest.inc | 5 +++++ WordPress/Tests/WP/I18nUnitTest.inc.fixed | 5 +++++ WordPress/Tests/WP/I18nUnitTest.php | 3 +++ 4 files changed, 23 insertions(+) diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index cfc4c4af48..0a35fcf935 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -334,5 +334,15 @@ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { $phpcs_file->fixer->endChangeset(); } } + + // NoEmptyStrings + + // Strip placeholders and surrounding quotes. + $non_placeholder_content = trim( $content, "'" ); + $non_placeholder_content = preg_replace( self::$sprintf_placeholder_regex, '', $non_placeholder_content ); + + if ( empty( $non_placeholder_content ) ) { + $phpcs_file->addError( 'Strings should have translatable content', $stack_ptr, 'NoEmptyStrings' ); + } } } diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index d5929c916a..2a881d88f6 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -101,3 +101,8 @@ _n( 'I have a cat.', 'I have %d cats.', $number, 'my-slug' ); // Bad, singular s _n_noop( 'I have a cat.', 'I have %d cats.', 'my-slug' ); // Bad, singular should have placeholder. _nx( 'I have a cat.', 'I have %d cats.', $number, 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. _nx_noop( 'I have a cat.', 'I have %d cats.', 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. + +__( '%s', 'my-slug' ); // Bad, don't waste translator's time +__( '%1$s%2$s', 'my-slug' ); // Bad, don't waste translator's time +_n( 'I have %d cat.', '%d', $number, 'my-slug' ); // Bad, move the logic out of the translation +__( '\'%s\'', 'my-slug' ); // OK (ish. this is a technical test, not a great string) diff --git a/WordPress/Tests/WP/I18nUnitTest.inc.fixed b/WordPress/Tests/WP/I18nUnitTest.inc.fixed index 0618202aec..5475314362 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc.fixed +++ b/WordPress/Tests/WP/I18nUnitTest.inc.fixed @@ -101,3 +101,8 @@ _n( 'I have a cat.', 'I have %d cats.', $number, 'my-slug' ); // Bad, singular s _n_noop( 'I have a cat.', 'I have %d cats.', 'my-slug' ); // Bad, singular should have placeholder. _nx( 'I have a cat.', 'I have %d cats.', $number, 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. _nx_noop( 'I have a cat.', 'I have %d cats.', 'Not really.', 'my-slug' ); // Bad, singular should have placeholder. + +__( '%s', 'my-slug' ); // Bad, don't waste translator's time +__( '%1$s%2$s', 'my-slug' ); // Bad, don't waste translator's time +_n( 'I have %d cat.', '%d', $number, 'my-slug' ); // Bad, move the logic out of the translation +__( '\'%s\'', 'my-slug' ); // OK (ish. this is a technical test, not a great string) diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index a5faa22d51..dd80e444a8 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -72,6 +72,9 @@ public function getErrorList() { 101 => 1, 102 => 1, 103 => 1, + 105 => 1, + 106 => 1, + 107 => 1, ); } From cff5cff2d1d9b5a01bf6cf065d97b3cee84ad0a4 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 10 Jul 2016 17:44:52 +0200 Subject: [PATCH 050/122] Run travis against PHP 7.0 as well. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index c6d71fbf72..4905d2588f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 env: - PHPCS_BRANCH=master From 07bf22aa35219d60ec09d5a68498ddd3c0f03117 Mon Sep 17 00:00:00 2001 From: Ulrich Pogson Date: Mon, 11 Jul 2016 09:07:28 +0200 Subject: [PATCH 051/122] Sort the list in a better order --- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index a1f1c03dbf..05d32eeb69 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -22,8 +22,7 @@ * @package PHP_CodeSniffer * @author John Godley */ -class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ +class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { /** * A list of forbidden functions with their alternatives. @@ -34,17 +33,20 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ * @var array(string => string|null) */ public $forbiddenFunctions = array( - 'print_r' => null, - 'debug_print_backtrace' => null, + // Deprecated 'ereg_replace' => 'preg_replace', 'ereg' => null, 'eregi_replace' => 'preg_replace', - 'json_encode' => 'wp_json_encode', 'split' => null, 'spliti' => null, + // Development + 'print_r' => null, + 'debug_print_backtrace' => null, 'var_dump' => null, 'var_export' => null, - // WordPress + // Discouraged + 'json_encode' => 'wp_json_encode', + // WordPress deprecated 'find_base_dir' => 'WP_Filesystem::abspath', 'get_base_dir' => 'WP_Filesystem::abspath', 'dropdown_categories' => 'wp_link_category_checklist', @@ -59,6 +61,7 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ 'get_attachment_icon_src' => 'wp_get_attachment_image_src', 'get_attachment_icon' => 'wp_get_attachment_image', 'get_attachment_innerHTML' => 'wp_get_attachment_image', + // WordPress discouraged 'query_posts' => 'WP_Query', 'wp_reset_query' => 'wp_reset_postdata', ); @@ -71,5 +74,3 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ public $error = false; }//end class - -?> From eed3612b0b5a7431316a84387ab887f455dc8379 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 11 Jul 2016 15:20:59 +0200 Subject: [PATCH 052/122] Add runtime_configuration and path disclosure sections to the VIP.RestrictedFunctions sniff. Fixes #460 --- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 27 +++++++++++++++++++ .../Tests/VIP/RestrictedFunctionsUnitTest.inc | 13 +++++++++ .../Tests/VIP/RestrictedFunctionsUnitTest.php | 12 +++++++++ 3 files changed, 52 insertions(+) diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 5a476025b9..b9a859f7a4 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -326,6 +326,33 @@ public function getGroups() { ), ), + 'runtime_configuration' => array( + 'type' => 'error', + 'message' => '%s is prohibited, changing configuration at runtime is not allowed on VIP Production.', + 'functions' => array( + 'dl', + 'error_reporting', + 'ini_alter', + 'ini_restore', + 'ini_set', + 'magic_quotes_runtime', + 'set_magic_quotes_runtime', + 'apache_setenv', + 'putenv', + 'set_include_path', + 'restore_include_path', + ), + ), + + 'prevent_path_disclosure' => array( + 'type' => 'error', + 'message' => '%s is prohibited as it can lead to full path disclosure.', + 'functions' => array( + 'error_reporting', + 'phpinfo', + ), + ), + ); } }//end class diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index 93d4c66816..35f86b5a6a 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -70,3 +70,16 @@ get_adjacent_post(); // error get_previous_post(); // error get_next_post(); // error parse_url( 'http://example.com/' ); // warning + +dl(); // error +error_reporting(); // error +ini_alter(); // error +ini_restore(); // error +ini_set(); // error +magic_quotes_runtime(); // error +set_magic_quotes_runtime(); // error +apache_setenv(); // error +putenv(); // error +set_include_path(); // error +restore_include_path(); // error +phpinfo(); // error diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index a1778c1a8e..17ee7fa365 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -55,6 +55,18 @@ public function getErrorList() 69 => 1, 70 => 1, 71 => 1, + 74 => 1, + 75 => 2, + 76 => 1, + 77 => 1, + 78 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + 82 => 1, + 83 => 1, + 84 => 1, + 85 => 1, ); }//end getErrorList() From b788b57283990dcee5c201444d3bca6d5bbdd479 Mon Sep 17 00:00:00 2001 From: David Page Date: Mon, 11 Jul 2016 14:48:06 +0100 Subject: [PATCH 053/122] Remove get_pages() from unit testing Relates to #573 --- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc | 2 +- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index 93d4c66816..679ce45f35 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -57,7 +57,7 @@ url_to_post_id(); // error attachment_url_to_postid(); // error get_posts(); // warning wp_get_recent_posts(); // warning -get_pages(); // error + get_children(); // error wp_get_post_terms(); // error wp_get_post_categories(); // error diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index a1778c1a8e..93d12c4998 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -43,7 +43,6 @@ public function getErrorList() 55 => 1, 56 => 1, 57 => 1, - 60 => 1, 61 => 1, 62 => 1, 63 => 1, From 0c8c34b63dc7507cf13aac3b093368a1d7562896 Mon Sep 17 00:00:00 2001 From: David Page Date: Mon, 11 Jul 2016 14:49:30 +0100 Subject: [PATCH 054/122] Switch get_children() from error to warning Merging in with the same as functions wp_get_recent_posts() Relates to #573 --- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc | 2 +- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index 679ce45f35..28ec5d6901 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -58,7 +58,7 @@ attachment_url_to_postid(); // error get_posts(); // warning wp_get_recent_posts(); // warning -get_children(); // error +get_children(); // warning wp_get_post_terms(); // error wp_get_post_categories(); // error wp_get_post_tags(); // error diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index 93d12c4998..998ab0bb36 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -43,7 +43,6 @@ public function getErrorList() 55 => 1, 56 => 1, 57 => 1, - 61 => 1, 62 => 1, 63 => 1, 64 => 1, @@ -79,6 +78,7 @@ public function getWarningList() 19 => 1, 58 => 1, 59 => 1, + 61 => 1, 72 => 1, ); From d9bf003b89e3d8759a969a9eef197e6ce5cec26b Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 11:39:48 +0200 Subject: [PATCH 055/122] Initial setup of automated code style check for the WPCS library itself. --- .travis.yml | 13 +++++++++++++ bin/phpcs.xml | 10 ++++++++++ 2 files changed, 23 insertions(+) create mode 100644 bin/phpcs.xml diff --git a/.travis.yml b/.travis.yml index 4905d2588f..2b91b15f04 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,9 @@ env: matrix: fast_finish: true include: + # Run PHPCS against WPCS. I just picked to run it against 5.5. + - php: 5.5 + env: PHPCS_BRANCH=master SNIFF=1 # Run against PHPCS 3.0. I just picked to run it against 5.6. - php: 5.6 env: PHPCS_BRANCH=3.0 @@ -41,3 +44,13 @@ before_script: script: - if find . -name "*.php" -exec php -l {} \; | grep "^[Parse error|Fatal error]"; then exit 1; fi; - phpunit --filter WordPress /tmp/phpcs/tests/AllTests.php + # WordPress Coding Standards. + # @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + # @link http://pear.php.net/package/PHP_CodeSniffer/ + # -p flag: Show progress of the run. + # -s flag: Show sniff codes in all reports. + # -v flag: Print verbose output. + # -n flag: Do not print warnings. (shortcut for --warning-severity=0) + # --standard: Use WordPress as the standard. + # --extensions: Only sniff PHP files. + - if [[ "$SNIFF" == "1" ]]; then $PHPCS_DIR/scripts/phpcs -p -s -v -n . --standard=./bin/phpcs.xml --extensions=php; fi \ No newline at end of file diff --git a/bin/phpcs.xml b/bin/phpcs.xml new file mode 100644 index 0000000000..ba0e060e35 --- /dev/null +++ b/bin/phpcs.xml @@ -0,0 +1,10 @@ + + + The Coding standard for the WordPress Coding Standards itself. + + + + + + + From b0e50f951f83d7f8e67e041ec02926b7b86728e8 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 13:30:45 +0200 Subject: [PATCH 056/122] Code style adjustments for all sniffs to comply with WordPress-Core standard. --- WordPress/Sniff.php | 566 +++++----- .../ArrayAssignmentRestrictionsSniff.php | 118 +- .../Sniffs/Arrays/ArrayDeclarationSniff.php | 457 ++++---- .../ArrayKeySpacingRestrictionsSniff.php | 49 +- .../Sniffs/CSRF/NonceVerificationSniff.php | 7 +- .../Sniffs/Classes/ValidClassNameSniff.php | 100 +- WordPress/Sniffs/Files/FileNameSniff.php | 83 +- .../Functions/FunctionRestrictionsSniff.php | 76 +- .../ValidFunctionNameSniff.php | 254 +++-- .../ValidVariableNameSniff.php | 34 +- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 50 +- .../Sniffs/PHP/StrictComparisonsSniff.php | 26 +- WordPress/Sniffs/PHP/StrictInArraySniff.php | 12 +- WordPress/Sniffs/PHP/YodaConditionsSniff.php | 42 +- WordPress/Sniffs/VIP/AdminBarRemovalSniff.php | 31 +- WordPress/Sniffs/VIP/CronIntervalSniff.php | 61 +- .../Sniffs/VIP/DirectDatabaseQuerySniff.php | 74 +- .../VIP/FileSystemWritesDisallowSniff.php | 67 +- WordPress/Sniffs/VIP/OrderByRandSniff.php | 15 +- WordPress/Sniffs/VIP/PluginMenuSlugSniff.php | 29 +- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 50 +- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 164 +-- .../Sniffs/VIP/RestrictedVariablesSniff.php | 27 +- .../Sniffs/VIP/SessionFunctionsUsageSniff.php | 83 +- .../Sniffs/VIP/SessionVariableUsageSniff.php | 69 +- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 27 +- .../Sniffs/VIP/SuperGlobalInputUsageSniff.php | 30 +- WordPress/Sniffs/VIP/TimezoneChangeSniff.php | 37 +- .../VIP/ValidatedSanitizedInputSniff.php | 11 +- .../Sniffs/Variables/GlobalVariablesSniff.php | 29 +- .../Variables/VariableRestrictionsSniff.php | 123 +- .../Sniffs/WP/EnqueuedResourcesSniff.php | 86 +- WordPress/Sniffs/WP/I18nSniff.php | 65 +- WordPress/Sniffs/WP/PreparedSQLSniff.php | 40 +- .../WhiteSpace/CastStructureSpacingSniff.php | 103 +- .../ControlStructureSpacingSniff.php | 1003 ++++++++--------- .../WhiteSpace/OperatorSpacingSniff.php | 383 ++++--- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 82 +- 38 files changed, 2217 insertions(+), 2346 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index 99e5f87d42..c3a83755c7 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -1,5 +1,4 @@ true, + 'wp_verify_nonce' => true, 'check_admin_referer' => true, - 'check_ajax_referer' => true, + 'check_ajax_referer' => true, ); /** @@ -42,37 +41,37 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $escapingFunctions = array( - 'absint' => true, - 'esc_attr__' => true, - 'esc_attr_e' => true, - 'esc_attr_x' => true, - 'esc_attr' => true, - 'esc_html__' => true, - 'esc_html_e' => true, - 'esc_html_x' => true, - 'esc_html' => true, - 'esc_js' => true, - 'esc_sql' => true, - 'esc_textarea' => true, - 'esc_url_raw' => true, - 'esc_url' => true, - 'filter_input' => true, - 'filter_var' => true, - 'intval' => true, - 'json_encode' => true, - 'like_escape' => true, - 'number_format' => true, - 'rawurlencode' => true, - 'sanitize_html_class' => true, - 'sanitize_user_field' => true, - 'tag_escape' => true, - 'urlencode_deep' => true, - 'urlencode' => true, - 'wp_json_encode' => true, + 'absint' => true, + 'esc_attr__' => true, + 'esc_attr_e' => true, + 'esc_attr_x' => true, + 'esc_attr' => true, + 'esc_html__' => true, + 'esc_html_e' => true, + 'esc_html_x' => true, + 'esc_html' => true, + 'esc_js' => true, + 'esc_sql' => true, + 'esc_textarea' => true, + 'esc_url_raw' => true, + 'esc_url' => true, + 'filter_input' => true, + 'filter_var' => true, + 'intval' => true, + 'json_encode' => true, + 'like_escape' => true, + 'number_format' => true, + 'rawurlencode' => true, + 'sanitize_html_class' => true, + 'sanitize_user_field' => true, + 'tag_escape' => true, + 'urlencode_deep' => true, + 'urlencode' => true, + 'wp_json_encode' => true, 'wp_kses_allowed_html' => true, - 'wp_kses_data' => true, - 'wp_kses_post' => true, - 'wp_kses' => true, + 'wp_kses_data' => true, + 'wp_kses_post' => true, + 'wp_kses' => true, ); /** @@ -83,150 +82,150 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $autoEscapedFunctions = array( - 'allowed_tags' => true, - 'bloginfo' => true, - 'body_class' => true, - 'calendar_week_mod' => true, + 'allowed_tags' => true, + 'bloginfo' => true, + 'body_class' => true, + 'calendar_week_mod' => true, 'cancel_comment_reply_link' => true, - 'category_description' => true, - 'checked' => true, + 'category_description' => true, + 'checked' => true, 'comment_author_email_link' => true, - 'comment_author_email' => true, - 'comment_author_IP' => true, - 'comment_author_link' => true, - 'comment_author_rss' => true, - 'comment_author_url_link' => true, - 'comment_author_url' => true, - 'comment_author' => true, - 'comment_class' => true, - 'comment_date' => true, - 'comment_excerpt' => true, - 'comment_form_title' => true, - 'comment_form' => true, - 'comment_id_fields' => true, - 'comment_ID' => true, - 'comment_reply_link' => true, - 'comment_text_rss' => true, - 'comment_text' => true, - 'comment_time' => true, - 'comment_type' => true, - 'comments_link' => true, - 'comments_number' => true, - 'comments_popup_link' => true, - 'comments_popup_script' => true, - 'comments_rss_link' => true, - 'count' => true, + 'comment_author_email' => true, + 'comment_author_IP' => true, + 'comment_author_link' => true, + 'comment_author_rss' => true, + 'comment_author_url_link' => true, + 'comment_author_url' => true, + 'comment_author' => true, + 'comment_class' => true, + 'comment_date' => true, + 'comment_excerpt' => true, + 'comment_form_title' => true, + 'comment_form' => true, + 'comment_id_fields' => true, + 'comment_ID' => true, + 'comment_reply_link' => true, + 'comment_text_rss' => true, + 'comment_text' => true, + 'comment_time' => true, + 'comment_type' => true, + 'comments_link' => true, + 'comments_number' => true, + 'comments_popup_link' => true, + 'comments_popup_script' => true, + 'comments_rss_link' => true, + 'count' => true, 'delete_get_calendar_cache' => true, - 'disabled' => true, - 'do_shortcode' => true, - 'do_shortcode_tag' => true, - 'edit_bookmark_link' => true, - 'edit_comment_link' => true, - 'edit_post_link' => true, - 'edit_tag_link' => true, - 'get_archives_link' => true, - 'get_attachment_link' => true, - 'get_avatar' => true, - 'get_bookmark_field' => true, - 'get_bookmark' => true, - 'get_calendar' => true, - 'get_comment_author_link' => true, - 'get_comment_date' => true, - 'get_comment_time' => true, - 'get_current_blog_id' => true, - 'get_delete_post_link' => true, - 'get_footer' => true, - 'get_header' => true, - 'get_search_form' => true, - 'get_search_query' => true, - 'get_sidebar' => true, - 'get_template_part' => true, - 'get_the_author_link' => true, - 'get_the_author' => true, - 'get_the_date' => true, - 'get_the_post_thumbnail' => true, - 'get_the_term_list' => true, - 'get_the_title' => true, - 'has_post_thumbnail' => true, - 'is_attachment' => true, - 'next_comments_link' => true, - 'next_image_link' => true, - 'next_post_link' => true, - 'next_posts_link' => true, - 'paginate_comments_links' => true, - 'permalink_anchor' => true, - 'post_class' => true, - 'post_password_required' => true, - 'post_type_archive_title' => true, - 'posts_nav_link' => true, - 'previous_comments_link' => true, - 'previous_image_link' => true, - 'previous_post_link' => true, - 'previous_posts_link' => true, - 'selected' => true, - 'single_cat_title' => true, - 'single_month_title' => true, - 'single_post_title' => true, - 'single_tag_title' => true, - 'single_term_title' => true, - 'sticky_class' => true, - 'tag_description' => true, - 'term_description' => true, - 'the_attachment_link' => true, - 'the_author_link' => true, - 'the_author_meta' => true, - 'the_author_posts_link' => true, - 'the_author_posts' => true, - 'the_author' => true, - 'the_category_rss' => true, - 'the_category' => true, - 'the_content_rss' => true, - 'the_content' => true, - 'the_date_xml' => true, - 'the_date' => true, - 'the_excerpt_rss' => true, - 'the_excerpt' => true, - 'the_feed_link' => true, - 'the_ID' => true, - 'the_meta' => true, - 'the_modified_author' => true, - 'the_modified_date' => true, - 'the_modified_time' => true, - 'the_permalink' => true, - 'the_post_thumbnail' => true, - 'the_search_query' => true, - 'the_shortlink' => true, - 'the_tags' => true, - 'the_taxonomies' => true, - 'the_terms' => true, - 'the_time' => true, - 'the_title_attribute' => true, - 'the_title_rss' => true, - 'the_title' => true, - 'vip_powered_wpcom' => true, - 'walk_nav_menu_tree' => true, - 'wp_attachment_is_image' => true, - 'wp_dropdown_categories' => true, - 'wp_dropdown_users' => true, - 'wp_enqueue_script' => true, - 'wp_generate_tag_cloud' => true, - 'wp_get_archives' => true, - 'wp_get_attachment_image' => true, - 'wp_get_attachment_link' => true, - 'wp_link_pages' => true, - 'wp_list_authors' => true, - 'wp_list_bookmarks' => true, - 'wp_list_categories' => true, - 'wp_list_comments' => true, - 'wp_login_form' => true, - 'wp_loginout' => true, - 'wp_meta' => true, - 'wp_nav_menu' => true, - 'wp_register' => true, - 'wp_shortlink_header' => true, - 'wp_shortlink_wp_head' => true, - 'wp_tag_cloud' => true, - 'wp_title' => true, + 'disabled' => true, + 'do_shortcode' => true, + 'do_shortcode_tag' => true, + 'edit_bookmark_link' => true, + 'edit_comment_link' => true, + 'edit_post_link' => true, + 'edit_tag_link' => true, + 'get_archives_link' => true, + 'get_attachment_link' => true, + 'get_avatar' => true, + 'get_bookmark_field' => true, + 'get_bookmark' => true, + 'get_calendar' => true, + 'get_comment_author_link' => true, + 'get_comment_date' => true, + 'get_comment_time' => true, + 'get_current_blog_id' => true, + 'get_delete_post_link' => true, + 'get_footer' => true, + 'get_header' => true, + 'get_search_form' => true, + 'get_search_query' => true, + 'get_sidebar' => true, + 'get_template_part' => true, + 'get_the_author_link' => true, + 'get_the_author' => true, + 'get_the_date' => true, + 'get_the_post_thumbnail' => true, + 'get_the_term_list' => true, + 'get_the_title' => true, + 'has_post_thumbnail' => true, + 'is_attachment' => true, + 'next_comments_link' => true, + 'next_image_link' => true, + 'next_post_link' => true, + 'next_posts_link' => true, + 'paginate_comments_links' => true, + 'permalink_anchor' => true, + 'post_class' => true, + 'post_password_required' => true, + 'post_type_archive_title' => true, + 'posts_nav_link' => true, + 'previous_comments_link' => true, + 'previous_image_link' => true, + 'previous_post_link' => true, + 'previous_posts_link' => true, + 'selected' => true, + 'single_cat_title' => true, + 'single_month_title' => true, + 'single_post_title' => true, + 'single_tag_title' => true, + 'single_term_title' => true, + 'sticky_class' => true, + 'tag_description' => true, + 'term_description' => true, + 'the_attachment_link' => true, + 'the_author_link' => true, + 'the_author_meta' => true, + 'the_author_posts_link' => true, + 'the_author_posts' => true, + 'the_author' => true, + 'the_category_rss' => true, + 'the_category' => true, + 'the_content_rss' => true, + 'the_content' => true, + 'the_date_xml' => true, + 'the_date' => true, + 'the_excerpt_rss' => true, + 'the_excerpt' => true, + 'the_feed_link' => true, + 'the_ID' => true, + 'the_meta' => true, + 'the_modified_author' => true, + 'the_modified_date' => true, + 'the_modified_time' => true, + 'the_permalink' => true, + 'the_post_thumbnail' => true, + 'the_search_query' => true, + 'the_shortlink' => true, + 'the_tags' => true, + 'the_taxonomies' => true, + 'the_terms' => true, + 'the_time' => true, + 'the_title_attribute' => true, + 'the_title_rss' => true, + 'the_title' => true, + 'vip_powered_wpcom' => true, + 'walk_nav_menu_tree' => true, + 'wp_attachment_is_image' => true, + 'wp_dropdown_categories' => true, + 'wp_dropdown_users' => true, + 'wp_enqueue_script' => true, + 'wp_generate_tag_cloud' => true, + 'wp_get_archives' => true, + 'wp_get_attachment_image' => true, + 'wp_get_attachment_link' => true, + 'wp_link_pages' => true, + 'wp_list_authors' => true, + 'wp_list_bookmarks' => true, + 'wp_list_categories' => true, + 'wp_list_comments' => true, + 'wp_login_form' => true, + 'wp_loginout' => true, + 'wp_meta' => true, + 'wp_nav_menu' => true, + 'wp_register' => true, + 'wp_shortlink_header' => true, + 'wp_shortlink_wp_head' => true, + 'wp_tag_cloud' => true, + 'wp_title' => true, ); /** @@ -237,46 +236,46 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $sanitizingFunctions = array( - '_wp_handle_upload' => true, - 'absint' => true, - 'array_key_exists' => true, - 'esc_url_raw' => true, - 'filter_input' => true, - 'filter_var' => true, - 'hash_equals' => true, - 'in_array' => true, - 'intval' => true, - 'is_array' => true, - 'is_email' => true, - 'number_format' => true, - 'sanitize_bookmark_field' => true, - 'sanitize_bookmark' => true, - 'sanitize_email' => true, - 'sanitize_file_name' => true, - 'sanitize_html_class' => true, - 'sanitize_key' => true, - 'sanitize_meta' => true, - 'sanitize_mime_type' => true, - 'sanitize_option' => true, - 'sanitize_sql_orderby' => true, - 'sanitize_term_field' => true, - 'sanitize_term' => true, - 'sanitize_text_field' => true, - 'sanitize_title_for_query' => true, + '_wp_handle_upload' => true, + 'absint' => true, + 'array_key_exists' => true, + 'esc_url_raw' => true, + 'filter_input' => true, + 'filter_var' => true, + 'hash_equals' => true, + 'in_array' => true, + 'intval' => true, + 'is_array' => true, + 'is_email' => true, + 'number_format' => true, + 'sanitize_bookmark_field' => true, + 'sanitize_bookmark' => true, + 'sanitize_email' => true, + 'sanitize_file_name' => true, + 'sanitize_html_class' => true, + 'sanitize_key' => true, + 'sanitize_meta' => true, + 'sanitize_mime_type' => true, + 'sanitize_option' => true, + 'sanitize_sql_orderby' => true, + 'sanitize_term_field' => true, + 'sanitize_term' => true, + 'sanitize_text_field' => true, + 'sanitize_title_for_query' => true, 'sanitize_title_with_dashes' => true, - 'sanitize_title' => true, - 'sanitize_user_field' => true, - 'sanitize_user' => true, - 'validate_file' => true, - 'wp_handle_sideload' => true, - 'wp_handle_upload' => true, - 'wp_kses_allowed_html' => true, - 'wp_kses_data' => true, - 'wp_kses_post' => true, - 'wp_kses' => true, - 'wp_parse_id_list' => true, - 'wp_redirect' => true, - 'wp_safe_redirect' => true, + 'sanitize_title' => true, + 'sanitize_user_field' => true, + 'sanitize_user' => true, + 'validate_file' => true, + 'wp_handle_sideload' => true, + 'wp_handle_upload' => true, + 'wp_kses_allowed_html' => true, + 'wp_kses_data' => true, + 'wp_kses_post' => true, + 'wp_kses' => true, + 'wp_parse_id_list' => true, + 'wp_redirect' => true, + 'wp_safe_redirect' => true, ); /** @@ -287,10 +286,10 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $unslashingSanitizingFunctions = array( - 'absint' => true, - 'boolval' => true, - 'intval' => true, - 'is_array' => true, + 'absint' => true, + 'boolval' => true, + 'intval' => true, + 'is_array' => true, 'sanitize_key' => true, ); @@ -309,12 +308,12 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { */ public static $formattingFunctions = array( 'array_fill' => true, - 'ent2ncr' => true, - 'implode' => true, - 'join' => true, - 'nl2br' => true, - 'sprintf' => true, - 'vsprintf' => true, + 'ent2ncr' => true, + 'implode' => true, + 'join' => true, + 'nl2br' => true, + 'sprintf' => true, + 'vsprintf' => true, 'wp_sprintf' => true, ); @@ -327,21 +326,21 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { */ public static $printingFunctions = array( '_deprecated_argument' => true, - '_deprecated_file' => true, + '_deprecated_file' => true, '_deprecated_function' => true, - '_doing_it_wrong' => true, - '_e' => true, - '_ex' => true, - 'die' => true, - 'echo' => true, - 'exit' => true, - 'print' => true, - 'printf' => true, - 'trigger_error' => true, - 'user_error' => true, - 'vprintf' => true, - 'wp_die' => true, - 'wp_dropdown_pages' => true, + '_doing_it_wrong' => true, + '_e' => true, + '_ex' => true, + 'die' => true, + 'echo' => true, + 'exit' => true, + 'print' => true, + 'printf' => true, + 'trigger_error' => true, + 'user_error' => true, + 'vprintf' => true, + 'wp_die' => true, + 'wp_dropdown_pages' => true, ); /** @@ -352,9 +351,9 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $SQLEscapingFunctions = array( - 'absint' => true, - 'esc_sql' => true, - 'intval' => true, + 'absint' => true, + 'esc_sql' => true, + 'intval' => true, 'like_escape' => true, ); @@ -442,7 +441,7 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { */ protected function init( PHP_CodeSniffer_File $phpcsFile ) { $this->phpcsFile = $phpcsFile; - $this->tokens = $phpcsFile->getTokens(); + $this->tokens = $phpcsFile->getTokens(); } /** @@ -457,9 +456,9 @@ protected function init( PHP_CodeSniffer_File $phpcsFile ) { */ protected function get_last_ptr_on_line( $stackPtr ) { - $tokens = $this->tokens; + $tokens = $this->tokens; $currentLine = $tokens[ $stackPtr ]['line']; - $nextPtr = $stackPtr + 1; + $nextPtr = ( $stackPtr + 1 ); while ( isset( $tokens[ $nextPtr ] ) && $tokens[ $nextPtr ]['line'] === $currentLine ) { $nextPtr++; @@ -468,7 +467,7 @@ protected function get_last_ptr_on_line( $stackPtr ) { // We've made it to the next line, back up one to the last in the previous line. // We do this for micro-optimization of the above loop. - $lastPtr = $nextPtr - 1; + $lastPtr = ( $nextPtr - 1 ); return $lastPtr; } @@ -501,10 +500,7 @@ protected function has_whitelist_comment( $comment, $stackPtr ) { // There is a findEndOfStatement() method, but it considers more tokens than // we need to here. - $end_of_statement = $this->phpcsFile->findNext( - array( T_CLOSE_TAG, T_SEMICOLON ) - , $stackPtr - ); + $end_of_statement = $this->phpcsFile->findNext( array( T_CLOSE_TAG, T_SEMICOLON ), $stackPtr ); // Check at the end of the statement if it comes before the end of the line. if ( $end_of_statement < $end_of_line ) { @@ -513,9 +509,9 @@ protected function has_whitelist_comment( $comment, $stackPtr ) { // whitespace token. If the semicolon was left out and it was terminated // by an ending tag, we need to look backwards. if ( T_SEMICOLON === $this->tokens[ $end_of_statement ]['code'] ) { - $lastPtr = $this->phpcsFile->findNext( T_WHITESPACE, $end_of_statement + 1, null, true ); + $lastPtr = $this->phpcsFile->findNext( T_WHITESPACE, ( $end_of_statement + 1 ), null, true ); } else { - $lastPtr = $this->phpcsFile->findPrevious( T_WHITESPACE, $end_of_statement - 1, null, true ); + $lastPtr = $this->phpcsFile->findPrevious( T_WHITESPACE, ( $end_of_statement - 1 ), null, true ); } } @@ -549,13 +545,13 @@ protected function is_assignment( $stackPtr ) { $tokens = $this->phpcsFile->getTokens(); // Must be a variable or closing square bracket (see below). - if ( ! in_array( $tokens[ $stackPtr ]['code'], array( T_VARIABLE, T_CLOSE_SQUARE_BRACKET ) ) ) { + if ( ! in_array( $tokens[ $stackPtr ]['code'], array( T_VARIABLE, T_CLOSE_SQUARE_BRACKET ), true ) ) { return false; } $next_non_empty = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens - , $stackPtr + 1 + , ( $stackPtr + 1 ) , null , true , null @@ -568,7 +564,7 @@ protected function is_assignment( $stackPtr ) { } // If the next token is an assignment, that's all we need to know. - if ( in_array( $tokens[ $next_non_empty ]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens ) ) { + if ( in_array( $tokens[ $next_non_empty ]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens, true ) ) { return true; } @@ -605,7 +601,7 @@ protected function has_nonce_check( $stackPtr ) { static $last; $start = 0; - $end = $stackPtr; + $end = $stackPtr; $tokens = $this->phpcsFile->getTokens(); @@ -694,7 +690,7 @@ protected function is_in_isset_or_empty( $stackPtr ) { $open_parenthesis = key( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); reset( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); - return in_array( $this->tokens[ $open_parenthesis - 1 ]['code'], array( T_ISSET, T_EMPTY ) ); + return in_array( $this->tokens[ ( $open_parenthesis - 1 ) ]['code'], array( T_ISSET, T_EMPTY ), true ); } /** @@ -744,16 +740,13 @@ protected function is_safe_casted( $stackPtr ) { // Get the last non-empty token. $prev = $this->phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens - , $stackPtr - 1 + , ( $stackPtr - 1 ) , null , true ); // Check if it is a safe cast. - return in_array( - $this->tokens[ $prev ]['code'] - , array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ) - ); + return in_array( $this->tokens[ $prev ]['code'], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ); } /** @@ -785,7 +778,7 @@ protected function is_sanitized( $stackPtr, $require_unslash = false ) { // Get the function that it's in. $function_closer = end( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); $function_opener = key( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); - $function = $this->tokens[ $function_opener - 1 ]; + $function = $this->tokens[ ( $function_opener - 1 ) ]; // If it is just being unset, the value isn't used at all, so it's safe. if ( T_UNSET === $function['code'] ) { @@ -805,8 +798,7 @@ protected function is_sanitized( $stackPtr, $require_unslash = false ) { // Check if wp_unslash() is being used. if ( 'wp_unslash' === $functionName ) { - $is_unslashed = true; - + $is_unslashed = true; $function_closer = prev( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); // If there is no other function being used, this value is unsanitized. @@ -815,7 +807,7 @@ protected function is_sanitized( $stackPtr, $require_unslash = false ) { } $function_opener = key( $this->tokens[ $stackPtr ]['nested_parenthesis'] ); - $functionName = $this->tokens[ $function_opener - 1 ]['content']; + $functionName = $this->tokens[ ( $function_opener - 1 ) ]['content']; } else { @@ -828,7 +820,7 @@ protected function is_sanitized( $stackPtr, $require_unslash = false ) { // Get the first parameter (name of function being used on the array). $mapped_function = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens - , $function_opener + 1 + , ( $function_opener + 1 ) , $function_closer , true ); @@ -881,7 +873,7 @@ protected function get_array_access_key( $stackPtr ) { // Find the next non-empty token. $open_bracket = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - $stackPtr + 1, + ( $stackPtr + 1 ), null, true ); @@ -892,8 +884,8 @@ protected function get_array_access_key( $stackPtr ) { } $key = $this->phpcsFile->getTokensAsString( - $open_bracket + 1 - , $this->tokens[ $open_bracket ]['bracket_closer'] - $open_bracket - 1 + ( $open_bracket + 1 ) + , ( $this->tokens[ $open_bracket ]['bracket_closer'] - $open_bracket - 1 ) ); return trim( $key ); @@ -937,8 +929,10 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl if ( $in_condition_only ) { - // This is a stricter check, requiring the variable to be used only - // within the validation condition. + /* + This is a stricter check, requiring the variable to be used only + within the validation condition. + */ // If there are no conditions, there's no validation. if ( empty( $this->tokens[ $stackPtr ]['conditions'] ) ) { @@ -946,9 +940,9 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl } $conditions = $this->tokens[ $stackPtr ]['conditions']; - end( $conditions ); // Get closest condition + end( $conditions ); // Get closest condition. $conditionPtr = key( $conditions ); - $condition = $this->tokens[ $conditionPtr ]; + $condition = $this->tokens[ $conditionPtr ]; if ( ! isset( $condition['parenthesis_opener'] ) ) { @@ -966,8 +960,10 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl } else { - // We are are more loose, requiring only that the variable be validated - // in the same function/file scope as it is used. + /* + We are are more loose, requiring only that the variable be validated + in the same function/file scope as it is used. + */ // Check if we are in a function. $function = $this->phpcsFile->findPrevious( T_FUNCTION, $stackPtr ); @@ -982,9 +978,9 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl $scope_end = $stackPtr; } - for ( $i = $scope_start + 1; $i < $scope_end; $i++ ) { + for ( $i = ( $scope_start + 1 ); $i < $scope_end; $i++ ) { - if ( ! in_array( $this->tokens[ $i ]['code'], array( T_ISSET, T_EMPTY, T_UNSET ) ) ) { + if ( ! in_array( $this->tokens[ $i ]['code'], array( T_ISSET, T_EMPTY, T_UNSET ), true ) ) { continue; } @@ -992,7 +988,7 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl $issetCloser = $this->tokens[ $issetOpener ]['parenthesis_closer']; // Look for this variable. We purposely stomp $i from the parent loop. - for ( $i = $issetOpener + 1; $i < $issetCloser; $i++ ) { + for ( $i = ( $issetOpener + 1 ); $i < $issetCloser; $i++ ) { if ( T_VARIABLE !== $this->tokens[ $i ]['code'] ) { continue; @@ -1042,19 +1038,19 @@ protected function is_comparison( $stackPtr ) { // yoda conditions are usually expected. $previous_token = $this->phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, - $stackPtr - 1, + ( $stackPtr - 1 ), null, true ); - if ( in_array( $this->tokens[ $previous_token ]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens ) ) { + if ( in_array( $this->tokens[ $previous_token ]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens, true ) ) { return true; } // Maybe the comparison operator is after this. $next_token = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - $stackPtr + 1, + ( $stackPtr + 1 ), null, true ); @@ -1064,13 +1060,13 @@ protected function is_comparison( $stackPtr ) { $next_token = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - $this->tokens[ $next_token ]['bracket_closer'] + 1, + ( $this->tokens[ $next_token ]['bracket_closer'] + 1 ), null, true ); } - if ( in_array( $this->tokens[ $next_token ]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens ) ) { + if ( in_array( $this->tokens[ $next_token ]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens, true ) ) { return true; } @@ -1096,7 +1092,7 @@ protected function is_comparison( $stackPtr ) { protected function get_use_type( $stackPtr ) { // USE keywords inside closures. - $next = $this->phpcsFile->findNext( T_WHITESPACE, $stackPtr + 1, null, true ); + $next = $this->phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); if ( T_OPEN_PARENTHESIS === $this->tokens[ $next ]['code'] ) { return 'closure'; @@ -1124,7 +1120,7 @@ protected function get_interpolated_variables( $string ) { $variables = array(); if ( preg_match_all( '/(?P\\\\*)\$(?P\w+)/', $string, $match_sets, PREG_SET_ORDER ) ) { foreach ( $match_sets as $matches ) { - if ( strlen( $matches['backslashes'] ) % 2 === 0 ) { + if ( ( strlen( $matches['backslashes'] ) % 2 ) === 0 ) { $variables[] = $matches['symbol']; } } @@ -1132,5 +1128,3 @@ protected function get_interpolated_variables( $string ) { return $variables; } } - -// EOF diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index ec4843a325..13d675c71a 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -1,20 +1,19 @@ */ -class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_Sniff -{ +class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_Sniff { /** - * Exclude groups + * Exclude groups. * * Example: 'foo,bar' * - * @var string Comma-delimited group list + * @var string Comma-delimited group list. */ public $exclude = ''; @@ -33,19 +32,19 @@ class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress * * @return array */ - public function register() - { + public function register() { return array( - T_DOUBLE_ARROW, - T_CLOSE_SQUARE_BRACKET, - T_CONSTANT_ENCAPSED_STRING, - T_DOUBLE_QUOTED_STRING, - ); + T_DOUBLE_ARROW, + T_CLOSE_SQUARE_BRACKET, + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + ); + + } // end register() - }//end register() /** - * Groups of variables to restrict + * Groups of variables to restrict. * This should be overridden in extending classes. * * Example: groups => array( @@ -74,8 +73,7 @@ public function getGroups() { * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $groups = $this->getGroups(); @@ -84,45 +82,47 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) return; } - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; $exclude = explode( ',', $this->exclude ); - if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET ) ) ) { - $equal = $phpcsFile->findNext( T_WHITESPACE, $stackPtr + 1, null, true ); - if ( $tokens[$equal]['code'] !== T_EQUAL ) { + if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET ), true ) ) { + $equal = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + if ( T_EQUAL !== $tokens[ $equal ]['code'] ) { return; // This is not an assignment! } } - // Instances: Multi-dimensional array, keyed by line + // Instances: Multi-dimensional array, keyed by line. $inst = array(); - // $foo = array( 'bar' => 'taz' ); - // $foo['bar'] = $taz; - if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET, T_DOUBLE_ARROW ) ) ) { - if ( $token['code'] == T_CLOSE_SQUARE_BRACKET ) { - $operator = $phpcsFile->findNext( array( T_EQUAL ), $stackPtr + 1 ); - } elseif ( $token['code'] == T_DOUBLE_ARROW ) { + /* + Covers: + $foo = array( 'bar' => 'taz' ); + $foo['bar'] = $taz; + */ + if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET, T_DOUBLE_ARROW ), true ) ) { + if ( T_CLOSE_SQUARE_BRACKET === $token['code'] ) { + $operator = $phpcsFile->findNext( array( T_EQUAL ), ( $stackPtr + 1 ) ); + } elseif ( T_DOUBLE_ARROW === $token['code'] ) { $operator = $stackPtr; } - $keyIdx = $phpcsFile->findPrevious( array( T_WHITESPACE, T_CLOSE_SQUARE_BRACKET ), $operator - 1, null, true ); - if ( ! is_numeric( $tokens[$keyIdx]['content'] ) ) { - $key = trim( $tokens[$keyIdx]['content'], '\'"' ); - $valStart = $phpcsFile->findNext( array( T_WHITESPACE ), $operator + 1, null, true ); - $valEnd = $phpcsFile->findNext( array( T_COMMA, T_SEMICOLON ), $valStart + 1, null, false, null, true ); - $val = $phpcsFile->getTokensAsString( $valStart, $valEnd - $valStart ); - $val = trim( $val, '\'"' ); + $keyIdx = $phpcsFile->findPrevious( array( T_WHITESPACE, T_CLOSE_SQUARE_BRACKET ), ( $operator - 1 ), null, true ); + if ( ! is_numeric( $tokens[ $keyIdx ]['content'] ) ) { + $key = trim( $tokens[ $keyIdx ]['content'], '\'"' ); + $valStart = $phpcsFile->findNext( array( T_WHITESPACE ), ( $operator + 1 ), null, true ); + $valEnd = $phpcsFile->findNext( array( T_COMMA, T_SEMICOLON ), ( $valStart + 1 ), null, false, null, true ); + $val = $phpcsFile->getTokensAsString( $valStart, ( $valEnd - $valStart ) ); + $val = trim( $val, '\'"' ); $inst[ $key ][] = array( $val, $token['line'] ); } - } - // $foo = 'bar=taz&other=thing'; - elseif ( in_array( $token['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ) ) ) { + } elseif ( in_array( $token['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { + // $foo = 'bar=taz&other=thing'; if ( preg_match_all( '#[\'"&]([a-z_]+)=([^\'"&]*)#i', $token['content'], $matches ) <= 0 ) { - return; // No assignments here, nothing to check + return; // No assignments here, nothing to check. } foreach ( $matches[1] as $i => $_k ) { - $inst[ $_k ][] = array( $matches[2][$i], $token['line'] ); + $inst[ $_k ][] = array( $matches[2][ $i ], $token['line'] ); } } @@ -130,10 +130,9 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) return; } - foreach ( $groups as $groupName => $group ) { - if ( in_array( $groupName, $exclude ) ) { + if ( in_array( $groupName, $exclude, true ) ) { continue; } @@ -143,21 +142,21 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) foreach ( $assignments as $occurance ) { list( $val, $line ) = $occurance; - if ( ! in_array( $key, $group['keys'] ) ) { + if ( ! in_array( $key, $group['keys'], true ) ) { continue; } $output = call_user_func( $callback, $key, $val, $line, $group ); - if ( $output === false || $output === null ) { + if ( ! isset( $output ) || false === $output ) { continue; - } elseif ( $output === true ) { + } elseif ( true === $output ) { $message = $group['message']; } else { $message = $output; } - if ( $group['type'] == 'warning' ) { + if ( 'warning' === $group['type'] ) { $addWhat = array( $phpcsFile, 'addWarning' ); } else { $addWhat = array( $phpcsFile, 'addError' ); @@ -169,30 +168,27 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $stackPtr, $groupName, array( $key, $val ) - ); + ); } } - - // return; // Show one error only - + // return; // Show one error only. } - }//end process() + } // end process() /** - * Callback to process each confirmed key, to check value - * This must be extended to add the logic to check assignment value + * Callback to process each confirmed key, to check value. + * This must be extended to add the logic to check assignment value. * - * @param string $key Array index / key - * @param mixed $val Assigned value - * @param int $line Token line - * @param array $group Group definition - * @return mixed FALSE if no match, TRUE if matches, STRING if matches with custom error message passed to ->process() + * @param string $key Array index / key. + * @param mixed $val Assigned value. + * @param int $line Token line. + * @param array $group Group definition. + * @return mixed FALSE if no match, TRUE if matches, STRING if matches + * with custom error message passed to ->process(). */ public function callback( $key, $val, $line, $group ) { return true; } - - -}//end class +} // end class diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php index 66eaf5a1fc..c17aaea26e 100644 --- a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -1,6 +1,6 @@ getTokens(); // Check that there is a single space after the array opener. - if ( T_WHITESPACE !== $tokens[ $arrayStart + 1 ]['code'] ) { + if ( T_WHITESPACE !== $tokens[ ( $arrayStart + 1 ) ]['code'] ) { $warning = 'Missing space after array opener.'; - $fix = $phpcsFile->addFixableError( $warning, $arrayStart, 'NoSpaceAfterOpenParenthesis' ); + $fix = $phpcsFile->addFixableError( $warning, $arrayStart, 'NoSpaceAfterOpenParenthesis' ); - if ( $fix ) { + if ( true === $fix ) { $phpcsFile->fixer->addContent( $arrayStart, ' ' ); } - - } elseif ( ' ' !== $tokens[ $arrayStart + 1 ]['content'] ) { + } elseif ( ' ' !== $tokens[ ( $arrayStart + 1 ) ]['content'] ) { $fix = $phpcsFile->addFixableError( 'Expected 1 space after array opener, found %s.', $arrayStart, 'SpaceAfterArrayOpener', - strlen( $tokens[ $arrayStart + 1 ]['content'] ) + strlen( $tokens[ ( $arrayStart + 1 ) ]['content'] ) ); - if ( $fix ) { - $phpcsFile->fixer->replaceToken( $arrayStart + 1, ' ' ); + if ( true === $fix ) { + $phpcsFile->fixer->replaceToken( ( $arrayStart + 1 ), ' ' ); } } - if ( T_WHITESPACE !== $tokens[ $arrayEnd - 1 ]['code'] ) { + if ( T_WHITESPACE !== $tokens[ ( $arrayEnd - 1 ) ]['code'] ) { $warning = 'Missing space before array closer.'; - $fix = $phpcsFile->addFixableError( $warning, $arrayEnd, 'NoSpaceAfterOpenParenthesis' ); + $fix = $phpcsFile->addFixableError( $warning, $arrayEnd, 'NoSpaceAfterOpenParenthesis' ); - if ( $fix ) { + if ( true === $fix ) { $phpcsFile->fixer->addContentBefore( $arrayEnd, ' ' ); } - - } elseif ( ' ' !== $tokens[ $arrayEnd - 1 ]['content'] ) { + } elseif ( ' ' !== $tokens[ ( $arrayEnd - 1 ) ]['content'] ) { $fix = $phpcsFile->addFixableError( 'Expected 1 space before array closer, found %s.', $arrayEnd, 'SpaceAfterArrayCloser', - strlen( $tokens[ $arrayEnd - 1 ]['content'] ) + strlen( $tokens[ ( $arrayEnd - 1 ) ]['content'] ) ); - if ( $fix ) { - $phpcsFile->fixer->replaceToken( $arrayEnd - 1, ' ' ); + if ( true === $fix ) { + $phpcsFile->fixer->replaceToken( ( $arrayEnd - 1 ), ' ' ); } } } @@ -90,37 +88,37 @@ public function processSingleLineArray( PHP_CodeSniffer_File $phpcsFile, $stackP */ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $arrayStart, $arrayEnd ) { $tokens = $phpcsFile->getTokens(); - $keywordStart = $tokens[$stackPtr]['column']; + $keywordStart = $tokens[ $stackPtr ]['column']; // Check the closing bracket is on a new line. - $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($arrayEnd - 1), $arrayStart, true); - if ($tokens[$lastContent]['line'] === $tokens[$arrayEnd]['line']) { + $lastContent = $phpcsFile->findPrevious( T_WHITESPACE, ( $arrayEnd - 1 ), $arrayStart, true ); + if ( $tokens[ $lastContent ]['line'] === $tokens[ $arrayEnd ]['line'] ) { $error = 'Closing parenthesis of array declaration must be on a new line'; - $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNewLine'); - if ($fix === true) { - $phpcsFile->fixer->addNewlineBefore($arrayEnd); + $fix = $phpcsFile->addFixableError( $error, $arrayEnd, 'CloseBraceNewLine' ); + if ( true === $fix ) { + $phpcsFile->fixer->addNewlineBefore( $arrayEnd ); } /* - } else if ($tokens[$arrayEnd]['column'] !== $keywordStart) { + } elseif ( $tokens[ $arrayEnd ]['column'] !== $keywordStart ) { // Check the closing bracket is lined up under the "a" in array. - $expected = ($keywordStart - 1); - $found = ($tokens[$arrayEnd]['column'] - 1); + $expected = ( $keywordStart - 1 ); + $found = ( $tokens[ $arrayEnd ]['column'] - 1 ); $error = 'Closing parenthesis not aligned correctly; expected %s space(s) but found %s'; $data = array( $expected, $found, ); - $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNotAligned', $data); - if ($fix === true) { - if ($found === 0) { - $phpcsFile->fixer->addContent(($arrayEnd - 1), str_repeat(' ', $expected)); + $fix = $phpcsFile->addFixableError( $error, $arrayEnd, 'CloseBraceNotAligned', $data ); + if ( true === $fix ) { + if ( 0 === $found ) { + $phpcsFile->fixer->addContent( ( $arrayEnd - 1 ), str_repeat(' ', $expected ) ); } else { - $phpcsFile->fixer->replaceToken(($arrayEnd - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $arrayEnd - 1 ), str_repeat(' ', $expected ) ); } } */ - }//end if + } // end if $nextToken = $stackPtr; $keyUsed = false; @@ -128,33 +126,33 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt $indices = array(); $maxLength = 0; - if ($tokens[$stackPtr]['code'] === T_ARRAY) { - $lastToken = $tokens[$stackPtr]['parenthesis_opener']; + if ( T_ARRAY === $tokens[ $stackPtr ]['code'] ) { + $lastToken = $tokens[ $stackPtr ]['parenthesis_opener']; } else { $lastToken = $stackPtr; } // Find all the double arrows that reside in this scope. - for ($nextToken = ($stackPtr + 1); $nextToken < $arrayEnd; $nextToken++) { + for ( $nextToken = ( $stackPtr + 1 ); $nextToken < $arrayEnd; $nextToken++ ) { // Skip bracketed statements, like function calls. - if ($tokens[$nextToken]['code'] === T_OPEN_PARENTHESIS - && (isset($tokens[$nextToken]['parenthesis_owner']) === false - || $tokens[$nextToken]['parenthesis_owner'] !== $stackPtr) + if ( T_OPEN_PARENTHESIS === $tokens[ $nextToken ]['code'] + && ( ! isset( $tokens[ $nextToken ]['parenthesis_owner'] ) + || $tokens[ $nextToken ]['parenthesis_owner'] !== $stackPtr ) ) { - $nextToken = $tokens[$nextToken]['parenthesis_closer']; + $nextToken = $tokens[ $nextToken ]['parenthesis_closer']; continue; } - if ($tokens[$nextToken]['code'] === T_ARRAY) { + if ( T_ARRAY === $tokens[ $nextToken ]['code'] ) { // Let subsequent calls of this test handle nested arrays. - if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) { - $indices[] = array('value' => $nextToken); + if ( T_DOUBLE_ARROW !== $tokens[ $lastToken ]['code'] ) { + $indices[] = array( 'value' => $nextToken ); $lastToken = $nextToken; } - $nextToken = $tokens[$tokens[$nextToken]['parenthesis_opener']]['parenthesis_closer']; - $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); - if ($tokens[$nextToken]['code'] !== T_COMMA) { + $nextToken = $tokens[ $tokens[ $nextToken ]['parenthesis_opener'] ]['parenthesis_closer']; + $nextToken = $phpcsFile->findNext( T_WHITESPACE, ( $nextToken + 1 ), null, true ); + if ( T_COMMA !== $tokens[ $nextToken ]['code'] ) { $nextToken--; } else { $lastToken = $nextToken; @@ -163,16 +161,16 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt continue; } - if ($tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY) { + if ( T_OPEN_SHORT_ARRAY === $tokens[ $nextToken ]['code'] ) { // Let subsequent calls of this test handle nested arrays. - if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) { - $indices[] = array('value' => $nextToken); + if ( T_DOUBLE_ARROW !== $tokens[ $lastToken ]['code'] ) { + $indices[] = array( 'value' => $nextToken ); $lastToken = $nextToken; } - $nextToken = $tokens[$nextToken]['bracket_closer']; - $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); - if ($tokens[$nextToken]['code'] !== T_COMMA) { + $nextToken = $tokens[ $nextToken ]['bracket_closer']; + $nextToken = $phpcsFile->findNext( T_WHITESPACE, ( $nextToken + 1 ), null, true ); + if ( T_COMMA !== $tokens[ $nextToken ]['code'] ) { $nextToken--; } else { $lastToken = $nextToken; @@ -181,15 +179,15 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt continue; } - if ($tokens[$nextToken]['code'] === T_CLOSURE) { - if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) { - $indices[] = array('value' => $nextToken); + if ( T_CLOSURE === $tokens[ $nextToken ]['code'] ) { + if ( T_DOUBLE_ARROW !== $tokens[ $lastToken ]['code'] ) { + $indices[] = array( 'value' => $nextToken ); $lastToken = $nextToken; } - $nextToken = $tokens[$nextToken]['scope_closer']; - $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); - if ($tokens[$nextToken]['code'] !== T_COMMA) { + $nextToken = $tokens[ $nextToken ]['scope_closer']; + $nextToken = $phpcsFile->findNext( T_WHITESPACE, ( $nextToken + 1 ), null, true ); + if ( T_COMMA !== $tokens[ $nextToken ]['code'] ) { $nextToken--; } else { $lastToken = $nextToken; @@ -198,30 +196,28 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt continue; } - if ($tokens[$nextToken]['code'] !== T_DOUBLE_ARROW - && $tokens[$nextToken]['code'] !== T_COMMA - ) { + if ( T_DOUBLE_ARROW !== $tokens[ $nextToken ]['code'] && T_COMMA !== $tokens[ $nextToken ]['code'] ) { continue; } $currentEntry = array(); - if ($tokens[$nextToken]['code'] === T_COMMA) { + if ( T_COMMA === $tokens[ $nextToken ]['code'] ) { $stackPtrCount = 0; - if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { - $stackPtrCount = count($tokens[$stackPtr]['nested_parenthesis']); + if ( isset( $tokens[ $stackPtr ]['nested_parenthesis'] ) ) { + $stackPtrCount = count( $tokens[ $stackPtr ]['nested_parenthesis'] ); } $commaCount = 0; - if (isset($tokens[$nextToken]['nested_parenthesis']) === true) { - $commaCount = count($tokens[$nextToken]['nested_parenthesis']); - if ($tokens[$stackPtr]['code'] === T_ARRAY) { + if ( isset( $tokens[ $nextToken ]['nested_parenthesis'] ) ) { + $commaCount = count( $tokens[ $nextToken ]['nested_parenthesis'] ); + if ( T_ARRAY === $tokens[ $stackPtr ]['code'] ) { // Remove parenthesis that are used to define the array. $commaCount--; } } - if ($commaCount > $stackPtrCount) { + if ( $commaCount > $stackPtrCount ) { // This comma is inside more parenthesis than the ARRAY keyword, // then there it is actually a comma used to separate arguments // in a function call. @@ -229,20 +225,20 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt } /* - if ($keyUsed === true && $tokens[$lastToken]['code'] === T_COMMA) { + if ( true === $keyUsed && T_COMMA === $tokens[ $lastToken ]['code'] ) { $error = 'No key specified for array entry; first entry specifies key'; - $phpcsFile->addError($error, $nextToken, 'NoKeySpecified'); + $phpcsFile->addError( $error, $nextToken, 'NoKeySpecified' ); return; } */ - if ($keyUsed === false) { - if ($tokens[($nextToken - 1)]['code'] === T_WHITESPACE) { - $content = $tokens[($nextToken - 2)]['content']; - if ($tokens[($nextToken - 1)]['content'] === $phpcsFile->eolChar) { + if ( false === $keyUsed ) { + if ( T_WHITESPACE === $tokens[ ( $nextToken - 1 ) ]['code'] ) { + $content = $tokens[ ( $nextToken - 2 ) ]['content']; + if ( $tokens[ ( $nextToken - 1 ) ]['content'] === $phpcsFile->eolChar ) { $spaceLength = 'newline'; } else { - $spaceLength = $tokens[($nextToken - 1)]['length']; + $spaceLength = $tokens[ ( $nextToken - 1 ) ]['length']; } $error = 'Expected 0 spaces between "%s" and comma; %s found'; @@ -251,116 +247,115 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt $spaceLength, ); - $fix = $phpcsFile->addFixableError($error, $nextToken, 'SpaceBeforeComma', $data); - if ($fix === true) { - $phpcsFile->fixer->replaceToken(($nextToken - 1), ''); + $fix = $phpcsFile->addFixableError( $error, $nextToken, 'SpaceBeforeComma', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->replaceToken( ( $nextToken - 1 ), '' ); } } $valueContent = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - ($lastToken + 1), + ( $lastToken + 1 ), $nextToken, true ); - $indices[] = array('value' => $valueContent); + $indices[] = array( 'value' => $valueContent ); $singleUsed = true; - }//end if + } // end if $lastToken = $nextToken; continue; - }//end if + } // end if - - if ($tokens[$nextToken]['code'] === T_DOUBLE_ARROW) { + if ( T_DOUBLE_ARROW === $tokens[ $nextToken ]['code'] ) { /* - if ($singleUsed === true) { + if ( true === $singleUsed ) { $error = 'Key specified for array entry; first entry has no key'; - $phpcsFile->addError($error, $nextToken, 'KeySpecified'); + $phpcsFile->addError( $error, $nextToken, 'KeySpecified' ); return; } */ $currentEntry['arrow'] = $nextToken; - $keyUsed = true; + $keyUsed = true; // Find the start of index that uses this double arrow. - $indexEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($nextToken - 1), $arrayStart, true); - $indexStart = $phpcsFile->findStartOfStatement($indexEnd); + $indexEnd = $phpcsFile->findPrevious( T_WHITESPACE, ( $nextToken - 1 ), $arrayStart, true ); + $indexStart = $phpcsFile->findStartOfStatement( $indexEnd ); - if ($indexStart === $indexEnd) { + if ( $indexStart === $indexEnd ) { $currentEntry['index'] = $indexEnd; - $currentEntry['index_content'] = $tokens[$indexEnd]['content']; + $currentEntry['index_content'] = $tokens[ $indexEnd ]['content']; } else { $currentEntry['index'] = $indexStart; - $currentEntry['index_content'] = $phpcsFile->getTokensAsString($indexStart, ($indexEnd - $indexStart + 1)); + $currentEntry['index_content'] = $phpcsFile->getTokensAsString( $indexStart, ( $indexEnd - $indexStart + 1 ) ); } - $indexLength = strlen($currentEntry['index_content']); - if ($maxLength < $indexLength) { + $indexLength = strlen( $currentEntry['index_content'] ); + if ( $maxLength < $indexLength ) { $maxLength = $indexLength; } // Find the value of this index. $nextContent = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - ($nextToken + 1), + ( $nextToken + 1 ), $arrayEnd, true ); $currentEntry['value'] = $nextContent; - $indices[] = $currentEntry; - $lastToken = $nextToken; - }//end if - }//end for + $indices[] = $currentEntry; + $lastToken = $nextToken; + } // end if + } // end for // Check for mutli-line arrays that should be single-line. $singleValue = false; - if (empty($indices) === true) { + if ( empty( $indices ) ) { $singleValue = true; - } else if (count($indices) === 1 && $tokens[$lastToken]['code'] === T_COMMA) { + } elseif ( 1 === count( $indices ) && T_COMMA === $tokens[ $lastToken ]['code'] ) { // There may be another array value without a comma. $exclude = PHP_CodeSniffer_Tokens::$emptyTokens; $exclude[] = T_COMMA; - $nextContent = $phpcsFile->findNext($exclude, ($indices[0]['value'] + 1), $arrayEnd, true); - if ($nextContent === false) { + $nextContent = $phpcsFile->findNext( $exclude, ( $indices[0]['value'] + 1 ), $arrayEnd, true ); + if ( false === $nextContent ) { $singleValue = true; } } /* - if ($singleValue === true) { + if ( true === $singleValue ) { // Array cannot be empty, so this is a multi-line array with // a single value. It should be defined on single line. $error = 'Multi-line array contains a single value; use single-line array instead'; - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'MultiLineNotAllowed'); + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'MultiLineNotAllowed' ); - if ($fix === true) { + if ( true === $fix ) { $phpcsFile->fixer->beginChangeset(); - for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { - if ($tokens[$i]['code'] !== T_WHITESPACE) { + for ( $i = ( $arrayStart + 1 ); $i < $arrayEnd; $i++ ) { + if ( T_WHITESPACE !== $tokens[ $i ]['code'] ) { break; } - $phpcsFile->fixer->replaceToken($i, ''); + $phpcsFile->fixer->replaceToken( $i, '' ); } - for ($i = ($arrayEnd - 1); $i > $arrayStart; $i--) { - if ($tokens[$i]['code'] !== T_WHITESPACE) { + for ( $i = ( $arrayEnd - 1 ); $i > $arrayStart; $i-- ) { + if ( T_WHITESPACE !== $tokens[ $i ]['code'] ) { break; } - $phpcsFile->fixer->replaceToken($i, ''); + $phpcsFile->fixer->replaceToken( $i, '' ); } $phpcsFile->fixer->endChangeset(); } return; - }//end if + } // end if */ /* @@ -374,75 +369,75 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt ); */ - if ($keyUsed === false && empty($indices) === false) { - $count = count($indices); - $lastIndex = $indices[($count - 1)]['value']; + if ( false === $keyUsed && ! empty( $indices ) ) { + $count = count( $indices ); + $lastIndex = $indices[ ( $count - 1 ) ]['value']; $trailingContent = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, - ($arrayEnd - 1), + ( $arrayEnd - 1 ), $lastIndex, true ); - if ($tokens[$trailingContent]['code'] !== T_COMMA) { - $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no'); + if ( T_COMMA !== $tokens[ $trailingContent ]['code'] ) { + $phpcsFile->recordMetric( $stackPtr, 'Array end comma', 'no' ); $error = 'Comma required after last value in array declaration'; - $fix = $phpcsFile->addFixableError($error, $trailingContent, 'NoCommaAfterLast'); - if ($fix === true) { - $phpcsFile->fixer->addContent($trailingContent, ','); + $fix = $phpcsFile->addFixableError( $error, $trailingContent, 'NoCommaAfterLast' ); + if ( true === $fix ) { + $phpcsFile->fixer->addContent( $trailingContent, ',' ); } } else { - $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes'); + $phpcsFile->recordMetric( $stackPtr, 'Array end comma', 'yes' ); } $lastValueLine = false; - foreach ($indices as $value) { - if (empty($value['value']) === true) { + foreach ( $indices as $value ) { + if ( empty( $value['value'] ) ) { // Array was malformed and we couldn't figure out // the array value correctly, so we have to ignore it. // Other parts of this sniff will correct the error. continue; } - if ($lastValueLine !== false && $tokens[$value['value']]['line'] === $lastValueLine) { + if ( false !== $lastValueLine && $tokens[ $value['value'] ]['line'] === $lastValueLine ) { $error = 'Each value in a multi-line array must be on a new line'; - $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNoNewline'); - if ($fix === true) { - if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) { - $phpcsFile->fixer->replaceToken(($value['value'] - 1), ''); + $fix = $phpcsFile->addFixableError( $error, $value['value'], 'ValueNoNewline' ); + if ( true === $fix ) { + if ( T_WHITESPACE === $tokens[ ( $value['value'] - 1 ) ]['code'] ) { + $phpcsFile->fixer->replaceToken( ( $value['value'] - 1 ), '' ); } - $phpcsFile->fixer->addNewlineBefore($value['value']); + $phpcsFile->fixer->addNewlineBefore( $value['value'] ); } /* - } else if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) { + } elseif ( T_WHITESPACE === $tokens[ ( $value['value'] - 1 ) ]['code'] ) { $expected = $keywordStart; - $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $value['value'], true); - $found = ($tokens[$first]['column'] - 1); - if ($found !== $expected) { + $first = $phpcsFile->findFirstOnLine( T_WHITESPACE, $value['value'], true ); + $found = ($tokens[ $first ]['column'] - 1); + if ( $found !== $expected ) { $error = 'Array value not aligned correctly; expected %s spaces but found %s'; $data = array( $expected, $found, ); - $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNotAligned', $data); - if ($fix === true) { - if ($found === 0) { - $phpcsFile->fixer->addContent(($value['value'] - 1), str_repeat(' ', $expected)); + $fix = $phpcsFile->addFixableError( $error, $value['value'], 'ValueNotAligned', $data ); + if ( true === $fix ) { + if ( 0 === $found ) { + $phpcsFile->fixer->addContent( ( $value['value'] - 1 ), str_repeat(' ', $expected ) ); } else { - $phpcsFile->fixer->replaceToken(($value['value'] - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $value['value'] - 1 ), str_repeat(' ', $expected ) ); } } } */ - }//end if + } // end if - $lastValueLine = $tokens[$value['value']]['line']; - }//end foreach - }//end if + $lastValueLine = $tokens[ $value['value'] ]['line']; + } // end foreach + } // end if /* Below the actual indentation of the array is checked. @@ -471,21 +466,21 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt to be moved back one space however, then both errors would be fixed. */ - $numValues = count($indices); + $numValues = count( $indices ); - $indicesStart = ($keywordStart + 1); - $arrowStart = ($indicesStart + $maxLength + 1); - $valueStart = ($arrowStart + 3); - $indexLine = $tokens[$stackPtr]['line']; + $indicesStart = ( $keywordStart + 1 ); + $arrowStart = ( $indicesStart + $maxLength + 1 ); + $valueStart = ( $arrowStart + 3 ); + $indexLine = $tokens[ $stackPtr ]['line']; $lastIndexLine = null; - foreach ($indices as $index) { - if (isset($index['index']) === false) { + foreach ( $indices as $index ) { + if ( ! isset( $index['index'] ) ) { // Array value only. - if ($tokens[$index['value']]['line'] === $tokens[$stackPtr]['line'] && $numValues > 1) { + if ( $tokens[ $index['value'] ]['line'] === $tokens[ $stackPtr ]['line'] && $numValues > 1 ) { $error = 'The first value in a multi-value array must be on a new line'; - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FirstValueNoNewline'); - if ($fix === true) { - $phpcsFile->fixer->addNewlineBefore($index['value']); + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'FirstValueNoNewline' ); + if ( true === $fix ) { + $phpcsFile->fixer->addNewlineBefore( $index['value'] ); } } @@ -493,79 +488,79 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt } $lastIndexLine = $indexLine; - $indexLine = $tokens[$index['index']]['line']; + $indexLine = $tokens[ $index['index'] ]['line']; - if ($indexLine === $tokens[$stackPtr]['line']) { + if ( $indexLine === $tokens[ $stackPtr ]['line'] ) { $error = 'The first index in a multi-value array must be on a new line'; - $fix = $phpcsFile->addFixableError($error, $index['index'], 'FirstIndexNoNewline'); - if ($fix === true) { - $phpcsFile->fixer->addNewlineBefore($index['index']); + $fix = $phpcsFile->addFixableError( $error, $index['index'], 'FirstIndexNoNewline' ); + if ( true === $fix ) { + $phpcsFile->fixer->addNewlineBefore( $index['index'] ); } continue; } - if ($indexLine === $lastIndexLine) { + if ( $indexLine === $lastIndexLine ) { $error = 'Each index in a multi-line array must be on a new line'; - $fix = $phpcsFile->addFixableError($error, $index['index'], 'IndexNoNewline'); - if ($fix === true) { - if ($tokens[($index['index'] - 1)]['code'] === T_WHITESPACE) { - $phpcsFile->fixer->replaceToken(($index['index'] - 1), ''); + $fix = $phpcsFile->addFixableError( $error, $index['index'], 'IndexNoNewline' ); + if ( true === $fix ) { + if ( T_WHITESPACE === $tokens[ ( $index['index'] - 1 ) ]['code'] ) { + $phpcsFile->fixer->replaceToken( ( $index['index'] - 1 ), '' ); } - $phpcsFile->fixer->addNewlineBefore($index['index']); + $phpcsFile->fixer->addNewlineBefore( $index['index'] ); } continue; } /* - if ($tokens[$index['index']]['column'] !== $indicesStart) { - $expected = ($indicesStart - 1); - $found = ($tokens[$index['index']]['column'] - 1); + if ( $tokens[ $index['index'] ]['column'] !== $indicesStart ) { + $expected = ( $indicesStart - 1 ); + $found = ( $tokens[ $index['index'] ]['column'] - 1 ); $error = 'Array key not aligned correctly; expected %s spaces but found %s'; $data = array( $expected, $found, ); - $fix = $phpcsFile->addFixableError($error, $index['index'], 'KeyNotAligned', $data); - if ($fix === true) { - if ($found === 0) { - $phpcsFile->fixer->addContent(($index['index'] - 1), str_repeat(' ', $expected)); + $fix = $phpcsFile->addFixableError( $error, $index['index'], 'KeyNotAligned', $data ); + if ( true === $fix ) { + if ( 0 === $found ) { + $phpcsFile->fixer->addContent( ( $index['index'] - 1 ), str_repeat(' ', $expected ) ); } else { - $phpcsFile->fixer->replaceToken(($index['index'] - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $index['index'] - 1 ), str_repeat(' ', $expected ) ); } } continue; } - if ($tokens[$index['arrow']]['column'] !== $arrowStart) { - $expected = ($arrowStart - (strlen($index['index_content']) + $tokens[$index['index']]['column'])); - $found = ($tokens[$index['arrow']]['column'] - (strlen($index['index_content']) + $tokens[$index['index']]['column'])); + if ( $tokens[ $index['arrow'] ]['column'] !== $arrowStart ) { + $expected = ( $arrowStart - ( strlen( $index['index_content'] ) + $tokens[ $index['index'] ]['column'] ) ); + $found = ( $tokens[ $index['arrow'] ]['column'] - ( strlen( $index['index_content'] ) + $tokens[ $index['index'] ]['column'] ) ); $error = 'Array double arrow not aligned correctly; expected %s space(s) but found %s'; $data = array( $expected, $found, ); - $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'DoubleArrowNotAligned', $data); - if ($fix === true) { - if ($found === 0) { - $phpcsFile->fixer->addContent(($index['arrow'] - 1), str_repeat(' ', $expected)); + $fix = $phpcsFile->addFixableError( $error, $index['arrow'], 'DoubleArrowNotAligned', $data ); + if ( true === $fix ) { + if ( 0 === $found ) { + $phpcsFile->fixer->addContent( ( $index['arrow'] - 1 ), str_repeat(' ', $expected ) ); } else { - $phpcsFile->fixer->replaceToken(($index['arrow'] - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $index['arrow'] - 1 ), str_repeat(' ', $expected ) ); } } continue; } - if ($tokens[$index['value']]['column'] !== $valueStart) { - $expected = ($valueStart - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); - $found = ($tokens[$index['value']]['column'] - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); - if ($found < 0) { + if ( $tokens[ $index['value'] ]['column'] !== $valueStart ) { + $expected = ( $valueStart - ( $tokens[ $index['arrow'] ]['length'] + $tokens[ $index['arrow'] ]['column'] ) ); + $found = ( $tokens[ $index['value'] ]['column'] - ( $tokens[ $index['arrow'] ]['length'] + $tokens[ $index['arrow'] ]['column'] ) ); + if ( $found < 0 ) { $found = 'newline'; } @@ -575,95 +570,95 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt $found, ); - $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'ValueNotAligned', $data); - if ($fix === true) { - if ($found === 'newline') { - $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($index['value'] - 1), null, true); + $fix = $phpcsFile->addFixableError( $error, $index['arrow'], 'ValueNotAligned', $data ); + if ( true === $fix ) { + if ( 'newline' === $found ) { + $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $index['value'] - 1 ), null, true ); $phpcsFile->fixer->beginChangeset(); - for ($i = ($prev + 1); $i < $index['value']; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); + for ( $i = ( $prev + 1 ); $i < $index['value']; $i++ ) { + $phpcsFile->fixer->replaceToken( $i, '' ); } - $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); $phpcsFile->fixer->endChangeset(); - } else if ($found === 0) { - $phpcsFile->fixer->addContent(($index['value'] - 1), str_repeat(' ', $expected)); + } elseif ( 0 === $found ) { + $phpcsFile->fixer->addContent( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); } else { - $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->replaceToken( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); } } - }//end if + } // end if */ // Check each line ends in a comma. - $valueLine = $tokens[$index['value']]['line']; + $valueLine = $tokens[ $index['value'] ]['line']; $nextComma = false; - for ($i = $index['value']; $i < $arrayEnd; $i++) { + for ( $i = $index['value']; $i < $arrayEnd; $i++ ) { // Skip bracketed statements, like function calls. - if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) { - $i = $tokens[$i]['parenthesis_closer']; - $valueLine = $tokens[$i]['line']; + if ( T_OPEN_PARENTHESIS === $tokens[ $i ]['code'] ) { + $i = $tokens[ $i ]['parenthesis_closer']; + $valueLine = $tokens[ $i ]['line']; continue; } - if ($tokens[$i]['code'] === T_ARRAY) { - $i = $tokens[$tokens[$i]['parenthesis_opener']]['parenthesis_closer']; - $valueLine = $tokens[$i]['line']; + if ( T_ARRAY === $tokens[ $i ]['code'] ) { + $i = $tokens[ $tokens[ $i ]['parenthesis_opener'] ]['parenthesis_closer']; + $valueLine = $tokens[ $i ]['line']; continue; } - if ($tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { - $i = $tokens[$i]['bracket_closer']; - $valueLine = $tokens[$i]['line']; + if ( T_OPEN_SHORT_ARRAY === $tokens[ $i ]['code'] ) { + $i = $tokens[ $i ]['bracket_closer']; + $valueLine = $tokens[ $i ]['line']; continue; } - if ($tokens[$i]['code'] === T_CLOSURE) { - $i = $tokens[$i]['scope_closer']; - $valueLine = $tokens[$i]['line']; + if ( T_CLOSURE === $tokens[ $i ]['code'] ) { + $i = $tokens[ $i ]['scope_closer']; + $valueLine = $tokens[ $i ]['line']; continue; } - if ($tokens[$i]['code'] === T_COMMA) { + if ( T_COMMA === $tokens[ $i ]['code'] ) { $nextComma = $i; break; } - }//end for + } // end for - //if ($nextComma === false || ($tokens[$nextComma]['line'] !== $valueLine)) { - if ( $nextComma === false ) { + //if ( $nextComma === false || ( $tokens[ $nextComma ]['line'] !== $valueLine ) ) { + if ( false === $nextComma ) { $error = 'Each line in an array declaration must end in a comma'; - $fix = $phpcsFile->addFixableError($error, $index['value'], 'NoComma'); + $fix = $phpcsFile->addFixableError( $error, $index['value'], 'NoComma' ); - if ($fix === true) { + if ( true === $fix ) { // Find the end of the line and put a comma there. - for ($i = ($index['value'] + 1); $i < $phpcsFile->numTokens; $i++) { - if ($tokens[$i]['line'] > $valueLine) { + for ( $i = ( $index['value'] + 1 ); $i < $phpcsFile->numTokens; $i++ ) { + if ( $tokens[ $i ]['line'] > $valueLine ) { break; } } - $phpcsFile->fixer->addContentBefore(($i - 1), ','); + $phpcsFile->fixer->addContentBefore( ( $i - 1 ), ',' ); } } // Check that there is no space before the comma. - if ($nextComma !== false && $tokens[($nextComma - 1)]['code'] === T_WHITESPACE) { - $content = $tokens[($nextComma - 2)]['content']; - $spaceLength = $tokens[($nextComma - 1)]['length']; + if ( false !== $nextComma && T_WHITESPACE === $tokens[ ( $nextComma - 1 ) ]['code'] ) { + $content = $tokens[ ( $nextComma - 2 ) ]['content']; + $spaceLength = $tokens[ ( $nextComma - 1 ) ]['length']; $error = 'Expected 0 spaces between "%s" and comma; %s found'; $data = array( $content, $spaceLength, ); - $fix = $phpcsFile->addFixableError($error, $nextComma, 'SpaceBeforeComma', $data); - if ($fix === true) { - $phpcsFile->fixer->replaceToken(($nextComma - 1), ''); + $fix = $phpcsFile->addFixableError( $error, $nextComma, 'SpaceBeforeComma', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->replaceToken( ( $nextComma - 1 ), '' ); } } - }//end foreach + } // end foreach - }//end processMultiLineArray() + } // end processMultiLineArray() -}//end class +} // end class diff --git a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php index 0eb3fc97e9..bb7742a87c 100644 --- a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php @@ -1,27 +1,26 @@ */ -class WordPress_Sniffs_Arrays_ArrayKeySpacingRestrictionsSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_Arrays_ArrayKeySpacingRestrictionsSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( - T_OPEN_SQUARE_BRACKET, - ); + T_OPEN_SQUARE_BRACKET, + ); - }//end register() + } // end register() /** * Processes this test, when one of its tokens is encountered. @@ -32,8 +31,7 @@ public function register() * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $token = $tokens[ $stackPtr ]; @@ -44,40 +42,39 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $need_spaces = $phpcsFile->findNext( array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_WHITESPACE, T_MINUS ), - $stackPtr + 1, + ( $stackPtr + 1 ), $token['bracket_closer'], true ); - $spaced1 = ( T_WHITESPACE === $tokens[ $stackPtr + 1 ]['code'] ); - $spaced2 = ( T_WHITESPACE === $tokens[ $token['bracket_closer'] - 1 ]['code'] ); + $spaced1 = ( T_WHITESPACE === $tokens[ ( $stackPtr + 1 ) ]['code'] ); + $spaced2 = ( T_WHITESPACE === $tokens[ ( $token['bracket_closer'] - 1 ) ]['code'] ); - // It should have spaces only if it only has strings or numbers as the key + // It should have spaces only if it only has strings or numbers as the key. if ( $need_spaces && ! ( $spaced1 && $spaced2 ) ) { $error = 'Array keys must be surrounded by spaces unless they contain a string or an integer.'; - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpacesAroundArrayKeys' ); - if ( $fix ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpacesAroundArrayKeys' ); + if ( true === $fix ) { if ( ! $spaced1 ) { - $phpcsFile->fixer->addContentBefore( $stackPtr + 1, ' ' ); + $phpcsFile->fixer->addContentBefore( ( $stackPtr + 1 ), ' ' ); } if ( ! $spaced2 ) { $phpcsFile->fixer->addContentBefore( $token['bracket_closer'], ' ' ); } } - } - elseif( ! $need_spaces && ( $spaced1 || $spaced2 ) ) { + } elseif ( ! $need_spaces && ( $spaced1 || $spaced2 ) ) { $error = 'Array keys must NOT be surrounded by spaces if they only contain a string or an integer.'; - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpacesAroundArrayKeys' ); - if ( $fix ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpacesAroundArrayKeys' ); + if ( true === $fix ) { if ( $spaced1 ) { - $phpcsFile->fixer->replaceToken( $stackPtr + 1, '' ); + $phpcsFile->fixer->replaceToken( ( $stackPtr + 1 ), '' ); } if ( $spaced2 ) { - $phpcsFile->fixer->replaceToken( $token['bracket_closer'] - 1, '' ); + $phpcsFile->fixer->replaceToken( ( $token['bracket_closer'] - 1 ), '' ); } } } - }//end process() + } // end process() -}//end class +} // end class diff --git a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php index 5a624a8a33..39c9f580cd 100644 --- a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php +++ b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php @@ -1,5 +1,4 @@ init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); + $tokens = $phpcsFile->getTokens(); $instance = $tokens[ $stackPtr ]; $superglobals = array_merge( @@ -104,7 +103,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { , $this->warnForSuperGlobals ); - if ( ! in_array( $instance['content'], $superglobals ) ) { + if ( ! in_array( $instance['content'], $superglobals, true ) ) { return; } @@ -125,7 +124,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // If we're still here, no nonce-verification function was found. - $severity = ( in_array( $instance['content'], $this->errorForSuperGlobals ) ) ? 0 : 'warning'; + $severity = ( in_array( $instance['content'], $this->errorForSuperGlobals, true ) ) ? 0 : 'warning'; $phpcsFile->addError( 'Processing form data without nonce verification.' diff --git a/WordPress/Sniffs/Classes/ValidClassNameSniff.php b/WordPress/Sniffs/Classes/ValidClassNameSniff.php index ffa9a79fff..35e513d8aa 100644 --- a/WordPress/Sniffs/Classes/ValidClassNameSniff.php +++ b/WordPress/Sniffs/Classes/ValidClassNameSniff.php @@ -28,65 +28,57 @@ * @version Release: 1.2.0RC1 * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Sniffs_Classes_ValidClassNameSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_Classes_ValidClassNameSniff implements PHP_CodeSniffer_Sniff { + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_CLASS, + T_INTERFACE, + ); - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array( - T_CLASS, - T_INTERFACE, - ); + } // end register() - }//end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The current file being processed. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + if ( ! isset( $tokens[ $stackPtr ]['scope_opener'] ) ) { + $error = 'Possible parse error: '; + $error .= $tokens[ $stackPtr ]['content']; + $error .= ' missing opening or closing brace'; + $phpcsFile->addWarning( $error, $stackPtr, 'MissingBrace' ); + return; + } - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The current file being processed. - * @param int $stackPtr The position of the current token in the - * stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); + // Determine the name of the class or interface. Note that we cannot + // simply look for the first T_STRING because a class name + // starting with the number will be multiple tokens. + $opener = $tokens[ $stackPtr ]['scope_opener']; + $nameStart = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), $opener, true ); + $nameEnd = $phpcsFile->findNext( T_WHITESPACE, $nameStart, $opener ); + $name = trim( $phpcsFile->getTokensAsString( $nameStart, ( $nameEnd - $nameStart ) ) ); - if (isset($tokens[$stackPtr]['scope_opener']) === false) { - $error = 'Possible parse error: '; - $error .= $tokens[$stackPtr]['content']; - $error .= ' missing opening or closing brace'; - $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace'); - return; - } + // Check for camel caps format. + $valid = PHP_CodeSniffer::isCamelCaps( str_replace( '_', '', $name ), true, true, false ); + if ( false === $valid ) { + $type = ucfirst( $tokens[ $stackPtr ]['content'] ); + $error = "$type name \"$name\" is not in camel caps format"; + $phpcsFile->addError( $error, $stackPtr, 'NotCamelCaps' ); + } - // Determine the name of the class or interface. Note that we cannot - // simply look for the first T_STRING because a class name - // starting with the number will be multiple tokens. - $opener = $tokens[$stackPtr]['scope_opener']; - $nameStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $opener, true); - $nameEnd = $phpcsFile->findNext(T_WHITESPACE, $nameStart, $opener); - $name = trim($phpcsFile->getTokensAsString($nameStart, ($nameEnd - $nameStart))); + } // end process() - // Check for camel caps format. - $valid = PHP_CodeSniffer::isCamelCaps(str_replace('_', '', $name), true, true, false); - if ($valid === false) { - $type = ucfirst($tokens[$stackPtr]['content']); - $error = "$type name \"$name\" is not in camel caps format"; - $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps'); - } - - }//end process() - - -}//end class - -?> +} // end class diff --git a/WordPress/Sniffs/Files/FileNameSniff.php b/WordPress/Sniffs/Files/FileNameSniff.php index 5e9ea4bf8d..5a2b3c6915 100644 --- a/WordPress/Sniffs/Files/FileNameSniff.php +++ b/WordPress/Sniffs/Files/FileNameSniff.php @@ -1,7 +1,6 @@ getFileName()); - - if (strpos($fileName, '_') !== false) { - $expected = str_replace('_', '-', $fileName); - $error = 'Filename "'.$fileName.'" with underscores found; use '.$expected.' instead'; - $phpcsFile->addError($error, $stackPtr, 'UnderscoresNotAllowed'); - } - - return $phpcsFile->numTokens + 1; - - }//end process() - - -}//end class - -?> +class WordPress_Sniffs_Files_FileNameSniff implements PHP_CodeSniffer_Sniff { + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( T_OPEN_TAG ); + + } // end register() + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return int + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + + $fileName = basename( $phpcsFile->getFileName() ); + + if ( false !== strpos( $fileName, '_' ) ) { + $expected = str_replace( '_', '-', $fileName ); + $error = 'Filename "' . $fileName . '" with underscores found; use ' . $expected . ' instead'; + $phpcsFile->addError( $error, $stackPtr, 'UnderscoresNotAllowed' ); + } + + return ( $phpcsFile->numTokens + 1 ); + + } // end process() +} // end class diff --git a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php index 6e2d7df1f7..420ed5da2c 100644 --- a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php +++ b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php @@ -1,20 +1,19 @@ */ -class WordPress_Sniffs_Functions_FunctionRestrictionsSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_Functions_FunctionRestrictionsSniff implements PHP_CodeSniffer_Sniff { /** - * Exclude groups + * Exclude groups. * * Example: 'switch_to_blog,user_meta' - * - * @var string Comma-delimited group list + * + * @var string Comma-delimited group list. */ public $exclude = ''; @@ -23,26 +22,25 @@ class WordPress_Sniffs_Functions_FunctionRestrictionsSniff implements PHP_CodeSn * * @return array */ - public function register() - { + public function register() { return array( - T_STRING, - T_EVAL, - ); + T_STRING, + T_EVAL, + ); - }//end register() + } // end register() /** - * Groups of functions to restrict + * Groups of functions to restrict. * * Example: groups => array( * 'lambda' => array( - * 'type' => 'error' | 'warning', - * 'message' => 'Use anonymous functions instead please!', + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', * 'functions' => array( 'eval', 'create_function' ), * ) * ) - * + * * @return array */ public function getGroups() { @@ -59,29 +57,27 @@ public function getGroups() { * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; - $token = $tokens[$stackPtr]; - - // exclude function definitions, class methods, and namespaced calls + // Exclude function definitions, class methods, and namespaced calls. if ( - $token['code'] == T_STRING + T_STRING === $token['code'] && - ( $prev = $phpcsFile->findPrevious( T_WHITESPACE, $stackPtr - 1, null, true ) ) + ( $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true ) ) && ( - // Skip sniffing if calling a method, or on function definitions - in_array( $tokens[$prev]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ) ) + // Skip sniffing if calling a method, or on function definitions. + in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) || ( - // Skip namespaced functions, ie: \foo\bar() not \bar() - $tokens[$prev]['code'] == T_NS_SEPARATOR + // Skip namespaced functions, ie: \foo\bar() not \bar(). + T_NS_SEPARATOR === $tokens[ $prev ]['code'] && - ( $pprev = $phpcsFile->findPrevious( T_WHITESPACE, $prev - 1, null, true ) ) + ( $pprev = $phpcsFile->findPrevious( T_WHITESPACE, ( $prev - 1 ), null, true ) ) && - $tokens[$pprev]['code'] == T_STRING + T_STRING === $tokens[ $pprev ]['code'] ) ) ) { @@ -93,12 +89,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $groups = $this->getGroups(); if ( empty( $groups ) ) { - return count( $tokens ) + 1; + return ( count( $tokens ) + 1 ); } foreach ( $groups as $groupName => $group ) { - - if ( in_array( $groupName, $exclude ) ) { + + if ( in_array( $groupName, $exclude, true ) ) { continue; } @@ -109,7 +105,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) continue; } - if ( $group['type'] == 'warning' ) { + if ( 'warning' === $group['type'] ) { $addWhat = array( $phpcsFile, 'addWarning' ); } else { $addWhat = array( $phpcsFile, 'addError' ); @@ -117,15 +113,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) call_user_func( $addWhat, - $group['message'], - $stackPtr, - $groupName, + $group['message'], + $stackPtr, + $groupName, array( $token['content'] ) - ); + ); } - }//end process() - - -}//end class + } // end process() +} // end class diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index b1857277a3..399cb35fc0 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -1,6 +1,6 @@ */ -class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff -{ - - private $_magicMethods = array( - 'construct', - 'destruct', - 'call', - 'callStatic', - 'get', - 'set', - 'isset', - 'unset', - 'sleep', - 'wakeup', - 'toString', - 'set_state', - 'clone', - 'invoke', - 'debugInfo' - ); - - - /** - * Processes the tokens outside the scope. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being processed. - * @param int $stackPtr The position where this token was - * found. - * - * @return void - */ - protected function processTokenOutsideScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $functionName = $phpcsFile->getDeclarationName($stackPtr); - - if (strtolower($functionName) !== $functionName) { - $suggested = preg_replace('/([A-Z])/', '_$1', $functionName); - $suggested = strtolower($suggested); - $suggested = str_replace('__', '_', $suggested); - - $error = "Function name \"$functionName\" is in camel caps format, try '".$suggested."'"; - $phpcsFile->addError($error, $stackPtr, 'FunctionNameInvalid'); - } - - }//end processTokenOutsideScope() - - - /** - * Processes the tokens within the scope. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being processed. - * @param int $stackPtr The position where this token was - * found. - * @param int $currScope The position of the current scope. - * - * @return void - */ - protected function processTokenWithinScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $currScope) - { - $className = $phpcsFile->getDeclarationName($currScope); - $methodName = $phpcsFile->getDeclarationName($stackPtr); - - // Is this a magic method. IE. is prefixed with "__". - if (preg_match('|^__|', $methodName) !== 0) { - $magicPart = substr($methodName, 2); - if (in_array($magicPart, $this->_magicMethods) === false) { - $error = "Method name \"$className::$methodName\" is invalid; only PHP magic methods should be prefixed with a double underscore"; - $phpcsFile->addError($error, $stackPtr, 'MethodDoubleUnderscore'); - } - - return; - } - - // PHP4 constructors are allowed to break our rules. - if ($methodName === $className) { - return; - } - - // PHP4 destructors are allowed to break our rules. - if ($methodName === '_'.$className) { - return; - } - - // If this is a child class, it may have to use camelCase. - if ( $phpcsFile->findExtendedClassName( $currScope ) || $this->findImplementedInterfaceName( $currScope, $phpcsFile ) ) { - return; - } - - $methodProps = $phpcsFile->getMethodProperties($stackPtr); - $scope = $methodProps['scope']; - $scopeSpecified = $methodProps['scope_specified']; - - if ($methodProps['scope'] === 'private') - $isPublic = false; - else - $isPublic = true; - - // If the scope was specified on the method, then the method must be - // camel caps and an underscore should be checked for. If it wasn't - // specified, treat it like a public method and remove the underscore - // prefix if there is one because we can't determine if it is private or - // public. - $testMethodName = $methodName; - if ($scopeSpecified === false && $methodName{0} === '_') { - $testMethodName = substr($methodName, 1); - } - - if (strtolower($testMethodName) !== $testMethodName) { - $suggested = preg_replace('/([A-Z])/', '_$1', $methodName); - $suggested = strtolower($suggested); - $suggested = str_replace('__', '_', $suggested); - - $error = "Function name \"$methodName\" is in camel caps format, try '".$suggested."'"; - $phpcsFile->addError($error, $stackPtr, 'FunctionNameInvalid'); - } - - }//end processTokenWithinScope() +class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff { + + private $_magicMethods = array( + 'construct', + 'destruct', + 'call', + 'callStatic', + 'get', + 'set', + 'isset', + 'unset', + 'sleep', + 'wakeup', + 'toString', + 'set_state', + 'clone', + 'invoke', + 'debugInfo', + ); + + + /** + * Processes the tokens outside the scope. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $functionName = $phpcsFile->getDeclarationName( $stackPtr ); + + if ( strtolower( $functionName ) !== $functionName ) { + $suggested = preg_replace( '/([A-Z])/', '_$1', $functionName ); + $suggested = strtolower( $suggested ); + $suggested = str_replace( '__', '_', $suggested ); + + $error = "Function name \"$functionName\" is in camel caps format, try '{$suggested}'"; + $phpcsFile->addError( $error, $stackPtr, 'FunctionNameInvalid' ); + } + + } // end processTokenOutsideScope() + + + /** + * Processes the tokens within the scope. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * @param int $currScope The position of the current scope. + * + * @return void + */ + protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $currScope ) { + $className = $phpcsFile->getDeclarationName( $currScope ); + $methodName = $phpcsFile->getDeclarationName( $stackPtr ); + + // Is this a magic method. IE. is prefixed with "__". + if ( 0 === strpos( $methodName, '__' ) ) { + $magicPart = substr( $methodName, 2 ); + if ( false === in_array( $magicPart, $this->_magicMethods, true ) ) { + $error = "Method name \"$className::$methodName\" is invalid; only PHP magic methods should be prefixed with a double underscore"; + $phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore' ); + } + + return; + } + + // PHP4 constructors are allowed to break our rules. + if ( $methodName === $className ) { + return; + } + + // PHP4 destructors are allowed to break our rules. + if ( '_' . $className === $methodName ) { + return; + } + + // If this is a child class, it may have to use camelCase. + if ( $phpcsFile->findExtendedClassName( $currScope ) || $this->findImplementedInterfaceName( $currScope, $phpcsFile ) ) { + return; + } + + $methodProps = $phpcsFile->getMethodProperties( $stackPtr ); + $scope = $methodProps['scope']; + $scopeSpecified = $methodProps['scope_specified']; + + if ( 'private' === $methodProps['scope'] ) { + $isPublic = false; + } else { + $isPublic = true; + } + + // If the scope was specified on the method, then the method must be + // camel caps and an underscore should be checked for. If it wasn't + // specified, treat it like a public method and remove the underscore + // prefix if there is one because we can't determine if it is private or + // public. + $testMethodName = $methodName; + if ( false === $scopeSpecified && '_' === $methodName{0} ) { + $testMethodName = substr( $methodName, 1 ); + } + + if ( strtolower( $testMethodName ) !== $testMethodName ) { + $suggested = preg_replace( '/([A-Z])/', '_$1', $methodName ); + $suggested = strtolower( $suggested ); + $suggested = str_replace( '__', '_', $suggested ); + + $error = "Function name \"$methodName\" is in camel caps format, try '{$suggested}'"; + $phpcsFile->addError( $error, $stackPtr, 'FunctionNameInvalid' ); + } + + } // end processTokenWithinScope() /** * Returns the name of the class that the specified class implements. * * Returns FALSE on error or if there is no implemented class name. * - * @param int $stackPtr The stack position of the class. + * @param int $stackPtr The stack position of the class. * @param PHP_CodeSniffer_File $phpcsFile The stack position of the class. * * @see PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff::findExtendedClassName() @@ -152,17 +150,17 @@ public function findImplementedInterfaceName( $stackPtr, $phpcsFile ) { $tokens = $phpcsFile->getTokens(); // Check for the existence of the token. - if ( isset( $tokens[ $stackPtr ] ) === false ) { + if ( ! isset( $tokens[ $stackPtr ] ) ) { return false; } - if ( $tokens[ $stackPtr ]['code'] !== T_CLASS ) { + if ( T_CLASS !== $tokens[ $stackPtr ]['code'] ) { return false; } - if ( isset( $tokens[ $stackPtr ]['scope_closer'] ) === false ) { + if ( ! isset( $tokens[ $stackPtr ]['scope_closer'] ) ) { return false; } $classOpenerIndex = $tokens[ $stackPtr ]['scope_opener']; - $extendsIndex = $phpcsFile->findNext( T_IMPLEMENTS, $stackPtr, $classOpenerIndex ); + $extendsIndex = $phpcsFile->findNext( T_IMPLEMENTS, $stackPtr, $classOpenerIndex ); if ( false === $extendsIndex ) { return false; } @@ -171,13 +169,13 @@ public function findImplementedInterfaceName( $stackPtr, $phpcsFile ) { T_STRING, T_WHITESPACE, ); - $end = $phpcsFile->findNext( $find, ( $extendsIndex + 1 ), $classOpenerIndex + 1, true ); + $end = $phpcsFile->findNext( $find, ( $extendsIndex + 1 ), ( $classOpenerIndex + 1 ), true ); $name = $phpcsFile->getTokensAsString( ( $extendsIndex + 1 ), ( $end - $extendsIndex - 1 ) ); $name = trim( $name ); - if ( $name === '' ) { + if ( '' === $name ) { return false; } return $name; - }//end findExtendedClassName() + } // end findExtendedClassName() -}//end class +} // end class diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 1f8eaf1b28..7b3315c394 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -106,20 +106,20 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr self::$addedCustomVariables = true; } - $tokens = $phpcs_file->getTokens(); + $tokens = $phpcs_file->getTokens(); $var_name = ltrim( $tokens[ $stack_ptr ]['content'], '$' ); // If it's a php reserved var, then its ok. - if ( in_array( $var_name, $this->php_reserved_vars ) === true ) { + if ( in_array( $var_name, $this->php_reserved_vars, true ) ) { return; } $obj_operator = $phpcs_file->findNext( array( T_WHITESPACE ), ( $stack_ptr + 1 ), null, true ); if ( T_OBJECT_OPERATOR === $tokens[ $obj_operator ]['code'] ) { // Check to see if we are using a variable from an object. - $var = $phpcs_file->findNext( array( T_WHITESPACE ), ($obj_operator + 1), null, true ); + $var = $phpcs_file->findNext( array( T_WHITESPACE ), ( $obj_operator + 1 ), null, true ); if ( T_STRING === $tokens[ $var ]['code'] ) { - $bracket = $phpcs_file->findNext( array( T_WHITESPACE ), ($var + 1), null, true ); + $bracket = $phpcs_file->findNext( array( T_WHITESPACE ), ( $var + 1 ), null, true ); if ( T_OPEN_PARENTHESIS !== $tokens[ $bracket ]['code'] ) { $obj_var_name = $tokens[ $var ]['content']; @@ -127,7 +127,7 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr // private, so we have to ignore a leading underscore if there is // one and just check the main part of the variable name. $original_var_name = $obj_var_name; - if ( substr( $obj_var_name, 0, 1 ) === '_' ) { + if ( '_' === substr( $obj_var_name, 0, 1 ) ) { $obj_var_name = substr( $obj_var_name, 1 ); } @@ -136,9 +136,9 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr $data = array( $original_var_name ); $phpcs_file->addError( $error, $var, 'NotSnakeCaseMemberVar', $data ); } - }//end if - }//end if - }//end if + } // end if + } // end if + } // end if $in_class = false; $obj_operator = $phpcs_file->findPrevious( array( T_WHITESPACE ), ( $stack_ptr - 1 ), null, true ); @@ -152,7 +152,7 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr // so we have to ignore a leading underscore if there is one and just // check the main part of the variable name. $original_var_name = $var_name; - if ( substr( $var_name, 0, 1 ) === '_' && true === $in_class ) { + if ( '_' === substr( $var_name, 0, 1 ) && true === $in_class ) { $var_name = substr( $var_name, 1 ); } @@ -188,7 +188,7 @@ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_pt $var_name = ltrim( $tokens[ $stack_ptr ]['content'], '$' ); $member_props = $phpcs_file->getMemberProperties( $stack_ptr ); - if ( empty( $member_props ) === true ) { + if ( empty( $member_props ) ) { // Couldn't get any info about this variable, which // generally means it is invalid or possibly has a parse // error. Any errors will be reported by the core, so @@ -197,7 +197,7 @@ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_pt } $error_data = array( $var_name ); - if ( ! in_array( $var_name, $this->whitelisted_mixed_case_member_var_names, true ) && self::isSnakeCase( $var_name ) === false ) { + if ( ! in_array( $var_name, $this->whitelisted_mixed_case_member_var_names, true ) && false === self::isSnakeCase( $var_name ) ) { $error = 'Member variable "%s" is not in valid snake_case format.'; $phpcs_file->addError( $error, $stack_ptr, 'MemberNotSnakeCase', $error_data ); } @@ -210,21 +210,21 @@ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_pt * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. * @param int $stack_ptr The position of the double quoted - * string. + * string. * * @return void */ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $tokens = $phpcs_file->getTokens(); - if ( preg_match_all( '|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[ $stack_ptr ]['content'], $matches ) !== 0 ) { + if ( preg_match_all( '|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[ $stack_ptr ]['content'], $matches ) > 0 ) { foreach ( $matches[1] as $var_name ) { // If it's a php reserved var, then its ok. - if ( in_array( $var_name, $this->php_reserved_vars ) === true ) { + if ( in_array( $var_name, $this->php_reserved_vars, true ) ) { continue; } - if ( self::isSnakeCase( $var_name ) === false ) { + if ( false === self::isSnakeCase( $var_name ) ) { $error = 'Variable "%s" is not in valid snake_case format'; $data = array( $var_name ); $phpcs_file->addError( $error, $stack_ptr, 'StringNotSnakeCase', $data ); @@ -237,10 +237,10 @@ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $s /** * Return whether the variable is in snake_case. * - * @param string $var_name + * @param string $var_name Variable name. * @return bool */ static function isSnakeCase( $var_name ) { return (bool) preg_match( '/^[a-z0-9_]+$/', $var_name ); } -}//end class +} // end class diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index 05d32eeb69..898d8b5dc8 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -9,8 +9,8 @@ * @author John Godley */ -if (class_exists('Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true) === false) { - throw new PHP_CodeSniffer_Exception('Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found'); +if ( false === class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); } /** @@ -24,29 +24,32 @@ */ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { - /** - * A list of forbidden functions with their alternatives. - * - * The value is NULL if no alternative exists. IE, the - * function should just not be used. - * - * @var array(string => string|null) - */ - public $forbiddenFunctions = array( - // Deprecated + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. I.e. the + * function should just not be used. + * + * @var array(string => string|null) + */ + public $forbiddenFunctions = array( + // Deprecated. 'ereg_replace' => 'preg_replace', 'ereg' => null, 'eregi_replace' => 'preg_replace', 'split' => null, 'spliti' => null, - // Development + + // Development. 'print_r' => null, 'debug_print_backtrace' => null, 'var_dump' => null, 'var_export' => null, - // Discouraged + + // Discouraged. 'json_encode' => 'wp_json_encode', - // WordPress deprecated + + // WordPress deprecated. 'find_base_dir' => 'WP_Filesystem::abspath', 'get_base_dir' => 'WP_Filesystem::abspath', 'dropdown_categories' => 'wp_link_category_checklist', @@ -61,16 +64,17 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ 'get_attachment_icon_src' => 'wp_get_attachment_image_src', 'get_attachment_icon' => 'wp_get_attachment_image', 'get_attachment_innerHTML' => 'wp_get_attachment_image', - // WordPress discouraged + + // WordPress discouraged. 'query_posts' => 'WP_Query', 'wp_reset_query' => 'wp_reset_postdata', ); - /** - * If true, an error will be thrown; otherwise a warning. - * - * @var bool - */ - public $error = false; + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var bool + */ + public $error = false; -}//end class +} // end class diff --git a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php index e7126ec4f5..2fe86fdca1 100644 --- a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php +++ b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php @@ -1,6 +1,6 @@ init( $phpcsFile ); if ( ! $this->has_whitelist_comment( 'loose comparison', $stackPtr ) ) { $tokens = $phpcsFile->getTokens(); - $error = 'Found: ' . $tokens[$stackPtr]['content'] . '. Use strict comparisons (=== or !==).'; + $error = 'Found: ' . $tokens[ $stackPtr ]['content'] . '. Use strict comparisons (=== or !==).'; $phpcsFile->addWarning( $error, $stackPtr, 'LooseComparison' ); } - }//end process() + } // end process() -}//end class +} // end class diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index d14bc307b3..9545c77acf 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -6,7 +6,6 @@ * @category PHP * @package PHP_CodeSniffer */ - class WordPress_Sniffs_PHP_StrictInArraySniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { /** @@ -23,8 +22,9 @@ public function register() { /** * Processes this test, when one of its tokens is encountered. * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token in the stack passed in $tokens. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. * * @return void */ @@ -36,7 +36,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - if ( ! isset( $tokens[ $stackPtr - 1 ] ) ) { + if ( ! isset( $tokens[ ( $stackPtr - 1 ) ] ) ) { return; } @@ -48,7 +48,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Get the closing parenthesis. - $openParenthesis = $phpcsFile->findNext( T_OPEN_PARENTHESIS, $stackPtr + 1 ); + $openParenthesis = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $stackPtr + 1 ) ); if ( false === $openParenthesis ) { return; } @@ -61,7 +61,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Get last token in the function call. $closeParenthesis = $tokens[ $openParenthesis ]['parenthesis_closer']; - $lastToken = $phpcsFile->findPrevious( array( T_WHITESPACE, T_COMMENT ), $closeParenthesis - 1, $openParenthesis + 1, true ); + $lastToken = $phpcsFile->findPrevious( array( T_WHITESPACE, T_COMMENT ), ( $closeParenthesis - 1 ), ( $openParenthesis + 1 ), true ); if ( false === $lastToken ) { $phpcsFile->addError( 'Missing arguments to in_array().', $openParenthesis, 'MissingArguments' ); return; diff --git a/WordPress/Sniffs/PHP/YodaConditionsSniff.php b/WordPress/Sniffs/PHP/YodaConditionsSniff.php index 922761dadb..f53393c8fe 100644 --- a/WordPress/Sniffs/PHP/YodaConditionsSniff.php +++ b/WordPress/Sniffs/PHP/YodaConditionsSniff.php @@ -1,6 +1,6 @@ * @author Marc McIntyre */ -class WordPress_Sniffs_PHP_YodaConditionsSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_PHP_YodaConditionsSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( T_IS_EQUAL, T_IS_NOT_EQUAL, @@ -35,20 +33,19 @@ public function register() T_IS_NOT_IDENTICAL, ); - }//end register() + } // end register() /** * Processes this test, when one of its tokens is encountered. * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token in the - * stack passed in $tokens. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. * * @return void */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $beginners = array_merge( @@ -64,7 +61,7 @@ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) for ( $i = $stackPtr; $i > $beginning; $i-- ) { // Ignore whitespace. - if ( in_array( $tokens[ $i ]['code'], PHP_CodeSniffer_Tokens::$emptyTokens ) ) { + if ( in_array( $tokens[ $i ]['code'], PHP_CodeSniffer_Tokens::$emptyTokens, true ) ) { continue; } @@ -75,7 +72,7 @@ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) } // If this is a function call or something, we are OK. - if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_CLOSE_PARENTHESIS, T_OPEN_PARENTHESIS, T_RETURN ) ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_CLOSE_PARENTHESIS, T_OPEN_PARENTHESIS, T_RETURN ), true ) ) { return; } } @@ -84,17 +81,17 @@ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) return; } - // Check if this is a var to var comparison, e.g.: if ( $var1 == $var2 ) - $next_non_empty = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true ); + // Check if this is a var to var comparison, e.g.: if ( $var1 == $var2 ). + $next_non_empty = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); - if ( in_array( $tokens[ $next_non_empty ]['code'], PHP_CodeSniffer_Tokens::$castTokens ) ) { - $next_non_empty = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, $next_non_empty + 1, null, true ); + if ( in_array( $tokens[ $next_non_empty ]['code'], PHP_CodeSniffer_Tokens::$castTokens, true ) ) { + $next_non_empty = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true ); } - if ( in_array( $tokens[ $next_non_empty ]['code'], array( T_SELF, T_PARENT, T_STATIC ) ) ) { + if ( in_array( $tokens[ $next_non_empty ]['code'], array( T_SELF, T_PARENT, T_STATIC ), true ) ) { $next_non_empty = $phpcsFile->findNext( array_merge( PHP_CodeSniffer_Tokens::$emptyTokens, array( T_DOUBLE_COLON ) ) - , $next_non_empty + 1 + , ( $next_non_empty + 1 ) , null , true ); @@ -106,9 +103,6 @@ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) $phpcsFile->addError( 'Use Yoda Condition checks, you must', $stackPtr, 'NotYoda' ); - }//end process() + } // end process() - -}//end class - -?> +} // end class diff --git a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php index b8f9f48e99..b31e65fa75 100644 --- a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php +++ b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php @@ -1,5 +1,4 @@ */ -class WordPress_Sniffs_VIP_AdminBarRemovalSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_VIP_AdminBarRemovalSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( - T_STRING, - T_CONSTANT_ENCAPSED_STRING, - T_DOUBLE_QUOTED_STRING, - ); + T_STRING, + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + ); - }//end register() + } // end register() /** @@ -35,16 +32,12 @@ public function register() * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); - if ( in_array( trim( $tokens[$stackPtr]['content'], '"\'' ), array( 'show_admin_bar' ) ) ) { - $phpcsFile->addError( 'Removal of admin bar is prohibited.', $stackPtr, 'RemovalDetected'); + if ( in_array( trim( $tokens[ $stackPtr ]['content'], '"\'' ), array( 'show_admin_bar' ), true ) ) { + $phpcsFile->addError( 'Removal of admin bar is prohibited.', $stackPtr, 'RemovalDetected' ); } - }//end process() - - -}//end class + } // end process() -?> +} // end class diff --git a/WordPress/Sniffs/VIP/CronIntervalSniff.php b/WordPress/Sniffs/VIP/CronIntervalSniff.php index 1cde15ce31..5294945a68 100644 --- a/WordPress/Sniffs/VIP/CronIntervalSniff.php +++ b/WordPress/Sniffs/VIP/CronIntervalSniff.php @@ -1,6 +1,6 @@ getTokens(); - $token = $tokens[$stackPtr]; + $token = $tokens[ $stackPtr ]; - if ( 'cron_schedules' != trim( $token['content'], '"\'' ) ) { + if ( 'cron_schedules' !== trim( $token['content'], '"\'' ) ) { return; } - // If within add_filter + // If within add_filter. $functionPtr = $phpcsFile->findPrevious( T_STRING, key( $token['nested_parenthesis'] ) ); - if ( $tokens[$functionPtr]['content'] != 'add_filter' ) { + if ( 'add_filter' !== $tokens[ $functionPtr ]['content'] ) { return; } - // Detect callback function name - $callbackPtr = $phpcsFile->findNext( array( T_COMMA, T_WHITESPACE ), $stackPtr + 1, null, true, null, true ); + // Detect callback function name. + $callbackPtr = $phpcsFile->findNext( array( T_COMMA, T_WHITESPACE ), ( $stackPtr + 1 ), null, true, null, true ); - // If callback is array, get second element - if ( T_ARRAY === $tokens[$callbackPtr]['code'] ) { - $comma = $phpcsFile->findNext( T_COMMA, $callbackPtr + 1 ); + // If callback is array, get second element. + if ( T_ARRAY === $tokens[ $callbackPtr ]['code'] ) { + $comma = $phpcsFile->findNext( T_COMMA, ( $callbackPtr + 1 ) ); if ( false === $comma ) { $this->confused( $phpcsFile, $stackPtr ); return; } - $callbackPtr = $phpcsFile->findNext( array( T_WHITESPACE ), $comma + 1, null, true, null, true ); + $callbackPtr = $phpcsFile->findNext( array( T_WHITESPACE ), ( $comma + 1 ), null, true, null, true ); if ( false === $callbackPtr ) { $this->confused( $phpcsFile, $stackPtr ); return; @@ -68,18 +66,16 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $functionPtr = null; - // Search for the function in tokens - if ( in_array( $tokens[$callbackPtr]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ) ) ) { - $functionName = trim( $tokens[$callbackPtr]['content'], '"\'' ); + // Search for the function in tokens. + if ( in_array( $tokens[ $callbackPtr ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { + $functionName = trim( $tokens[ $callbackPtr ]['content'], '"\'' ); foreach ( $tokens as $ptr => $_token ) { - if ( $_token['code'] == T_STRING && $_token['content'] == $functionName ) { + if ( T_STRING === $_token['code'] && $_token['content'] === $functionName ) { $functionPtr = $ptr; } } - } - // Closure - else if ( $tokens[$callbackPtr]['code'] === T_CLOSURE ) { + } elseif ( T_CLOSURE === $tokens[ $callbackPtr ]['code'] ) { // Closure. $functionPtr = $callbackPtr; } @@ -92,16 +88,16 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $closing = $tokens[ $opening ]['bracket_closer']; for ( $i = $opening; $i <= $closing; $i++ ) { - if ( in_array( $tokens[$i]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ) ) ) { - if ( trim( $tokens[$i]['content'], '\'"' ) == 'interval' ) { + if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { + if ( 'interval' === trim( $tokens[ $i ]['content'], '\'"' ) ) { $operator = $phpcsFile->findNext( T_DOUBLE_ARROW, $i, null, null, null, true ); if ( empty( $operator ) ) { $this->confused( $phpcsFile, $stackPtr ); } - $valueStart = $phpcsFile->findNext( T_WHITESPACE, $operator + 1, null, true, null, true ); - $valueEnd = $phpcsFile->findNext( array( T_COMMA, T_CLOSE_PARENTHESIS ), $valueStart + 1 ); - $value = $phpcsFile->getTokensAsString( $valueStart, $valueEnd - $valueStart ); + $valueStart = $phpcsFile->findNext( T_WHITESPACE, ( $operator + 1 ), null, true, null, true ); + $valueEnd = $phpcsFile->findNext( array( T_COMMA, T_CLOSE_PARENTHESIS ), ( $valueStart + 1 ) ); + $value = $phpcsFile->getTokensAsString( $valueStart, ( $valueEnd - $valueStart ) ); if ( is_numeric( $value ) ) { $interval = $value; @@ -110,7 +106,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) // If all digits and operators, eval! if ( preg_match( '#^[\s\d\+\*\-\/]+$#', $value ) > 0 ) { - $interval = eval( "return ( $value );" ); // No harm here + $interval = eval( "return ( $value );" ); // No harm here. break; } @@ -125,13 +121,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) return; } - - }//end process() + } // end process() public function confused( $phpcsFile, $stackPtr ) { $phpcsFile->addWarning( 'Detected changing of cron_schedules, but could not detect the interval value.', $stackPtr, 'ChangeDetected' ); } - - -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php index 9d131630da..27b41084e8 100644 --- a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php +++ b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php @@ -1,6 +1,6 @@ * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 */ -class WordPress_Sniffs_VIP_DirectDatabaseQuerySniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_VIP_DirectDatabaseQuerySniff implements PHP_CodeSniffer_Sniff { /** * List of custom cache get functions. @@ -67,13 +66,12 @@ class WordPress_Sniffs_VIP_DirectDatabaseQuerySniff implements PHP_CodeSniffer_S * * @return array */ - public function register() - { + public function register() { return array( - T_VARIABLE, - ); + T_VARIABLE, + ); - }//end register() + } // end register() /** @@ -85,8 +83,7 @@ public function register() * * @return int|void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { if ( ! isset( self::$methods['all'] ) ) { self::$methods['all'] = array_merge( self::$methods['cachable'], self::$methods['noncachable'] ); @@ -108,49 +105,51 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $tokens = $phpcsFile->getTokens(); - // Check for $wpdb variable - if ( $tokens[$stackPtr]['content'] != '$wpdb' ) + // Check for $wpdb variable. + if ( '$wpdb' !== $tokens[ $stackPtr ]['content'] ) { return; + } - $is_object_call = $phpcsFile->findNext( array( T_OBJECT_OPERATOR ), $stackPtr + 1, null, null, null, true ); - if ( false == $is_object_call ) - return; // This is not a call to the wpdb object + $is_object_call = $phpcsFile->findNext( array( T_OBJECT_OPERATOR ), ( $stackPtr + 1 ), null, null, null, true ); + if ( false === $is_object_call ) { + return; // This is not a call to the wpdb object. + } - $methodPtr = $phpcsFile->findNext( array( T_WHITESPACE ), $is_object_call + 1, null, true, null, true ); - $method = $tokens[ $methodPtr ]['content']; + $methodPtr = $phpcsFile->findNext( array( T_WHITESPACE ), ( $is_object_call + 1 ), null, true, null, true ); + $method = $tokens[ $methodPtr ]['content']; if ( ! isset( self::$methods['all'][ $method ] ) ) { return; } - $endOfStatement = $phpcsFile->findNext( array( T_SEMICOLON ), $stackPtr + 1, null, null, null, true ); + $endOfStatement = $phpcsFile->findNext( array( T_SEMICOLON ), ( $stackPtr + 1 ), null, null, null, true ); $endOfLineComment = ''; - for ( $i = $endOfStatement + 1; $i < count( $tokens ); $i++ ) { + $tokenCount = count( $tokens ); + for ( $i = ( $endOfStatement + 1 ); $i < $tokenCount; $i++ ) { - if ( $tokens[$i]['line'] !== $tokens[$endOfStatement]['line'] ) { + if ( $tokens[ $i ]['line'] !== $tokens[ $endOfStatement ]['line'] ) { break; } - if ( $tokens[$i]['code'] === T_COMMENT ) { - $endOfLineComment .= $tokens[$i]['content']; + if ( T_COMMENT === $tokens[ $i ]['code'] ) { + $endOfLineComment .= $tokens[ $i ]['content']; } - } $whitelisted_db_call = false; - if ( preg_match( '/db call\W*(ok|pass|clear|whitelist)/i', $endOfLineComment, $matches ) ) { + if ( preg_match( '/db call\W*(?:ok|pass|clear|whitelist)/i', $endOfLineComment ) ) { $whitelisted_db_call = true; } - // Check for Database Schema Changes + // Check for Database Schema Changes. $_pos = $stackPtr; - while ( $_pos = $phpcsFile->findNext( array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), $_pos + 1, $endOfStatement, null, null, true ) ) { - if ( preg_match( '#\b(ALTER|CREATE|DROP)\b#i', $tokens[$_pos]['content'], $matches ) > 0 ) { + while ( $_pos = $phpcsFile->findNext( array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), ( $_pos + 1 ), $endOfStatement, null, null, true ) ) { + if ( preg_match( '#\b(?:ALTER|CREATE|DROP)\b#i', $tokens[ $_pos ]['content'] ) > 0 ) { $phpcsFile->addError( 'Attempting a database schema change is highly discouraged.', $_pos, 'SchemaChange' ); } } - // Flag instance if not whitelisted + // Flag instance if not whitelisted. if ( ! $whitelisted_db_call ) { $phpcsFile->addWarning( 'Usage of a direct database call is discouraged.', $stackPtr, 'DirectQuery' ); } @@ -160,27 +159,26 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) } $whitelisted_cache = false; - $cached = $wp_cache_get = false; - if ( preg_match( '/cache\s+(ok|pass|clear|whitelist)/i', $endOfLineComment, $matches ) ) { + $cached = $wp_cache_get = false; + if ( preg_match( '/cache\s+(?:ok|pass|clear|whitelist)/i', $endOfLineComment ) ) { $whitelisted_cache = true; } - if ( ! $whitelisted_cache && ! empty( $tokens[$stackPtr]['conditions'] ) ) { + if ( ! $whitelisted_cache && ! empty( $tokens[ $stackPtr ]['conditions'] ) ) { $scope_function = $phpcsFile->getCondition( $stackPtr, T_FUNCTION ); if ( $scope_function ) { - $scopeStart = $tokens[$scope_function]['scope_opener']; - $scopeEnd = $tokens[$scope_function]['scope_closer']; + $scopeStart = $tokens[ $scope_function ]['scope_opener']; + $scopeEnd = $tokens[ $scope_function ]['scope_closer']; - for ( $i = $scopeStart + 1; $i < $scopeEnd; $i++ ) { + for ( $i = ( $scopeStart + 1 ); $i < $scopeEnd; $i++ ) { if ( T_STRING === $tokens[ $i ]['code'] ) { if ( isset( WordPress_Sniff::$cacheDeleteFunctions[ $tokens[ $i ]['content'] ] ) ) { - if ( in_array( $method, array( 'query', 'update', 'replace', 'delete' ) ) ) { + if ( in_array( $method, array( 'query', 'update', 'replace', 'delete' ), true ) ) { $cached = true; break; } - } elseif ( isset( WordPress_Sniff::$cacheGetFunctions[ $tokens[ $i ]['content'] ] ) ) { $wp_cache_get = true; @@ -204,6 +202,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) return $endOfStatement; - }//end process() + } // end process() -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php index 61a9ade3a0..28749570eb 100644 --- a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php +++ b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php @@ -9,8 +9,7 @@ * @author Shady Sharaf * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 */ -class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ +class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { /** * A list of forbidden functions with their alternatives. @@ -21,32 +20,32 @@ class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_ * @var array(string => string|null) */ public $forbiddenFunctions = array( - 'file_put_contents' => null, - 'fwrite' => null, - 'fputcsv' => null, - 'fputs' => null, - 'ftruncate' => null, - 'link' => null, - 'symlink' => null, - 'mkdir' => null, - 'rename' => null, - 'rmdir' => null, - 'tempnam' => null, - 'touch' => null, - 'unlink' => null, - 'is_writable' => null, - 'is_writeable' => null, - 'lchgrp' => null, - 'lchown' => null, - 'fputcsv' => null, - 'delete' => null, - 'chmod' => null, - 'chown' => null, - 'chgrp' => null, - 'chmod' => null, - 'chmod' => null, - 'flock' => null, - ); + 'file_put_contents' => null, + 'fwrite' => null, + 'fputcsv' => null, + 'fputs' => null, + 'ftruncate' => null, + 'link' => null, + 'symlink' => null, + 'mkdir' => null, + 'rename' => null, + 'rmdir' => null, + 'tempnam' => null, + 'touch' => null, + 'unlink' => null, + 'is_writable' => null, + 'is_writeable' => null, + 'lchgrp' => null, + 'lchown' => null, + 'fputcsv' => null, + 'delete' => null, + 'chmod' => null, + 'chown' => null, + 'chgrp' => null, + 'chmod' => null, + 'chmod' => null, + 'flock' => null, + ); /** * If true, an error will be thrown; otherwise a warning. @@ -66,18 +65,16 @@ class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_ * * @return void */ - protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) - { - $data = array($function); + protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) { + $data = array( $function ); $error = 'Filesystem writes are forbidden, you should not be using %s()'; - if ( $this->error === true ) { + if ( true === $this->error ) { $phpcsFile->addError( $error, $stackPtr, 'FileWriteDetected', $data ); } else { $phpcsFile->addWarning( $error, $stackPtr, 'FileWriteDetected', $data ); } - }//end addError() + } // end addError() - -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/OrderByRandSniff.php b/WordPress/Sniffs/VIP/OrderByRandSniff.php index 9e39d2da36..b1954d567b 100644 --- a/WordPress/Sniffs/VIP/OrderByRandSniff.php +++ b/WordPress/Sniffs/VIP/OrderByRandSniff.php @@ -20,7 +20,7 @@ public function getGroups() { 'keys' => array( 'orderby', ), - ) + ), ); } @@ -28,11 +28,11 @@ public function getGroups() { * Callback to process each confirmed key, to check value * This must be extended to add the logic to check assignment value * - * @param string $key Array index / key - * @param mixed $val Assigned value - * @param int $line Token line - * @param array $group Group definition - * @return mixed FALSE if no match, TRUE if matches, STRING if matches with custom error message passed to ->process() + * @param string $key Array index / key. + * @param mixed $val Assigned value. + * @param int $line Token line. + * @param array $group Group definition. + * @return mixed FALSE if no match, TRUE if matches, STRING if matches with custom error message passed to ->process(). */ public function callback( $key, $val, $line, $group ) { if ( 'rand' === strtolower( $val ) ) { @@ -41,5 +41,4 @@ public function callback( $key, $val, $line, $group ) { return false; } } - -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php index 863d3da472..db20dc8677 100644 --- a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php +++ b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php @@ -6,8 +6,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_PluginMenuSlugSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_VIP_PluginMenuSlugSniff implements PHP_CodeSniffer_Sniff { public $add_menu_functions = array( 'add_menu_page', @@ -25,20 +24,19 @@ class WordPress_Sniffs_VIP_PluginMenuSlugSniff implements PHP_CodeSniffer_Sniff 'add_users_page', 'add_management_page', 'add_options_page', - ); + ); /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( - T_STRING, - ); + T_STRING, + ); - }//end register() + } // end register() /** @@ -50,24 +48,23 @@ public function register() * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); - $token = $tokens[$stackPtr]; + $token = $tokens[ $stackPtr ]; - if ( ! in_array( $token['content'], $this->add_menu_functions ) ) { + if ( ! in_array( $token['content'], $this->add_menu_functions, true ) ) { return; } $opening = $phpcsFile->findNext( T_OPEN_PARENTHESIS, $stackPtr ); - $closing = $tokens[$opening]['parenthesis_closer']; + $closing = $tokens[ $opening ]['parenthesis_closer']; $string = $phpcsFile->findNext( T_FILE, $opening, $closing, null, '__FILE__', true ); if ( $string ) { $phpcsFile->addError( 'Using __FILE__ for menu slugs risks exposing filesystem structure.', $stackPtr, 'Using__FILE__' ); } - - }//end process() -}//end class + } // end process() + +} // end class diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index d97d1a9a6f..c292cd587b 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -1,6 +1,6 @@ array( * 'wpdb' => array( - * 'type' => 'error' | 'warning', - * 'message' => 'Dont use this one please!', - * 'variables' => array( '$val', '$var' ), - * 'object_vars' => array( '$foo->bar', .. ), + * 'type' => 'error' | 'warning', + * 'message' => 'Dont use this one please!', + * 'variables' => array( '$val', '$var' ), + * 'object_vars' => array( '$foo->bar', .. ), * 'array_members' => array( '$foo['bar']', .. ), * ) * ) @@ -33,39 +33,37 @@ public function getGroups() { 'posts_per_page', 'nopaging', 'numberposts', - ), - ) - ); + ), + ), + ); } /** - * Callback to process each confirmed key, to check value - * This must be extended to add the logic to check assignment value - * - * @param string $key Array index / key - * @param mixed $val Assigned value - * @param int $line Token line - * @param array $group Group definition - * @return mixed FALSE if no match, TRUE if matches, STRING if matches with custom error message passed to ->process() + * Callback to process each confirmed key, to check value. + * This must be extended to add the logic to check assignment value. + * + * @param string $key Array index / key. + * @param mixed $val Assigned value. + * @param int $line Token line. + * @param array $group Group definition. + * @return mixed FALSE if no match, TRUE if matches, STRING if matches + * with custom error message passed to ->process(). */ public function callback( $key, $val, $line, $group ) { $key = strtolower( $key ); if ( - ( $key == 'nopaging' && ( $val == 'true' || $val == 1 ) ) + ( 'nopaging' === $key && ( 'true' === $val || 1 === $val ) ) || - ( in_array( $key, array( 'numberposts', 'posts_per_page' ) ) && $val == '-1' ) + ( in_array( $key, array( 'numberposts', 'posts_per_page' ), true ) && '-1' == $val ) ) { + return 'Disabling pagination is prohibited in VIP context, do not set `%s` to `%s` ever.'; - } - elseif ( - in_array( $key, array( 'posts_per_page', 'numberposts' ) ) - ) { + + } elseif ( in_array( $key, array( 'posts_per_page', 'numberposts' ), true ) ) { if ( $val > 100 ) { return 'Detected high pagination limit, `%s` is set to `%s`'; } } } - - -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index c1d5c86544..8c72951296 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -1,6 +1,6 @@ array( * 'lambda' => array( - * 'type' => 'error' | 'warning', - * 'message' => 'Use anonymous functions instead please!', + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', * 'functions' => array( 'eval', 'create_function' ), * ) * ) @@ -29,27 +29,27 @@ public function getGroups() { 'type' => 'error', 'message' => '%s is not something you should ever need to do in a VIP theme context. Instead use an API (XML-RPC, REST) to interact with other sites if needed.', 'functions' => array( 'switch_to_blog' ), - ), + ), 'create_function' => array( - 'type' => 'warning', - 'message' => '%s is discouraged, please use Anonymous functions instead.', + 'type' => 'warning', + 'message' => '%s is discouraged, please use Anonymous functions instead.', 'functions' => array( 'create_function', ), ), 'eval' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use Anonymous functions instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use Anonymous functions instead.', 'functions' => array( 'eval', ), ), 'file_get_contents' => array( - 'type' => 'warning', - 'message' => '%s is highly discouraged, please use wpcom_vip_file_get_contents() instead.', + 'type' => 'warning', + 'message' => '%s is highly discouraged, please use wpcom_vip_file_get_contents() instead.', 'functions' => array( 'file_get_contents', 'vip_wp_file_get_contents', @@ -57,8 +57,8 @@ public function getGroups() { ), 'get_term_link' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_get_term_link() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_get_term_link() instead.', 'functions' => array( 'get_term_link', 'get_tag_link', @@ -67,24 +67,24 @@ public function getGroups() { ), 'get_page_by_path' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_get_page_by_path() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_get_page_by_path() instead.', 'functions' => array( 'get_page_by_path', ), ), 'get_page_by_title' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_get_page_by_title() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_get_page_by_title() instead.', 'functions' => array( 'get_page_by_title', ), ), 'get_term_by' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_get_term_by() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_get_term_by() instead.', 'functions' => array( 'get_term_by', 'get_cat_ID', @@ -92,16 +92,16 @@ public function getGroups() { ), 'get_category_by_slug' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_get_category_by_slug() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_get_category_by_slug() instead.', 'functions' => array( 'get_category_by_slug', ), ), 'url_to_postid' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_url_to_postid() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_url_to_postid() instead.', 'functions' => array( 'url_to_postid', 'url_to_post_id', @@ -109,68 +109,68 @@ public function getGroups() { ), 'attachment_url_to_postid' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use wpcom_vip_attachment_url_to_postid() instead.', + 'type' => 'error', + 'message' => '%s is prohibited, please use wpcom_vip_attachment_url_to_postid() instead.', 'functions' => array( 'attachment_url_to_postid', ), ), 'wp_remote_get' => array( - 'type' => 'warning', - 'message' => '%s is highly discouraged, please use vip_safe_wp_remote_get() instead.', + 'type' => 'warning', + 'message' => '%s is highly discouraged, please use vip_safe_wp_remote_get() instead.', 'functions' => array( 'wp_remote_get', - ), ), + ), 'curl' => array( - 'type' => 'warning', - 'message' => 'Using cURL functions is highly discouraged within VIP context. Check (Fetching Remote Data) on VIP Documentation.', + 'type' => 'warning', + 'message' => 'Using cURL functions is highly discouraged within VIP context. Check (Fetching Remote Data) on VIP Documentation.', 'functions' => array( 'curl_*', - ), ), + ), 'extract' => array( - 'type' => 'warning', - 'message' => '%s() usage is highly discouraged, due to the complexity and unintended issues it might cause.', + 'type' => 'warning', + 'message' => '%s() usage is highly discouraged, due to the complexity and unintended issues it might cause.', 'functions' => array( 'extract', - ), ), + ), 'custom_role' => array( - 'type' => 'error', - 'message' => 'Use wpcom_vip_add_role() instead of add_role()', + 'type' => 'error', + 'message' => 'Use wpcom_vip_add_role() instead of add_role()', 'functions' => array( 'add_role', - ), ), + ), 'cookies' => array( - 'type' => 'warning', - 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', + 'type' => 'warning', + 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', 'functions' => array( 'setcookie', - ), ), + ), 'user_meta' => array( - 'type' => 'error', - 'message' => '%s() usage is highly discouraged, check VIP documentation on "Working with wp_users"', + 'type' => 'error', + 'message' => '%s() usage is highly discouraged, check VIP documentation on "Working with wp_users"', 'functions' => array( 'get_user_meta', 'update_user_meta', 'delete_user_meta', 'add_user_meta', - ), ), + ), // @todo Introduce a sniff specific to get_posts() that checks for suppress_filters=>false being supplied. 'get_posts' => array( - 'type' => 'warning', - 'message' => '%s is discouraged in favor of creating a new WP_Query() so that Advanced Post Cache will cache the query, unless you explicitly supply suppress_filters => false.', + 'type' => 'warning', + 'message' => '%s is discouraged in favor of creating a new WP_Query() so that Advanced Post Cache will cache the query, unless you explicitly supply suppress_filters => false.', 'functions' => array( 'get_posts', 'wp_get_recent_posts', @@ -179,8 +179,8 @@ public function getGroups() { ), 'wp_get_post_terms' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged due to not being cached; please use get_the_terms() along with wp_list_pluck() to extract the IDs.', + 'type' => 'error', + 'message' => '%s is highly discouraged due to not being cached; please use get_the_terms() along with wp_list_pluck() to extract the IDs.', 'functions' => array( 'wp_get_post_terms', 'wp_get_post_categories', @@ -190,32 +190,32 @@ public function getGroups() { ), 'term_exists' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_term_exists() instead.', + 'type' => 'error', + 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_term_exists() instead.', 'functions' => array( 'term_exists', ), ), 'count_user_posts' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_count_user_posts() instead.', + 'type' => 'error', + 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_count_user_posts() instead.', 'functions' => array( 'count_user_posts', ), ), 'wp_old_slug_redirect' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_old_slug_redirect() instead.', + 'type' => 'error', + 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_old_slug_redirect() instead.', 'functions' => array( 'wp_old_slug_redirect', ), ), 'get_adjacent_post' => array( - 'type' => 'error', - 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_get_adjacent_post() instead.', + 'type' => 'error', + 'message' => '%s is highly discouraged due to not being cached; please use wpcom_vip_get_adjacent_post() instead.', 'functions' => array( 'get_adjacent_post', 'get_previous_post', @@ -226,24 +226,24 @@ public function getGroups() { ), 'parse_url' => array( - 'type' => 'warning', - 'message' => '%s is discouraged due to a lack for backwards-compatibility in PHP versions; please use wp_parse_url() instead.', + 'type' => 'warning', + 'message' => '%s is discouraged due to a lack for backwards-compatibility in PHP versions; please use wp_parse_url() instead.', 'functions' => array( 'parse_url', ), ), 'get_intermediate_image_sizes' => array( - 'type' => 'error', - 'message' => 'Intermediate images do not exist on the VIP platform, and thus get_intermediate_image_sizes() returns an empty array() on the platform. This behavior is intentional to prevent WordPress from generating multiple thumbnails when images are uploaded.', + 'type' => 'error', + 'message' => 'Intermediate images do not exist on the VIP platform, and thus get_intermediate_image_sizes() returns an empty array() on the platform. This behavior is intentional to prevent WordPress from generating multiple thumbnails when images are uploaded.', 'functions' => array( 'get_intermediate_image_sizes', ), ), 'serialize' => array( - 'type' => 'warning', - 'message' => '%s Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data.', + 'type' => 'warning', + 'message' => '%s Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data.', 'functions' => array( 'serialize', 'unserialize', @@ -251,8 +251,8 @@ public function getGroups() { ), 'error_log' => array( - 'type' => 'error', - 'message' => '%s Debug code is not allowed on VIP Production', + 'type' => 'error', + 'message' => '%s Debug code is not allowed on VIP Production', 'functions' => array( 'error_log', 'var_dump', @@ -263,64 +263,64 @@ public function getGroups() { ), 'wp_redirect' => array( - 'type' => 'warning', - 'message' => '%s Using wp_safe_redirect(), along with the allowed_redirect_hosts filter, can help avoid any chances of malicious redirects within code. It’s also important to remember to call exit() after a redirect so that no other unwanted code is executed.', + 'type' => 'warning', + 'message' => '%s Using wp_safe_redirect(), along with the allowed_redirect_hosts filter, can help avoid any chances of malicious redirects within code. It’s also important to remember to call exit() after a redirect so that no other unwanted code is executed.', 'functions' => array( 'wp_redirect', ), ), 'wp_is_mobile' => array( - 'type' => 'error', - 'message' => '%s When targeting mobile visitors, jetpack_is_mobile() should be used instead of wp_is_mobile. It is more robust and works better with full page caching.', + 'type' => 'error', + 'message' => '%s When targeting mobile visitors, jetpack_is_mobile() should be used instead of wp_is_mobile. It is more robust and works better with full page caching.', 'functions' => array( 'wp_is_mobile', ), ), 'urlencode' => array( - 'type' => 'warning', - 'message' => '%s urlencode should only be used when dealing with legacy applications rawurlencode should now de used instead. See http://php.net/manual/en/function.rawurlencode.php and http://www.faqs.org/rfcs/rfc3986.html', + 'type' => 'warning', + 'message' => '%s urlencode should only be used when dealing with legacy applications rawurlencode should now de used instead. See http://php.net/manual/en/function.rawurlencode.php and http://www.faqs.org/rfcs/rfc3986.html', 'functions' => array( 'rawurlencode', ), ), 'ereg' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_match() instead. See http://php.net/manual/en/function.ereg.php', + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_match() instead. See http://php.net/manual/en/function.ereg.php', 'functions' => array( 'ereg', ), ), 'eregi' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_match() with i modifier instead. See http://php.net/manual/en/function.eregi.php', + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_match() with i modifier instead. See http://php.net/manual/en/function.eregi.php', 'functions' => array( 'eregi', ), ), 'ereg_replace' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_replace() instead. See http://php.net/manual/en/function.ereg-replace.php', + 'type' => 'error', + 'message' => '%s is prohibited, please use preg_replace() instead. See http://php.net/manual/en/function.ereg-replace.php', 'functions' => array( 'ereg_replace', ), ), 'split' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use explode() or preg_split() instead. See http://php.net/manual/en/function.split.php', + 'type' => 'error', + 'message' => '%s is prohibited, please use explode() or preg_split() instead. See http://php.net/manual/en/function.split.php', 'functions' => array( 'split', ), ), 'runtime_configuration' => array( - 'type' => 'error', - 'message' => '%s is prohibited, changing configuration at runtime is not allowed on VIP Production.', + 'type' => 'error', + 'message' => '%s is prohibited, changing configuration at runtime is not allowed on VIP Production.', 'functions' => array( 'dl', 'error_reporting', @@ -337,8 +337,8 @@ public function getGroups() { ), 'prevent_path_disclosure' => array( - 'type' => 'error', - 'message' => '%s is prohibited as it can lead to full path disclosure.', + 'type' => 'error', + 'message' => '%s is prohibited as it can lead to full path disclosure.', 'functions' => array( 'error_reporting', 'phpinfo', @@ -347,4 +347,4 @@ public function getGroups() { ); } -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php index 22461222ab..8ccd0f125d 100644 --- a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php @@ -1,16 +1,15 @@ */ -class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_Sniffs_Variables_VariableRestrictionsSniff -{ +class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_Sniffs_Variables_VariableRestrictionsSniff { /** - * Groups of variables to restrict + * Groups of variables to restrict. * * Example: groups => array( * 'wpdb' => array( @@ -27,26 +26,24 @@ class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_Sniffs_Var public function getGroups() { return array( 'user_meta' => array( - 'type' => 'error', - 'message' => 'Usage of users/usermeta tables is highly discouraged in VIP context, For storing user additional user metadata, you should look at User Attributes.', + 'type' => 'error', + 'message' => 'Usage of users/usermeta tables is highly discouraged in VIP context, For storing user additional user metadata, you should look at User Attributes.', 'object_vars' => array( '$wpdb->users', '$wpdb->usermeta', - ), ), + ), 'cache_constraints' => array( - 'type' => 'warning', - 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', - 'variables' => array( + 'type' => 'warning', + 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', + 'variables' => array( '$_COOKIE', ), 'array_members' => array( '$_SERVER[\'HTTP_USER_AGENT\']', '$_SERVER[\'REMOTE_ADDR\']', - ), ), - ); + ), + ); } - - -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php index aad293492d..a3cc3ccb3b 100644 --- a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php @@ -2,57 +2,54 @@ /** * WordPress_Sniffs_VIP_SessionFunctionsUsageSniff. * - * Discourages the use of session functions + * Discourages the use of session functions. * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf * @see https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ -class WordPress_Sniffs_VIP_SessionFunctionsUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ +class WordPress_Sniffs_VIP_SessionFunctionsUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { - /** - * A list of forbidden functions with their alternatives. - * - * The value is NULL if no alternative exists. IE, the - * function should just not be used. - * - * @var array(string => string|null) - */ - public $forbiddenFunctions = array( - 'session_cache_expire' => null, - 'session_cache_limiter' => null, - 'session_commit' => null, - 'session_decode' => null, - 'session_destroy' => null, - 'session_encode' => null, - 'session_get_cookie_params' => null, - 'session_id' => null, - 'session_is_registered' => null, - 'session_module_name' => null, - 'session_name' => null, - 'session_regenerate_id' => null, - 'session_register_shutdown' => null, - 'session_register' => null, - 'session_save_path' => null, - 'session_set_cookie_params' => null, - 'session_set_save_handler' => null, - 'session_start' => null, - 'session_status' => null, - 'session_unregister' => null, - 'session_unset' => null, - 'session_write_close' => null, - ); + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. I.e. the + * function should just not be used. + * + * @var array(string => string|null) + */ + public $forbiddenFunctions = array( + 'session_cache_expire' => null, + 'session_cache_limiter' => null, + 'session_commit' => null, + 'session_decode' => null, + 'session_destroy' => null, + 'session_encode' => null, + 'session_get_cookie_params' => null, + 'session_id' => null, + 'session_is_registered' => null, + 'session_module_name' => null, + 'session_name' => null, + 'session_regenerate_id' => null, + 'session_register_shutdown' => null, + 'session_register' => null, + 'session_save_path' => null, + 'session_set_cookie_params' => null, + 'session_set_save_handler' => null, + 'session_start' => null, + 'session_status' => null, + 'session_unregister' => null, + 'session_unset' => null, + 'session_write_close' => null, + ); - protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) - { - $data = array($function); - $error = 'The use of PHP session function %s() is prohibited.'; + protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) { + $data = array( $function ); + $error = 'The use of PHP session function %s() is prohibited.'; - $phpcsFile->addError( $error, $stackPtr, $function, $data ); + $phpcsFile->addError( $error, $stackPtr, $function, $data ); - }//end addError() - -}//end class + } // end addError() +} // end class diff --git a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php index 37255fb309..b823ace6fa 100644 --- a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php @@ -10,45 +10,38 @@ * @author Shady Sharaf * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ -class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ +class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array( - T_VARIABLE, - ); + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_VARIABLE, + ); - }//end register() + } // end register() - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @todo Allow T_CONSTANT_ENCAPSED_STRING? - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) { - $phpcsFile->addError( 'Usage of $_SESSION variable is prohibited.', $stackPtr, 'SessionVarsProhibited' ); - } - - - }//end process() - - - -}//end class + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @todo Allow T_CONSTANT_ENCAPSED_STRING? + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + + if ( '$_SESSION' === $tokens[ $stackPtr ]['content'] ) { + $phpcsFile->addError( 'Usage of $_SESSION variable is prohibited.', $stackPtr, 'SessionVarsProhibited' ); + } + + } // end process() + +} // end class diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index 06eaf46058..0c1e5dcbe7 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -1,24 +1,23 @@ */ -class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff -{ +class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { /** - * Groups of variables to restrict + * Groups of variables to restrict. * This should be overridden in extending classes. * * Example: groups => array( * 'wpdb' => array( - * 'type' => 'error' | 'warning', - * 'message' => 'Dont use this one please!', - * 'variables' => array( '$val', '$var' ), - * 'object_vars' => array( '$foo->bar', .. ), + * 'type' => 'error' | 'warning', + * 'message' => 'Dont use this one please!', + * 'variables' => array( '$val', '$var' ), + * 'object_vars' => array( '$foo->bar', .. ), * 'array_members' => array( '$foo['bar']', .. ), * ) * ) @@ -28,16 +27,16 @@ class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_Sniffs_Arrays_Arra public function getGroups() { return array( 'slow_db_query' => array( - 'type' => 'warning', + 'type' => 'warning', 'message' => 'Detected usage of %s, possible slow query.', - 'keys' => array( + 'keys' => array( 'tax_query', 'meta_query', 'meta_key', 'meta_value', - ), - ) - ); + ), + ), + ); } /** @@ -59,4 +58,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { parent::process( $phpcsFile, $stackPtr ); } -}//end class +} // end class diff --git a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php index 4d4f9c7ee5..4bff6de2d4 100644 --- a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php +++ b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php @@ -7,21 +7,19 @@ * @author Shady Sharaf * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/79 */ -class WordPress_Sniffs_VIP_SuperGlobalInputUsageSniff extends WordPress_Sniff -{ +class WordPress_Sniffs_VIP_SuperGlobalInputUsageSniff extends WordPress_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( - T_VARIABLE, - ); + T_VARIABLE, + ); - }//end register() + } // end register() /** @@ -33,27 +31,27 @@ public function register() * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); $tokens = $phpcsFile->getTokens(); - // Check for global input variable - if ( ! in_array( $tokens[ $stackPtr ]['content'], WordPress_Sniff::$input_superglobals ) ) { + // Check for global input variable. + if ( ! in_array( $tokens[ $stackPtr ]['content'], WordPress_Sniff::$input_superglobals, true ) ) { return; } - $varName = $tokens[$stackPtr]['content']; + $varName = $tokens[ $stackPtr ]['content']; - // If we're overriding a superglobal with an assignment, no need to test + // If we're overriding a superglobal with an assignment, no need to test. if ( $this->is_assignment( $stackPtr ) ) { return; } - // Check for whitelisting comment + // Check for whitelisting comment. if ( ! $this->has_whitelist_comment( 'input var', $stackPtr ) ) { $phpcsFile->addWarning( 'Detected access of super global var %s, probably need manual inspection.', $stackPtr, 'AccessDetected', array( $varName ) ); } - }//end process() -}//end class + } // end process() + +} // end class diff --git a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php index 36d8daad08..3d771790f9 100644 --- a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php +++ b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php @@ -9,27 +9,24 @@ * @author Shady Sharaf * @see http://vip.wordpress.com/documentation/use-current_time-not-date_default_timezone_set/ */ -class WordPress_Sniffs_VIP_TimezoneChangeSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff -{ +class WordPress_Sniffs_VIP_TimezoneChangeSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { - /** - * A list of forbidden functions with their alternatives. - * - * The value is NULL if no alternative exists. IE, the - * function should just not be used. - * - * @var array(string => string|null) - */ - public $forbiddenFunctions = array( - 'date_default_timezone_set' => null, - ); + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. IE, the + * function should just not be used. + * + * @var array(string => string|null) + */ + public $forbiddenFunctions = array( + 'date_default_timezone_set' => null, + ); - protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) - { - $error = 'Using date_default_timezone_set() and similar isn’t allowed, instead use WP internal timezone support.'; - $phpcsFile->addError( $error, $stackPtr, $function ); + protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) { + $error = 'Using date_default_timezone_set() and similar isn’t allowed, instead use WP internal timezone support.'; + $phpcsFile->addError( $error, $stackPtr, $function ); - }//end addError() - -}//end class + } // end addError() +} // end class diff --git a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php index 791321e662..419a176bab 100644 --- a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php +++ b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php @@ -13,7 +13,8 @@ class WordPress_Sniffs_VIP_ValidatedSanitizedInputSniff extends WordPress_Sniff { /** - * Check for validation functions for a variable within its own parenthesis only + * Check for validation functions for a variable within its own parenthesis only. + * * @var boolean */ public $check_validation_in_scope_only = false; @@ -88,7 +89,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $superglobals = WordPress_Sniff::$input_superglobals; - // Handling string interpolation + // Handling string interpolation. if ( T_DOUBLE_QUOTED_STRING === $tokens[ $stackPtr ]['code'] ) { $interpolated_variables = array_map( create_function( '$symbol', 'return "$" . $symbol;' ), // Replace with closure when 5.3 is minimum requirement for PHPCS. @@ -102,11 +103,11 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Check if this is a superglobal. - if ( ! in_array( $tokens[ $stackPtr ]['content'], $superglobals ) ) { + if ( ! in_array( $tokens[ $stackPtr ]['content'], $superglobals, true ) ) { return; } - // If we're overriding a superglobal with an assignment, no need to test + // If we're overriding a superglobal with an assignment, no need to test. if ( $this->is_assignment( $stackPtr ) ) { return; } @@ -137,7 +138,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - // Now look for sanitizing functions + // Now look for sanitizing functions. if ( ! $this->is_sanitized( $stackPtr, true ) ) { $phpcsFile->addError( 'Detected usage of a non-sanitized input variable: %s', $stackPtr, 'InputNotSanitized', array( $tokens[ $stackPtr ]['content'] ) ); } diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index 69bf0ac024..0c370405a8 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -8,8 +8,7 @@ * @package WordPress_Coding_Standards * @author Shady Sharaf */ -class WordPress_Sniffs_Variables_GlobalVariablesSniff extends WordPress_Sniff -{ +class WordPress_Sniffs_Variables_GlobalVariablesSniff extends WordPress_Sniff { public $globals = array( 'comment', @@ -278,23 +277,23 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $token = $tokens[ $stackPtr ]; - $search = array(); // Array of globals to watch for + $search = array(); // Array of globals to watch for. if ( T_VARIABLE === $token['code'] && '$GLOBALS' === $token['content'] ) { - $bracketPtr = $phpcsFile->findNext( array( T_WHITESPACE ), $stackPtr + 1, null, true ); + $bracketPtr = $phpcsFile->findNext( array( T_WHITESPACE ), ( $stackPtr + 1 ), null, true ); if ( T_OPEN_SQUARE_BRACKET !== $tokens[ $bracketPtr ]['code'] ) { return; } - $varPtr = $phpcsFile->findNext( T_WHITESPACE, $bracketPtr + 1, $tokens[ $bracketPtr ]['bracket_closer'], true ); + $varPtr = $phpcsFile->findNext( T_WHITESPACE, ( $bracketPtr + 1 ), $tokens[ $bracketPtr ]['bracket_closer'], true ); $varToken = $tokens[ $varPtr ]; - if ( ! in_array( trim( $varToken['content'], '\'"' ), $this->globals ) ) { + if ( ! in_array( trim( $varToken['content'], '\'"' ), $this->globals, true ) ) { return; } - $assignment = $phpcsFile->findNext( T_WHITESPACE, $tokens[ $bracketPtr ]['bracket_closer'] + 1, null, true ); + $assignment = $phpcsFile->findNext( T_WHITESPACE, ( $tokens[ $bracketPtr ]['bracket_closer'] + 1 ), null, true ); if ( $assignment && T_EQUAL === $tokens[ $assignment ]['code'] ) { if ( ! $this->has_whitelist_comment( 'override', $assignment ) ) { @@ -304,19 +303,19 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } return; - } - elseif ( T_GLOBAL === $token['code'] ) { - $ptr = $stackPtr + 1; + + } elseif ( T_GLOBAL === $token['code'] ) { + $ptr = ( $stackPtr + 1 ); while ( $ptr ) { $ptr++; $var = $tokens[ $ptr ]; if ( T_VARIABLE === $var['code'] ) { $varname = substr( $var['content'], 1 ); - if ( in_array( $varname, $this->globals ) ) { + if ( in_array( $varname, $this->globals, true ) ) { $search[] = $varname; } } - // Halt the loop + // Halt the loop. if ( T_SEMICOLON === $var['code'] ) { $ptr = false; } @@ -325,10 +324,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - // Check for assignments to collected global vars + // Check for assignments to collected global vars. foreach ( $tokens as $ptr => $token ) { - if ( T_VARIABLE === $token['code'] && in_array( substr( $token['content'], 1 ), $search ) ) { - $next = $phpcsFile->findNext( array( T_WHITESPACE, T_COMMENT ), $ptr + 1, null, true, null, true ); + if ( T_VARIABLE === $token['code'] && in_array( substr( $token['content'], 1 ), $search, true ) ) { + $next = $phpcsFile->findNext( array( T_WHITESPACE, T_COMMENT ), ( $ptr + 1 ), null, true, null, true ); if ( T_EQUAL === $tokens[ $next ]['code'] ) { if ( ! $this->has_whitelist_comment( 'override', $next ) ) { $phpcsFile->addError( 'Overriding WordPress globals is prohibited', $ptr, 'OverrideProhibited' ); diff --git a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php index 7410115fb0..f0b6099530 100644 --- a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php +++ b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php @@ -1,20 +1,19 @@ */ -class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSniffer_Sniff { /** - * Exclude groups + * Exclude groups. * * Example: 'foo,bar' - * - * @var string Comma-delimited group list + * + * @var string Comma-delimited group list. */ public $exclude = ''; @@ -22,7 +21,7 @@ class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSn * Groups of variable data to check against. * Don't use this in extended classes, override getGroups() instead. * This is only used for Unit tests. - * + * * @var array */ public static $groups = array(); @@ -33,20 +32,19 @@ class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSn * * @return array */ - public function register() - { + public function register() { return array( - T_VARIABLE, - T_OBJECT_OPERATOR, - T_DOUBLE_COLON, - T_OPEN_SQUARE_BRACKET, - T_DOUBLE_QUOTED_STRING, - ); + T_VARIABLE, + T_OBJECT_OPERATOR, + T_DOUBLE_COLON, + T_OPEN_SQUARE_BRACKET, + T_DOUBLE_QUOTED_STRING, + ); - }//end register() + } // end register() /** - * Groups of variables to restrict + * Groups of variables to restrict. * This should be overridden in extending classes. * * Example: groups => array( @@ -75,59 +73,54 @@ public function getGroups() { * * @return void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { - $tokens = $phpcsFile->getTokens(); - - $token = $tokens[$stackPtr]; - + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; $exclude = explode( ',', $this->exclude ); - - $groups = $this->getGroups(); + $groups = $this->getGroups(); if ( empty( $groups ) ) { - return count( $tokens ) + 1; + return ( count( $tokens ) + 1 ); } - // Check if it is a function not a variable - if ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ) ) ) { // This only works for object vars and array members - $method = $phpcsFile->findNext( T_WHITESPACE, $stackPtr + 1, null, true ); - $possible_parenthesis = $phpcsFile->findNext( T_WHITESPACE, $method + 1, null, true ); - if ( $tokens[$possible_parenthesis]['code'] == T_OPEN_PARENTHESIS ) { + // Check if it is a function not a variable. + if ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) { // This only works for object vars and array members. + $method = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + $possible_parenthesis = $phpcsFile->findNext( T_WHITESPACE, ( $method + 1 ), null, true ); + if ( T_OPEN_PARENTHESIS === $tokens[ $possible_parenthesis ]['code'] ) { return; // So .. it is a function after all ! } } foreach ( $groups as $groupName => $group ) { - - if ( in_array( $groupName, $exclude ) ) { + + if ( in_array( $groupName, $exclude, true ) ) { continue; } $patterns = array(); - // Simple variable - if ( in_array( $token['code'], array( T_VARIABLE, T_DOUBLE_QUOTED_STRING ) ) && ! empty( $group['variables'] ) ) { + // Simple variable. + if ( in_array( $token['code'], array( T_VARIABLE, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['variables'] ) ) { $patterns = array_merge( $patterns, $group['variables'] ); - $var = $token['content']; - } - // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar - elseif ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_DOUBLE_QUOTED_STRING ) ) && ! empty( $group['object_vars'] ) ) { + $var = $token['content']; + + } elseif ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['object_vars'] ) ) { + // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar $patterns = array_merge( $patterns, $group['object_vars'] ); $owner = $phpcsFile->findPrevious( array( T_VARIABLE, T_STRING ), $stackPtr ); $child = $phpcsFile->findNext( array( T_STRING, T_VAR, T_VARIABLE ), $stackPtr ); - $var = implode( '', array( $tokens[$owner]['content'], $token['content'], $tokens[$child]['content'] ) ); - } - // Array members - elseif ( in_array( $token['code'], array( T_OPEN_SQUARE_BRACKET, T_DOUBLE_QUOTED_STRING ) ) && ! empty( $group['array_members'] ) ) { + $var = implode( '', array( $tokens[ $owner ]['content'], $token['content'], $tokens[ $child ]['content'] ) ); + + } elseif ( in_array( $token['code'], array( T_OPEN_SQUARE_BRACKET, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['array_members'] ) ) { + // Array members. $patterns = array_merge( $patterns, $group['array_members'] ); - $owner = $phpcsFile->findPrevious( array( T_VARIABLE ), $stackPtr ); - $inside = $phpcsFile->getTokensAsString( $stackPtr, $token['bracket_closer'] - $stackPtr + 1 ); - $var = implode( '', array( $tokens[$owner]['content'], $inside ) ); - } - else { + $owner = $phpcsFile->findPrevious( array( T_VARIABLE ), $stackPtr ); + $inside = $phpcsFile->getTokensAsString( $stackPtr, ( $token['bracket_closer'] - $stackPtr + 1 ) ); + $var = implode( '', array( $tokens[ $owner ]['content'], $inside ) ); + } else { continue; } @@ -136,20 +129,18 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) } $patterns = array_map( array( $this, 'test_patterns' ), $patterns ); + $pattern = implode( '|', $patterns ); + $delim = ( T_OPEN_SQUARE_BRACKET !== $token['code'] ) ? '\b' : ''; - $pattern = implode( '|', $patterns ); - - $delim = ( $token['code'] != T_OPEN_SQUARE_BRACKET ) ? '\b' : ''; - - if ( $token['code'] == T_DOUBLE_QUOTED_STRING ) { + if ( T_DOUBLE_QUOTED_STRING === $token['code'] ) { $var = $token['content']; } - if ( preg_match( '#(' . $pattern . ')' . $delim .'#', $var, $match ) < 1 ) { + if ( preg_match( '#(' . $pattern . ')' . $delim . '#', $var, $match ) !== 1 ) { continue; } - if ( $group['type'] == 'warning' ) { + if ( 'warning' === $group['type'] ) { $addWhat = array( $phpcsFile, 'addWarning' ); } else { $addWhat = array( $phpcsFile, 'addError' ); @@ -157,27 +148,25 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) call_user_func( $addWhat, - $group['message'], - $stackPtr, - $groupName, + $group['message'], + $stackPtr, + $groupName, array( $var ) - ); + ); - return; // Show one error only + return; // Show one error only. } - }//end process() - + } // end process() + private function test_patterns( $pattern ) { $pattern = preg_quote( $pattern, '#' ); $pattern = preg_replace( array( '#\\\\\*#', '[\'"]' ), - array( '.*', '\'' ), + array( '.*', '\'' ), $pattern - ); + ); return $pattern; } - - -}//end class +} // end class diff --git a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php index 0f03f844a5..303ed4f67c 100644 --- a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php +++ b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php @@ -8,48 +8,44 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_WP_EnqueuedResourcesSniff implements PHP_CodeSniffer_Sniff -{ - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - return array( - T_CONSTANT_ENCAPSED_STRING, - T_DOUBLE_QUOTED_STRING, - T_INLINE_HTML, - ); - - }//end register() - - - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - $token = $tokens[$stackPtr]; - - if ( preg_match( '#rel=[\'"]?stylesheet[\'"]?#', $token['content'], $matches ) > 0 ) { - $phpcsFile->addError( 'Stylesheets must be registered/enqueued via wp_enqueue_style', $stackPtr, 'NonEnqueuedStylesheet' ); - } - - if ( preg_match( '#]*(?<=src=)#', $token['content'], $matches ) > 0 ) { - $phpcsFile->addError( 'Scripts must be registered/enqueued via wp_enqueue_script', $stackPtr, 'NonEnqueuedScript' ); - } - - }//end process() - - -}//end class +class WordPress_Sniffs_WP_EnqueuedResourcesSniff implements PHP_CodeSniffer_Sniff { + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + T_INLINE_HTML, + ); + + } // end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + + if ( preg_match( '#rel=[\'"]?stylesheet[\'"]?#', $token['content'] ) > 0 ) { + $phpcsFile->addError( 'Stylesheets must be registered/enqueued via wp_enqueue_style', $stackPtr, 'NonEnqueuedStylesheet' ); + } + + if ( preg_match( '#]*(?<=src=)#', $token['content'] ) > 0 ) { + $phpcsFile->addError( 'Scripts must be registered/enqueued via wp_enqueue_script', $stackPtr, 'NonEnqueuedScript' ); + } + + } // end process() + +} // end class diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 0a35fcf935..2bffb14ba4 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -48,9 +48,14 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { '_nx_noop' => 'noopnumber_context', ); - // These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552 + /** + * These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552 + */ static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; - // "Unordered" means there's no position specifier: '%s', not '%2$s' + + /** + * "Unordered" means there's no position specifier: '%s', not '%2$s'. + */ static $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; /** @@ -94,33 +99,33 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { $phpcs_file->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stack_ptr, 'LowLevelTranslationFunction', array( $translation_function ) ); } - $func_open_paren_token = $phpcs_file->findNext( T_WHITESPACE, $stack_ptr + 1, null, true ); + $func_open_paren_token = $phpcs_file->findNext( T_WHITESPACE, ( $stack_ptr + 1 ), null, true ); if ( ! $func_open_paren_token || T_OPEN_PARENTHESIS !== $tokens[ $func_open_paren_token ]['code'] ) { return; } $arguments_tokens = array(); - $argument_tokens = array(); + $argument_tokens = array(); // Look at arguments. - for ( $i = $func_open_paren_token + 1; $i < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $i += 1 ) { - $this_token = $tokens[ $i ]; + for ( $i = ( $func_open_paren_token + 1 ); $i < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $i += 1 ) { + $this_token = $tokens[ $i ]; $this_token['token_index'] = $i; if ( in_array( $this_token['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { continue; } if ( T_COMMA === $this_token['code'] ) { $arguments_tokens[] = $argument_tokens; - $argument_tokens = array(); + $argument_tokens = array(); continue; } // Merge consecutive single or double quoted strings (when they span multiple lines). if ( T_CONSTANT_ENCAPSED_STRING === $this_token['code'] || T_DOUBLE_QUOTED_STRING === $this_token['code'] ) { - for ( $j = $i + 1; $j < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $j += 1 ) { + for ( $j = ( $i + 1 ); $j < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $j += 1 ) { if ( $this_token['code'] === $tokens[ $j ]['code'] ) { $this_token['content'] .= $tokens[ $j ]['content']; - $i = $j; + $i = $j; } else { break; } @@ -130,9 +135,9 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { // Include everything up to and including the parenthesis_closer if this token has one. if ( ! empty( $this_token['parenthesis_closer'] ) ) { - for ( $j = $i + 1; $j <= $this_token['parenthesis_closer']; $j += 1 ) { + for ( $j = ( $i + 1 ); $j <= $this_token['parenthesis_closer']; $j += 1 ) { $tokens[ $j ]['token_index'] = $j; - $argument_tokens[] = $tokens[ $j ]; + $argument_tokens[] = $tokens[ $j ]; } $i = $this_token['parenthesis_closer']; } @@ -198,15 +203,15 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { * Check if supplied tokens represent a translation text string literal. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $context + * @param array $context * @return bool */ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $context ) { $stack_ptr = $context['stack_ptr']; - $tokens = $context['tokens']; - $arg_name = $context['arg_name']; - $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; - $content = $tokens[0]['content']; + $tokens = $context['tokens']; + $arg_name = $context['arg_name']; + $method = empty( $context['warning'] ) ? 'addError' : 'addWarning'; + $content = $tokens[0]['content']; if ( 0 === count( $tokens ) ) { $code = 'MissingArg' . ucfirst( $arg_name ); @@ -225,7 +230,7 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con return false; } - if ( in_array( $arg_name, array( 'text', 'single', 'plural' ) ) ) { + if ( in_array( $arg_name, array( 'text', 'single', 'plural' ), true ) ) { $this->check_text( $phpcs_file, $context ); } @@ -260,9 +265,9 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con /** * Check for inconsistencies between single and plural arguments. * - * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $single_context - * @param array $plural_context + * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. + * @param array $single_context + * @param array $plural_context * @return void */ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $phpcs_file, $stack_ptr, $single_context, $plural_context ) { @@ -294,28 +299,28 @@ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $ph } /** - * Check the string itself for problems + * Check the string itself for problems. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $single_context - * @param array $plural_context + * @param array $context * @return void */ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { - $stack_ptr = $context['stack_ptr']; - $arg_name = $context['arg_name']; - $content = $context['tokens'][0]['content']; + $stack_ptr = $context['stack_ptr']; + $arg_name = $context['arg_name']; + $content = $context['tokens'][0]['content']; $fixable_method = empty( $context['warning'] ) ? 'addFixableError' : 'addFixableWarning'; // UnorderedPlaceholders: Check for multiple unordered placeholders. preg_match_all( self::$unordered_sprintf_placeholder_regex, $content, $unordered_matches ); - $unordered_matches = $unordered_matches[0]; + $unordered_matches = $unordered_matches[0]; + $unordered_matches_count = count( $unordered_matches ); - if ( count( $unordered_matches ) >= 2 ) { + if ( $unordered_matches_count >= 2 ) { $code = 'UnorderedPlaceholders' . ucfirst( $arg_name ); $suggestions = array(); - for ( $i = 0; $i < count( $unordered_matches ); $i++ ) { + for ( $i = 0; $i < $unordered_matches_count; $i++ ) { $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], ( $i + 1 ) . '$', 1, 0 ); } @@ -335,7 +340,7 @@ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { } } - // NoEmptyStrings + // NoEmptyStrings. // Strip placeholders and surrounding quotes. $non_placeholder_content = trim( $content, "'" ); diff --git a/WordPress/Sniffs/WP/PreparedSQLSniff.php b/WordPress/Sniffs/WP/PreparedSQLSniff.php index 97be02e90b..5fe3bf12b1 100644 --- a/WordPress/Sniffs/WP/PreparedSQLSniff.php +++ b/WordPress/Sniffs/WP/PreparedSQLSniff.php @@ -17,12 +17,12 @@ class WordPress_Sniffs_WP_PreparedSQLSniff extends WordPress_Sniff { * @var array */ protected static $methods = array( - 'get_var' => true, - 'get_col' => true, - 'get_row' => true, + 'get_var' => true, + 'get_col' => true, + 'get_row' => true, 'get_results' => true, - 'prepare' => true, - 'query' => true, + 'prepare' => true, + 'query' => true, ); /** @@ -33,16 +33,16 @@ class WordPress_Sniffs_WP_PreparedSQLSniff extends WordPress_Sniff { * @var array */ protected $ignored_tokens = array( - T_OBJECT_OPERATOR => true, - T_OPEN_PARENTHESIS => true, - T_CLOSE_PARENTHESIS => true, - T_WHITESPACE => true, - T_STRING_CONCAT => true, + T_OBJECT_OPERATOR => true, + T_OPEN_PARENTHESIS => true, + T_CLOSE_PARENTHESIS => true, + T_WHITESPACE => true, + T_STRING_CONCAT => true, T_CONSTANT_ENCAPSED_STRING => true, - T_OPEN_SQUARE_BRACKET => true, - T_CLOSE_SQUARE_BRACKET => true, - T_COMMA => true, - T_LNUMBER => true, + T_OPEN_SQUARE_BRACKET => true, + T_CLOSE_SQUARE_BRACKET => true, + T_COMMA => true, + T_LNUMBER => true, ); /** @@ -130,7 +130,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { 'NotPrepared', array( $bad_variable, - $tokens[ $this->i ]['content'] + $tokens[ $this->i ]['content'], ) ); } @@ -152,7 +152,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { ) { // Find the opening parenthesis. - $opening_paren = $this->phpcsFile->findNext( T_WHITESPACE, $this->i + 1, null, true, null, true ); + $opening_paren = $this->phpcsFile->findNext( T_WHITESPACE, ( $this->i + 1 ), null, true, null, true ); if ( $opening_paren @@ -163,7 +163,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->i = $this->tokens[ $opening_paren ]['parenthesis_closer']; continue; } - } elseif ( isset( self::$formattingFunctions[ $tokens[ $this->i ]['content'] ] ) ) { continue; } @@ -199,16 +198,16 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { protected function is_wpdb_method_call( $stackPtr ) { // Check that this is a method call. - $is_object_call = $this->phpcsFile->findNext( array( T_OBJECT_OPERATOR ), $stackPtr + 1, null, null, null, true ); + $is_object_call = $this->phpcsFile->findNext( array( T_OBJECT_OPERATOR ), ( $stackPtr + 1 ), null, null, null, true ); if ( false === $is_object_call ) { return false; } - $methodPtr = $this->phpcsFile->findNext( array( T_WHITESPACE ), $is_object_call + 1, null, true, null, true ); + $methodPtr = $this->phpcsFile->findNext( array( T_WHITESPACE ), ( $is_object_call + 1 ), null, true, null, true ); $method = $this->tokens[ $methodPtr ]['content']; // Find the opening parenthesis. - $opening_paren = $this->phpcsFile->findNext( T_WHITESPACE, $methodPtr + 1, null, true, null, true ); + $opening_paren = $this->phpcsFile->findNext( T_WHITESPACE, ( $methodPtr + 1 ), null, true, null, true ); if ( ! $opening_paren ) { return false; @@ -234,5 +233,4 @@ protected function is_wpdb_method_call( $stackPtr ) { return true; } - } // end class. diff --git a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php index 0c3249b472..9feef002e8 100755 --- a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php @@ -1,8 +1,8 @@ getTokens(); + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); - $content = $tokens[$stackPtr]['content']; - $expected = str_replace(' ', '', $content); - $expected = str_replace("\t", '', $expected); + $content = $tokens[ $stackPtr ]['content']; + $expected = str_replace( ' ', '', $content ); + $expected = str_replace( "\t", '', $expected ); - if ($content !== $expected) { - $error = 'Cast statements must not contain whitespace; expected "%s" but found "%s"'; - $data = array( - $expected, - $content, - ); - $phpcsFile->addWarning($error, $stackPtr, 'ContainsWhiteSpace', $data); - } + if ( $content !== $expected ) { + $error = 'Cast statements must not contain whitespace; expected "%s" but found "%s"'; + $data = array( + $expected, + $content, + ); + $phpcsFile->addWarning( $error, $stackPtr, 'ContainsWhiteSpace', $data ); + } - if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { - $error = 'No space before opening casting parenthesis is prohibited'; - $phpcsFile->addWarning($error, $stackPtr, 'NoSpaceBeforeOpenParenthesis'); - } + if ( T_WHITESPACE !== $tokens[ ( $stackPtr - 1 ) ]['code'] ) { + $error = 'No space before opening casting parenthesis is prohibited'; + $phpcsFile->addWarning( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); + } - if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { - $error = 'No space after closing casting parenthesis is prohibited'; - $phpcsFile->addWarning($error, $stackPtr, 'NoSpaceAfterCloseParenthesis'); - } - }//end process() + if ( T_WHITESPACE !== $tokens[ ( $stackPtr + 1 ) ]['code'] ) { + $error = 'No space after closing casting parenthesis is prohibited'; + $phpcsFile->addWarning( $error, $stackPtr, 'NoSpaceAfterCloseParenthesis' ); + } + } // end process() - /** - * If true, an error will be thrown; otherwise a warning. - * - * @var bool - */ - public $error = false; + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var bool + */ + public $error = false; -}//end class - -?> +} // end class diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index c6dac82308..3fd014f00c 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -1,6 +1,6 @@ blank_line_check = (bool) $this->blank_line_check; - $this->blank_line_after_check = (bool) $this->blank_line_after_check; - - $tokens = $phpcsFile->getTokens(); - - $this->init( $phpcsFile ); - - if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE - && ! ( $tokens[$stackPtr]['code'] === T_ELSE && $tokens[($stackPtr + 1)]['code'] === T_COLON ) - && ! ( - T_CLOSURE === $tokens[ $stackPtr ]['code'] - && ( - 0 === (int) $this->spaces_before_closure_open_paren - || -1 === (int) $this->spaces_before_closure_open_paren - ) - ) - ) { - $error = 'Space after opening control structure is required'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfterStructureOpen'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContent($stackPtr, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'NoSpaceAfterStructureOpen'); - } - } - - if ( isset( $tokens[ $stackPtr ]['scope_closer'] ) === false ) { - - if ( T_USE === $tokens[ $stackPtr ]['code'] && 'closure' === $this->get_use_type( $stackPtr ) ) { - $scopeOpener = $phpcsFile->findNext( T_OPEN_CURLY_BRACKET, $stackPtr + 1 ); - $scopeCloser = $tokens[ $scopeOpener ]['scope_closer']; - } else { - return; - } - - } else { - $scopeOpener = $tokens[ $stackPtr ]['scope_opener']; - $scopeCloser = $tokens[ $stackPtr ]['scope_closer']; - } - - // alternative syntax - if ( $tokens[$scopeOpener]['code'] === T_COLON ) { - - if ( $this->space_before_colon === 'required') { - - if ( $tokens[$scopeOpener - 1]['code'] !== T_WHITESPACE ) { - $error = 'Space between opening control structure and T_COLON is required'; - - if ( isset($phpcsFile->fixer) === true ) { - $fix = $phpcsFile->addFixableError($error, $scopeOpener, 'NoSpaceBetweenStructureColon'); - - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContentBefore($scopeOpener, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'NoSpaceBetweenStructureColon'); - } - } - - } elseif ( $this->space_before_colon === 'forbidden' ) { - - if ( $tokens[$scopeOpener - 1]['code'] === T_WHITESPACE ) { - $error = 'Extra space between opening control structure and T_COLON found'; - - if ( isset($phpcsFile->fixer) === true ) { - $fix = $phpcsFile->addFixableError( $error, $scopeOpener - 1, 'SpaceBetweenStructureColon' ); - - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( $scopeOpener - 1, '' ); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError( $error, $stackPtr, 'SpaceBetweenStructureColon' ); - } - } - } - } - - $parenthesisOpener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true); - - // If this is a function declaration. - if ( $tokens[ $stackPtr ]['code'] === T_FUNCTION ) { - - if ( $tokens[ $parenthesisOpener ]['code'] === T_STRING ) { - - $function_name_ptr = $parenthesisOpener; - - } elseif ( $tokens[ $parenthesisOpener ]['code'] === T_BITWISE_AND ) { - - // This function returns by reference (function &function_name() {}). - $function_name_ptr = $parenthesisOpener = $phpcsFile->findNext( - PHP_CodeSniffer_Tokens::$emptyTokens, - $parenthesisOpener + 1, - null, - true - ); - } - - $parenthesisOpener = $phpcsFile->findNext( - PHP_CodeSniffer_Tokens::$emptyTokens, - $parenthesisOpener + 1, - null, - true - ); - - // Checking this: function my_function[*](...) {} - if ( $parenthesisOpener !== $function_name_ptr + 1 ) { - - $error = 'Space between function name and opening parenthesis is prohibited.'; - $fix = $phpcsFile->addFixableError( - $error, - $stackPtr, - 'SpaceBeforeFunctionOpenParenthesis', - $tokens[ $function_name_ptr + 1 ]['content'] - ); - - if ( true === $fix ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( $function_name_ptr + 1, '' ); - $phpcsFile->fixer->endChangeset(); - } - } - - } elseif ( T_CLOSURE === $tokens[ $stackPtr ]['code'] ) { - - // Check if there is a use () statement. - if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { - - $usePtr = $phpcsFile->findNext( - PHP_CodeSniffer_Tokens::$emptyTokens, - $tokens[ $parenthesisOpener ]['parenthesis_closer'] + 1, - null, - true, - null, - true - ); - - // If it is, we set that as the "scope opener". - if ( T_USE === $tokens[ $usePtr ]['code'] ) { - $scopeOpener = $usePtr; - } - } - } - - if ( - T_COLON !== $tokens[ $parenthesisOpener ]['code'] - && T_FUNCTION !== $tokens[ $stackPtr ]['code'] - ) { - - if ( - T_CLOSURE === $tokens[ $stackPtr ]['code'] - && 0 === (int) $this->spaces_before_closure_open_paren - ) { - - if ( ($stackPtr + 1) !== $parenthesisOpener ) { - // Checking this: function[*](...) {}. - $error = 'Space before closure opening parenthesis is prohibited'; - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpaceBeforeClosureOpenParenthesis' ); - if ( $fix === true ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( $stackPtr + 1, '' ); - $phpcsFile->fixer->endChangeset(); - } - } - - } elseif ( - ( - T_CLOSURE !== $tokens[ $stackPtr ]['code'] - || 1 === (int) $this->spaces_before_closure_open_paren - ) - && ($stackPtr + 1) === $parenthesisOpener - ) { - - // Checking this: if[*](...) {}. - $error = 'No space before opening parenthesis is prohibited'; - if ( isset( $phpcsFile->fixer ) === true ) { - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); - if ( $fix === true ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContent( $stackPtr, ' ' ); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); - } - } - } - - if ( - T_WHITESPACE === $tokens[ $stackPtr + 1 ]['code'] - && ' ' !== $tokens[ $stackPtr + 1 ]['content'] - ) { - // Checking this: if [*](...) {}. - $error = 'Expected exactly one space before opening parenthesis; "%s" found.'; - $fix = $phpcsFile->addFixableError( - $error, - $stackPtr, - 'ExtraSpaceBeforeOpenParenthesis', - $tokens[ $stackPtr + 1 ]['content'] - ); - - if ( true === $fix ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( $stackPtr + 1, ' ' ); - $phpcsFile->fixer->endChangeset(); - } - } - - if ($tokens[($parenthesisOpener + 1)]['code'] !== T_WHITESPACE - && $tokens[($parenthesisOpener + 1)]['code'] !== T_CLOSE_PARENTHESIS - ) { - // Checking this: $value = my_function([*]...). - $error = 'No space after opening parenthesis is prohibited'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfterOpenParenthesis'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContent($parenthesisOpener, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'NoSpaceAfterOpenParenthesis'); - } - } - - if ( isset($tokens[$parenthesisOpener]['parenthesis_closer']) === true ) { - - $parenthesisCloser = $tokens[$parenthesisOpener]['parenthesis_closer']; - - if ( $tokens[($parenthesisOpener + 1)]['code'] !== T_CLOSE_PARENTHESIS ) { - - if ($tokens[($parenthesisCloser - 1)]['code'] !== T_WHITESPACE) { - $error = 'No space before closing parenthesis is prohibited'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $parenthesisCloser, 'NoSpaceBeforeCloseParenthesis'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContentBefore($parenthesisCloser, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $parenthesisCloser, 'NoSpaceBeforeCloseParenthesis'); - } - } - - if ( - $tokens[ $parenthesisCloser + 1 ]['code'] !== T_WHITESPACE - && $tokens[ $scopeOpener ]['code'] !== T_COLON - ) { - $error = 'Space between opening control structure and closing parenthesis is required'; - - if ( isset( $phpcsFile->fixer ) === true ) { - $fix = $phpcsFile->addFixableError( $error, $scopeOpener, 'NoSpaceAfterCloseParenthesis' ); - - if ( $fix === true ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContentBefore( $scopeOpener, ' ' ); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError( $error, $stackPtr, 'NoSpaceAfterCloseParenthesis' ); - } - } - } - - if (isset($tokens[$parenthesisOpener]['parenthesis_owner']) === true - && $tokens[$parenthesisCloser]['line'] !== $tokens[$scopeOpener]['line'] - ) { - $error = 'Opening brace should be on the same line as the declaration'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $parenthesisOpener, 'OpenBraceNotSameLine'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - - for ($i = ($parenthesisCloser + 1); $i < $scopeOpener; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } - - $phpcsFile->fixer->addContent($parenthesisCloser, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $parenthesisOpener, 'OpenBraceNotSameLine'); - }//end if - return; - - } elseif ( - T_WHITESPACE === $tokens[ $parenthesisCloser + 1 ]['code'] - && ' ' !== $tokens[ $parenthesisCloser + 1 ]['content'] - ) { - - // Checking this: if (...) [*]{} - $error = 'Expected exactly one space between closing parenthesis and opening control structure; "%s" found.'; - $fix = $phpcsFile->addFixableError( - $error, - $stackPtr, - 'ExtraSpaceAfterCloseParenthesis', - $tokens[ $parenthesisCloser + 1 ]['content'] - ); - - if ( true === $fix ) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken( $parenthesisCloser + 1, ' ' ); - $phpcsFile->fixer->endChangeset(); - } - } - }//end if - - if ($this->blank_line_check === true) { - $firstContent = $phpcsFile->findNext(T_WHITESPACE, ($scopeOpener + 1), null, true); - if ($tokens[$firstContent]['line'] > ($tokens[$scopeOpener]['line'] + 1) - && in_array($tokens[$firstContent]['code'], array(T_CLOSE_TAG, T_COMMENT)) === false - ) { - $error = 'Blank line found at start of control structure'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $scopeOpener, 'BlankLineAfterStart'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - - for ($i = ($scopeOpener + 1); $i < $firstContent; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } - - $phpcsFile->fixer->addNewline($scopeOpener); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $scopeOpener, 'BlankLineAfterStart'); - } - } - - $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($scopeCloser - 1), null, true); - if ($tokens[$lastContent]['line'] !== ($tokens[$scopeCloser]['line'] - 1)) { - $errorToken = $scopeCloser; - for ($i = ($scopeCloser - 1); $i > $lastContent; $i--) { - if ($tokens[$i]['line'] < $tokens[$scopeCloser]['line'] - && $tokens[$firstContent]['code'] !== T_OPEN_TAG - ) { - // TODO: Reporting error at empty line won't highlight it in IDE. - $error = 'Blank line found at end of control structure'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $i, 'BlankLineBeforeEnd'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - - for ($j = ($lastContent + 1); $j < $scopeCloser; $j++) { - $phpcsFile->fixer->replaceToken($j, ''); - } - - $phpcsFile->fixer->addNewlineBefore($scopeCloser); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $i, 'BlankLineBeforeEnd'); - }//end if - break; - }//end if - }//end for - }//end if - }//end if - - $trailingContent = $phpcsFile->findNext(T_WHITESPACE, ($scopeCloser + 1), null, true); - if ($tokens[$trailingContent]['code'] === T_ELSE) { - if ($tokens[$stackPtr]['code'] === T_IF) { - // IF with ELSE. - return; - } - } - - if ($tokens[$trailingContent]['code'] === T_COMMENT) { - if ($tokens[$trailingContent]['line'] === $tokens[$scopeCloser]['line']) { - if (substr($tokens[$trailingContent]['content'], 0, 5) === '//end') { - // There is an end comment, so we have to get the next piece - // of content. - $trailingContent = $phpcsFile->findNext(T_WHITESPACE, ($trailingContent + 1), null, true); - } - } - } - - if ($tokens[$trailingContent]['code'] === T_BREAK) { - // If this BREAK is closing a CASE, we don't need the - // blank line after this control structure. - if (isset($tokens[$trailingContent]['scope_condition']) === true) { - $condition = $tokens[$trailingContent]['scope_condition']; - if ($tokens[$condition]['code'] === T_CASE || $tokens[$condition]['code'] === T_DEFAULT) { - return; - } - } - } - - if ($tokens[$trailingContent]['code'] === T_CLOSE_TAG) { - // At the end of the script or embedded code. - return; - } - - if ($tokens[$trailingContent]['code'] === T_CLOSE_CURLY_BRACKET) { - // Another control structure's closing brace. - if (isset($tokens[$trailingContent]['scope_condition']) === true) { - $owner = $tokens[$trailingContent]['scope_condition']; - if ($tokens[$owner]['code'] === T_FUNCTION) { - // The next content is the closing brace of a function - // so normal function rules apply and we can ignore it. - return; - } - } - - if ($this->blank_line_after_check === true - && $tokens[$trailingContent]['line'] != ($tokens[$scopeCloser]['line'] + 1) - ) { - // TODO: Won't cover following case: "} echo 'OK';". - $error = 'Blank line found after control structure'; - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $scopeCloser, 'BlankLineAfterEnd'); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - - for ($i = ($scopeCloser + 1); $i < $trailingContent; $i++) { - $phpcsFile->fixer->replaceToken($i, ''); - } - - // TODO: Instead a separate error should be triggered when content comes right after closing brace. - $phpcsFile->fixer->addNewlineBefore($trailingContent); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $scopeCloser, 'BlankLineAfterEnd'); - } - } - }//end if - - }//end process() - - -}//end class - -?> + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_IF, + T_WHILE, + T_FOREACH, + T_FOR, + T_SWITCH, + T_DO, + T_ELSE, + T_ELSEIF, + T_FUNCTION, + T_CLOSURE, + T_USE, + ); + + } // end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $this->blank_line_check = (bool) $this->blank_line_check; + $this->blank_line_after_check = (bool) $this->blank_line_after_check; + + $tokens = $phpcsFile->getTokens(); + + $this->init( $phpcsFile ); + + if ( T_WHITESPACE !== $tokens[ ( $stackPtr + 1) ]['code'] + && ! ( T_ELSE === $tokens[ $stackPtr ]['code'] && T_COLON === $tokens[ ( $stackPtr + 1 ) ]['code'] ) + && ! ( + T_CLOSURE === $tokens[ $stackPtr ]['code'] + && ( + 0 === (int) $this->spaces_before_closure_open_paren + || -1 === (int) $this->spaces_before_closure_open_paren + ) + ) + ) { + $error = 'Space after opening control structure is required'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceAfterStructureOpen' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent( $stackPtr, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceAfterStructureOpen' ); + } + } + + if ( ! isset( $tokens[ $stackPtr ]['scope_closer'] ) ) { + + if ( T_USE === $tokens[ $stackPtr ]['code'] && 'closure' === $this->get_use_type( $stackPtr ) ) { + $scopeOpener = $phpcsFile->findNext( T_OPEN_CURLY_BRACKET, ( $stackPtr + 1 ) ); + $scopeCloser = $tokens[ $scopeOpener ]['scope_closer']; + } else { + return; + } + } else { + $scopeOpener = $tokens[ $stackPtr ]['scope_opener']; + $scopeCloser = $tokens[ $stackPtr ]['scope_closer']; + } + + // Alternative syntax. + if ( T_COLON === $tokens[ $scopeOpener ]['code'] ) { + + if ( 'required' === $this->space_before_colon ) { + + if ( T_WHITESPACE !== $tokens[ ( $scopeOpener - 1 ) ]['code'] ) { + $error = 'Space between opening control structure and T_COLON is required'; + + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $scopeOpener, 'NoSpaceBetweenStructureColon' ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore( $scopeOpener, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceBetweenStructureColon' ); + } + } + } elseif ( 'forbidden' === $this->space_before_colon ) { + + if ( T_WHITESPACE === $tokens[ ( $scopeOpener - 1 ) ]['code'] ) { + $error = 'Extra space between opening control structure and T_COLON found'; + + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, ( $scopeOpener - 1 ), 'SpaceBetweenStructureColon' ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $scopeOpener - 1 ), '' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'SpaceBetweenStructureColon' ); + } + } + } + } + + $parenthesisOpener = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); + + // If this is a function declaration. + if ( T_FUNCTION === $tokens[ $stackPtr ]['code'] ) { + + if ( T_STRING === $tokens[ $parenthesisOpener ]['code'] ) { + + $function_name_ptr = $parenthesisOpener; + + } elseif ( T_BITWISE_AND === $tokens[ $parenthesisOpener ]['code'] ) { + + // This function returns by reference (function &function_name() {}). + $function_name_ptr = $parenthesisOpener = $phpcsFile->findNext( + PHP_CodeSniffer_Tokens::$emptyTokens, + ( $parenthesisOpener + 1 ), + null, + true + ); + } + + $parenthesisOpener = $phpcsFile->findNext( + PHP_CodeSniffer_Tokens::$emptyTokens, + ( $parenthesisOpener + 1 ), + null, + true + ); + + // Checking this: function my_function[*](...) {}. + if ( ( $function_name_ptr + 1 ) !== $parenthesisOpener ) { + + $error = 'Space between function name and opening parenthesis is prohibited.'; + $fix = $phpcsFile->addFixableError( + $error, + $stackPtr, + 'SpaceBeforeFunctionOpenParenthesis', + $tokens[ ( $function_name_ptr + 1 ) ]['content'] + ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $function_name_ptr + 1 ), '' ); + $phpcsFile->fixer->endChangeset(); + } + } + } elseif ( T_CLOSURE === $tokens[ $stackPtr ]['code'] ) { + + // Check if there is a use () statement. + if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { + + $usePtr = $phpcsFile->findNext( + PHP_CodeSniffer_Tokens::$emptyTokens, + ( $tokens[ $parenthesisOpener ]['parenthesis_closer'] + 1 ), + null, + true, + null, + true + ); + + // If it is, we set that as the "scope opener". + if ( T_USE === $tokens[ $usePtr ]['code'] ) { + $scopeOpener = $usePtr; + } + } + } + + if ( + T_COLON !== $tokens[ $parenthesisOpener ]['code'] + && T_FUNCTION !== $tokens[ $stackPtr ]['code'] + ) { + + if ( + T_CLOSURE === $tokens[ $stackPtr ]['code'] + && 0 === (int) $this->spaces_before_closure_open_paren + ) { + + if ( ( $stackPtr + 1) !== $parenthesisOpener ) { + // Checking this: function[*](...) {}. + $error = 'Space before closure opening parenthesis is prohibited'; + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpaceBeforeClosureOpenParenthesis' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $stackPtr + 1 ), '' ); + $phpcsFile->fixer->endChangeset(); + } + } + } elseif ( + ( + T_CLOSURE !== $tokens[ $stackPtr ]['code'] + || 1 === (int) $this->spaces_before_closure_open_paren + ) + && ( $stackPtr + 1 ) === $parenthesisOpener + ) { + + // Checking this: if[*](...) {}. + $error = 'No space before opening parenthesis is prohibited'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent( $stackPtr, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); + } + } + } + + if ( + T_WHITESPACE === $tokens[ ( $stackPtr + 1 ) ]['code'] + && ' ' !== $tokens[ ( $stackPtr + 1 ) ]['content'] + ) { + // Checking this: if [*](...) {}. + $error = 'Expected exactly one space before opening parenthesis; "%s" found.'; + $fix = $phpcsFile->addFixableError( + $error, + $stackPtr, + 'ExtraSpaceBeforeOpenParenthesis', + $tokens[ ( $stackPtr + 1 ) ]['content'] + ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $stackPtr + 1 ), ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } + + if ( T_WHITESPACE !== $tokens[ ( $parenthesisOpener + 1) ]['code'] + && T_CLOSE_PARENTHESIS !== $tokens[ ( $parenthesisOpener + 1) ]['code'] + ) { + // Checking this: $value = my_function([*]...). + $error = 'No space after opening parenthesis is prohibited'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceAfterOpenParenthesis' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent( $parenthesisOpener, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceAfterOpenParenthesis' ); + } + } + + if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { + + $parenthesisCloser = $tokens[ $parenthesisOpener ]['parenthesis_closer']; + + if ( T_CLOSE_PARENTHESIS !== $tokens[ ( $parenthesisOpener + 1 ) ]['code'] ) { + + if ( T_WHITESPACE !== $tokens[ ( $parenthesisCloser - 1 ) ]['code'] ) { + $error = 'No space before closing parenthesis is prohibited'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $parenthesisCloser, 'NoSpaceBeforeCloseParenthesis' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore( $parenthesisCloser, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $parenthesisCloser, 'NoSpaceBeforeCloseParenthesis' ); + } + } + + if ( + T_WHITESPACE !== $tokens[ ( $parenthesisCloser + 1 ) ]['code'] + && T_COLON !== $tokens[ $scopeOpener ]['code'] + ) { + $error = 'Space between opening control structure and closing parenthesis is required'; + + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $scopeOpener, 'NoSpaceAfterCloseParenthesis' ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore( $scopeOpener, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceAfterCloseParenthesis' ); + } + } + } + + if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_owner'] ) + && $tokens[ $parenthesisCloser ]['line'] !== $tokens[ $scopeOpener ]['line'] + ) { + $error = 'Opening brace should be on the same line as the declaration'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $parenthesisOpener, 'OpenBraceNotSameLine' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + + for ( $i = ( $parenthesisCloser + 1 ); $i < $scopeOpener; $i++ ) { + $phpcsFile->fixer->replaceToken( $i, '' ); + } + + $phpcsFile->fixer->addContent( $parenthesisCloser, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $parenthesisOpener, 'OpenBraceNotSameLine' ); + } // end if + return; + + } elseif ( + T_WHITESPACE === $tokens[ ( $parenthesisCloser + 1 ) ]['code'] + && ' ' !== $tokens[ ( $parenthesisCloser + 1 ) ]['content'] + ) { + + // Checking this: if (...) [*]{}. + $error = 'Expected exactly one space between closing parenthesis and opening control structure; "%s" found.'; + $fix = $phpcsFile->addFixableError( + $error, + $stackPtr, + 'ExtraSpaceAfterCloseParenthesis', + $tokens[ ( $parenthesisCloser + 1 ) ]['content'] + ); + + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $parenthesisCloser + 1 ), ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } + } // end if + + if ( true === $this->blank_line_check ) { + $firstContent = $phpcsFile->findNext( T_WHITESPACE, ( $scopeOpener + 1 ), null, true ); + if ( $tokens[ $firstContent ]['line'] > ( $tokens[ $scopeOpener ]['line'] + 1 ) + && false === in_array( $tokens[ $firstContent ]['code'], array( T_CLOSE_TAG, T_COMMENT ), true ) + ) { + $error = 'Blank line found at start of control structure'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $scopeOpener, 'BlankLineAfterStart' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + + for ( $i = ( $scopeOpener + 1 ); $i < $firstContent; $i++ ) { + $phpcsFile->fixer->replaceToken( $i, '' ); + } + + $phpcsFile->fixer->addNewline( $scopeOpener ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $scopeOpener, 'BlankLineAfterStart' ); + } + } + + $lastContent = $phpcsFile->findPrevious( T_WHITESPACE, ( $scopeCloser - 1 ), null, true ); + if ( ( $tokens[ $scopeCloser ]['line'] - 1 ) !== $tokens[ $lastContent ]['line'] ) { + $errorToken = $scopeCloser; + for ( $i = ( $scopeCloser - 1 ); $i > $lastContent; $i-- ) { + if ( $tokens[ $i ]['line'] < $tokens[ $scopeCloser ]['line'] + && T_OPEN_TAG !== $tokens[ $firstContent ]['code'] + ) { + // TODO: Reporting error at empty line won't highlight it in IDE. + $error = 'Blank line found at end of control structure'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $i, 'BlankLineBeforeEnd' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + + for ( $j = ( $lastContent + 1 ); $j < $scopeCloser; $j++ ) { + $phpcsFile->fixer->replaceToken( $j, '' ); + } + + $phpcsFile->fixer->addNewlineBefore( $scopeCloser ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $i, 'BlankLineBeforeEnd' ); + } // end if + break; + } // end if + } // end for + } // end if + } // end if + + $trailingContent = $phpcsFile->findNext( T_WHITESPACE, ( $scopeCloser + 1 ), null, true ); + if ( T_ELSE === $tokens[ $trailingContent ]['code'] ) { + if ( T_IF === $tokens[ $stackPtr ]['code'] ) { + // IF with ELSE. + return; + } + } + + if ( T_COMMENT === $tokens[ $trailingContent ]['code'] ) { + if ( $tokens[ $trailingContent ]['line'] === $tokens[ $scopeCloser ]['line'] ) { + if ( '//end' === substr( $tokens[ $trailingContent ]['content'], 0, 5 ) ) { + // There is an end comment, so we have to get the next piece + // of content. + $trailingContent = $phpcsFile->findNext( T_WHITESPACE, ( $trailingContent + 1), null, true ); + } + } + } + + if ( T_BREAK === $tokens[ $trailingContent ]['code'] ) { + // If this BREAK is closing a CASE, we don't need the + // blank line after this control structure. + if ( isset( $tokens[ $trailingContent ]['scope_condition'] ) ) { + $condition = $tokens[ $trailingContent ]['scope_condition']; + if ( T_CASE === $tokens[ $condition ]['code'] || T_DEFAULT === $tokens[ $condition ]['code'] ) { + return; + } + } + } + + if ( T_CLOSE_TAG === $tokens[ $trailingContent ]['code'] ) { + // At the end of the script or embedded code. + return; + } + + if ( T_CLOSE_CURLY_BRACKET === $tokens[ $trailingContent ]['code'] ) { + // Another control structure's closing brace. + if ( isset( $tokens[ $trailingContent ]['scope_condition'] ) ) { + $owner = $tokens[ $trailingContent ]['scope_condition']; + if ( T_FUNCTION === $tokens[ $owner ]['code'] ) { + // The next content is the closing brace of a function + // so normal function rules apply and we can ignore it. + return; + } + } + + if ( true === $this->blank_line_after_check + && ( $tokens[ $scopeCloser ]['line'] + 1 ) !== $tokens[ $trailingContent ]['line'] + ) { + // TODO: Won't cover following case: "} echo 'OK';". + $error = 'Blank line found after control structure'; + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $scopeCloser, 'BlankLineAfterEnd' ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + + for ( $i = ( $scopeCloser + 1 ); $i < $trailingContent; $i++ ) { + $phpcsFile->fixer->replaceToken( $i, '' ); + } + + // TODO: Instead a separate error should be triggered when content comes right after closing brace. + $phpcsFile->fixer->addNewlineBefore( $trailingContent ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $scopeCloser, 'BlankLineAfterEnd' ); + } + } + } // end if + + } // end process() + +} // end class diff --git a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php index be7b5aa4e1..fa5894df3d 100644 --- a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -18,197 +18,192 @@ * @author Greg Sherwood * @author Marc McIntyre */ -class WordPress_Sniffs_WhiteSpace_OperatorSpacingSniff implements PHP_CodeSniffer_Sniff -{ - - /** - * A list of tokenizers this sniff supports. - * - * @var array - */ - public $supportedTokenizers = array( - 'PHP', - 'JS', - ); - - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() - { - $comparison = PHP_CodeSniffer_Tokens::$comparisonTokens; - $operators = PHP_CodeSniffer_Tokens::$operators; - $assignment = PHP_CodeSniffer_Tokens::$assignmentTokens; - - $tokens = array_unique(array_merge($comparison, $operators, $assignment)); - $tokens[] = T_BOOLEAN_NOT; - - return $tokens; - - }//end register() - - - /** - * Processes this sniff, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The current file being checked. - * @param int $stackPtr The position of the current token in the - * stack passed in $tokens. - * - * @return void - */ - public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) - { - $tokens = $phpcsFile->getTokens(); - - if ($tokens[$stackPtr]['code'] === T_EQUAL) { - // Skip for '=&' case. - if (isset($tokens[($stackPtr + 1)]) === true && $tokens[($stackPtr + 1)]['code'] === T_BITWISE_AND) { - return; - } - - // Skip default values in function declarations. - if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { - $bracket = end($tokens[$stackPtr]['nested_parenthesis']); - if (isset($tokens[$bracket]['parenthesis_owner']) === true) { - $function = $tokens[$bracket]['parenthesis_owner']; - if ($tokens[$function]['code'] === T_FUNCTION) { - return; - } - } - } - } - - if ($tokens[$stackPtr]['code'] === T_BITWISE_AND) { - // If its not a reference, then we expect one space either side of the - // bitwise operator. - if ($phpcsFile->isReference($stackPtr) === false) { - - }//end if - } else { - if ($tokens[$stackPtr]['code'] === T_MINUS) { - // Check minus spacing, but make sure we aren't just assigning - // a minus value or returning one. - $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); - if ($tokens[$prev]['code'] === T_RETURN) { - // Just returning a negative value; eg. return -1. - return; - } - - if (in_array($tokens[$prev]['code'], PHP_CodeSniffer_Tokens::$operators) === true) { - // Just trying to operate on a negative value; eg. ($var * -1). - return; - } - - if (in_array($tokens[$prev]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens) === true) { - // Just trying to compare a negative value; eg. ($var === -1). - return; - } - - // A list of tokens that indicate that the token is not - // part of an arithmetic operation. - $invalidTokens = array( - T_COMMA, - T_OPEN_PARENTHESIS, - T_OPEN_SQUARE_BRACKET, - ); - - if (in_array($tokens[$prev]['code'], $invalidTokens) === true) { - // Just trying to use a negative value; eg. myFunction($var, -2). - return; - } - - $number = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); - if ($tokens[$number]['code'] === T_LNUMBER) { - $semi = $phpcsFile->findNext(T_WHITESPACE, ($number + 1), null, true); - if ($tokens[$semi]['code'] === T_SEMICOLON) { - if ($prev !== false && (in_array($tokens[$prev]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens) === true)) { - // This is a negative assignment. - return; - } - } - } - }//end if - - $operator = $tokens[$stackPtr]['content']; - - if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { - $error = 'Expected 1 space before "%s"; 0 found'; - $data = array($operator); - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBefore', $data); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContentBefore($stackPtr, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'NoSpaceBefore', $data); - } - } else if (strlen($tokens[($stackPtr - 1)]['content']) !== 1 && $tokens[($stackPtr - 1)]['column'] !== 1) { - // Don't throw an error for assignments, because other standards allow - // multiple spaces there to align multiple assignments. - if (in_array($tokens[$stackPtr]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens) === false) { - $found = strlen($tokens[($stackPtr - 1)]['content']); - $error = 'Expected 1 space before "%s"; %s found'; - $data = array( - $operator, - $found, - ); - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBefore', $data); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'SpacingBefore', $data); - } - } - }//end if - - if ($operator !== '-') { - if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { - $error = 'Expected 1 space after "%s"; 0 found'; - $data = array($operator); - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfter', $data); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContent($stackPtr, ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'NoSpaceAfter', $data); - } - } else if (strlen($tokens[($stackPtr + 1)]['content']) !== 1) { - $found = strlen($tokens[($stackPtr + 1)]['content']); - $error = 'Expected 1 space after "%s"; %s found'; - $data = array( - $operator, - $found, - ); - if (isset($phpcsFile->fixer) === true) { - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfter', $data); - if ($fix === true) { - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); - $phpcsFile->fixer->endChangeset(); - } - } else { - $phpcsFile->addError($error, $stackPtr, 'SpacingAfter', $data); - } - }//end if - }//end if - }//end if - - }//end process() - - -}//end class - -?> +class WordPress_Sniffs_WhiteSpace_OperatorSpacingSniff implements PHP_CodeSniffer_Sniff { + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = array( + 'PHP', + 'JS', + ); + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + $comparison = PHP_CodeSniffer_Tokens::$comparisonTokens; + $operators = PHP_CodeSniffer_Tokens::$operators; + $assignment = PHP_CodeSniffer_Tokens::$assignmentTokens; + + $tokens = array_unique( array_merge( $comparison, $operators, $assignment ) ); + $tokens[] = T_BOOLEAN_NOT; + + return $tokens; + + } // end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + + if ( T_EQUAL === $tokens[ $stackPtr ]['code'] ) { + // Skip for '=&' case. + if ( isset( $tokens[ ( $stackPtr + 1 ) ] ) && T_BITWISE_AND === $tokens[ ( $stackPtr + 1 ) ]['code'] ) { + return; + } + + // Skip default values in function declarations. + if ( isset( $tokens[ $stackPtr ]['nested_parenthesis'] ) ) { + $bracket = end( $tokens[ $stackPtr ]['nested_parenthesis'] ); + if ( isset( $tokens[ $bracket ]['parenthesis_owner'] ) ) { + $function = $tokens[ $bracket ]['parenthesis_owner']; + if ( T_FUNCTION === $tokens[ $function ]['code'] ) { + return; + } + } + } + } + + if ( T_BITWISE_AND === $tokens[ $stackPtr ]['code'] ) { + // If its not a reference, then we expect one space either side of the + // bitwise operator. + if ( false === $phpcsFile->isReference( $stackPtr ) ) { + // @todo Implement ? + + } // end if + } else { + if ( T_MINUS === $tokens[ $stackPtr ]['code'] ) { + // Check minus spacing, but make sure we aren't just assigning + // a minus value or returning one. + $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true ); + if ( T_RETURN === $tokens[ $prev ]['code'] ) { + // Just returning a negative value; eg. return -1. + return; + } + + if ( in_array( $tokens[ $prev ]['code'], PHP_CodeSniffer_Tokens::$operators, true ) ) { + // Just trying to operate on a negative value; eg. ($var * -1). + return; + } + + if ( in_array( $tokens[ $prev ]['code'], PHP_CodeSniffer_Tokens::$comparisonTokens, true ) ) { + // Just trying to compare a negative value; eg. ($var === -1). + return; + } + + // A list of tokens that indicate that the token is not + // part of an arithmetic operation. + $invalidTokens = array( + T_COMMA, + T_OPEN_PARENTHESIS, + T_OPEN_SQUARE_BRACKET, + ); + + if ( in_array( $tokens[ $prev ]['code'], $invalidTokens, true ) ) { + // Just trying to use a negative value; eg. myFunction($var, -2). + return; + } + + $number = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + if ( T_LNUMBER === $tokens[ $number ]['code'] ) { + $semi = $phpcsFile->findNext( T_WHITESPACE, ( $number + 1 ), null, true ); + if ( T_SEMICOLON === $tokens[ $semi ]['code'] ) { + if ( false !== $prev && in_array( $tokens[ $prev ]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens, true ) ) { + // This is a negative assignment. + return; + } + } + } + } // end if + + $operator = $tokens[ $stackPtr ]['content']; + + if ( T_WHITESPACE !== $tokens[ ( $stackPtr - 1 ) ]['code'] ) { + $error = 'Expected 1 space before "%s"; 0 found'; + $data = array( $operator ); + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceBefore', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore( $stackPtr, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceBefore', $data ); + } + } elseif ( 1 !== strlen( $tokens[ ( $stackPtr - 1 ) ]['content'] ) && 1 !== $tokens[ ( $stackPtr - 1 ) ]['column'] ) { + // Don't throw an error for assignments, because other standards allow + // multiple spaces there to align multiple assignments. + if ( false === in_array( $tokens[ $stackPtr ]['code'], PHP_CodeSniffer_Tokens::$assignmentTokens, true ) ) { + $found = strlen( $tokens[ ( $stackPtr - 1 ) ]['content'] ); + $error = 'Expected 1 space before "%s"; %s found'; + $data = array( + $operator, + $found, + ); + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpacingBefore', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $stackPtr - 1 ), ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'SpacingBefore', $data ); + } + } + } // end if + + if ( '-' !== $operator ) { + if ( T_WHITESPACE !== $tokens[ ( $stackPtr + 1 ) ]['code'] ) { + $error = 'Expected 1 space after "%s"; 0 found'; + $data = array( $operator ); + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceAfter', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent( $stackPtr, ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'NoSpaceAfter', $data ); + } + } elseif ( 1 !== strlen( $tokens[ ( $stackPtr + 1 ) ]['content'] ) ) { + $found = strlen( $tokens[ ( $stackPtr + 1 ) ]['content'] ); + $error = 'Expected 1 space after "%s"; %s found'; + $data = array( + $operator, + $found, + ); + if ( isset( $phpcsFile->fixer ) ) { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'SpacingAfter', $data ); + if ( true === $fix ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( ( $stackPtr + 1 ), ' ' ); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError( $error, $stackPtr, 'SpacingAfter', $data ); + } + } // end if + } // end if + } // end if + + } // end process() + +} // end class diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 6381134ee6..71db6ae524 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -17,8 +17,7 @@ * @author Weston Ruter * @link http://codex.wordpress.org/Data_Validation Data Validation on WordPress Codex */ -class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff -{ +class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { /** * Custom list of functions which escape values for output. @@ -65,7 +64,7 @@ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff * @var array */ public static $unsafePrintingFunctions = array( - '_e' => 'esc_html_e() or esc_attr_e()', + '_e' => 'esc_html_e() or esc_attr_e()', '_ex' => 'esc_html_ex() or esc_attr_ex()', ); @@ -76,13 +75,13 @@ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff */ public static $addedCustomFunctions = false; + /** * Returns an array of tokens this test wants to listen for. * * @return array */ - public function register() - { + public function register() { return array( T_ECHO, T_PRINT, @@ -90,7 +89,7 @@ public function register() T_STRING, ); - }//end register() + } // end register() /** @@ -102,13 +101,12 @@ public function register() * * @return int|void */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) - { + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Merge any custom functions with the defaults, if we haven't already. if ( ! self::$addedCustomFunctions ) { - WordPress_Sniff::$escapingFunctions = array_merge( WordPress_Sniff::$escapingFunctions, array_flip( $this->customEscapingFunctions ) ); + WordPress_Sniff::$escapingFunctions = array_merge( WordPress_Sniff::$escapingFunctions, array_flip( $this->customEscapingFunctions ) ); WordPress_Sniff::$autoEscapedFunctions = array_merge( WordPress_Sniff::$autoEscapedFunctions, array_flip( $this->customAutoEscapedFunctions ) ); - WordPress_Sniff::$printingFunctions = array_merge( WordPress_Sniff::$printingFunctions, array_flip( $this->customPrintingFunctions ) ); + WordPress_Sniff::$printingFunctions = array_merge( WordPress_Sniff::$printingFunctions, array_flip( $this->customPrintingFunctions ) ); if ( ! empty( $this->customSanitizingFunctions ) ) { WordPress_Sniff::$escapingFunctions = array_merge( WordPress_Sniff::$escapingFunctions, array_flip( $this->customSanitizingFunctions ) ); @@ -124,10 +122,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $function = $tokens[ $stackPtr ]['content']; // Find the opening parenthesis (if present; T_ECHO might not have it). - $open_paren = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true ); + $open_paren = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); - // If function, not T_ECHO nor T_PRINT - if ( $tokens[$stackPtr]['code'] == T_STRING ) { + // If function, not T_ECHO nor T_PRINT. + if ( T_STRING === $tokens[ $stackPtr ]['code'] ) { // Skip if it is a function but is not of the printing functions. if ( ! isset( self::$printingFunctions[ $tokens[ $stackPtr ]['content'] ] ) ) { return; @@ -138,12 +136,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) } // These functions only need to have the first argument escaped. - if ( in_array( $function, array( 'trigger_error', 'user_error' ) ) ) { + if ( in_array( $function, array( 'trigger_error', 'user_error' ), true ) ) { $end_of_statement = $phpcsFile->findEndOfStatement( $open_paren + 1 ); } } - // Checking for the ignore comment, ex: //xss ok + // Checking for the ignore comment, ex: //xss ok. if ( $this->has_whitelist_comment( 'xss', $stackPtr ) ) { return; } @@ -163,7 +161,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) if ( ! isset( $end_of_statement ) ) { $end_of_statement = $phpcsFile->findNext( array( T_SEMICOLON, T_CLOSE_TAG ), $stackPtr ); - $last_token = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, $end_of_statement - 1, null, true ); + $last_token = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $end_of_statement - 1 ), null, true ); // Check for the ternary operator. We only need to do this here if this // echo is lacking parenthesis. Otherwise it will be handled below. @@ -184,12 +182,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) $in_cast = false; - // looping through echo'd components + // Looping through echo'd components. $watch = true; for ( $i = $stackPtr; $i < $end_of_statement; $i++ ) { // Ignore whitespaces and comments. - if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMENT ) ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { continue; } @@ -208,7 +206,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) if ( $ternary ) { - $next_paren = $phpcsFile->findNext( T_OPEN_PARENTHESIS, $i + 1, $tokens[ $i ]['parenthesis_closer'] ); + $next_paren = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $i + 1 ), $tokens[ $i ]['parenthesis_closer'] ); // We only do it if the ternary isn't within a subset of parentheses. if ( ! $next_paren || $ternary > $tokens[ $next_paren ]['parenthesis_closer'] ) { @@ -221,52 +219,53 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) } // Handle arrays for those functions that accept them. - if ( $tokens[ $i ]['code'] === T_ARRAY ) { + if ( T_ARRAY === $tokens[ $i ]['code'] ) { $i++; // Skip the opening parenthesis. continue; } - if ( in_array( $tokens[ $i ]['code'], array( T_DOUBLE_ARROW, T_CLOSE_PARENTHESIS ) ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_DOUBLE_ARROW, T_CLOSE_PARENTHESIS ), true ) ) { continue; } // Handle magic constants for debug functions. - if ( in_array( $tokens[ $i ]['code'], array( T_METHOD_C, T_FUNC_C, T_FILE, T_CLASS_C ) ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_METHOD_C, T_FUNC_C, T_FILE, T_CLASS_C ), true ) ) { continue; } - // Wake up on concatenation characters, another part to check - if ( in_array( $tokens[$i]['code'], array( T_STRING_CONCAT ) ) ) { + // Wake up on concatenation characters, another part to check. + if ( in_array( $tokens[ $i ]['code'], array( T_STRING_CONCAT ), true ) ) { $watch = true; continue; } // Wake up after a ternary else (:). - if ( $ternary && in_array( $tokens[$i]['code'], array( T_INLINE_ELSE ) ) ) { + if ( $ternary && in_array( $tokens[ $i ]['code'], array( T_INLINE_ELSE ), true ) ) { $watch = true; continue; } // Wake up for commas. - if ( $tokens[ $i ]['code'] === T_COMMA ) { + if ( T_COMMA === $tokens[ $i ]['code'] ) { $in_cast = false; - $watch = true; + $watch = true; continue; } - if ( $watch === false ) + if ( false === $watch ) { continue; + } // Allow T_CONSTANT_ENCAPSED_STRING eg: echo 'Some String'; // Also T_LNUMBER, e.g.: echo 45; exit -1; and booleans. - if ( in_array( $tokens[$i]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_MINUS, T_TRUE, T_FALSE, T_NULL ) ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_MINUS, T_TRUE, T_FALSE, T_NULL ), true ) ) { continue; } $watch = false; - // Allow int/double/bool casted variables - if ( in_array( $tokens[$i]['code'], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ) ) ) { + // Allow int/double/bool casted variables. + if ( in_array( $tokens[ $i ]['code'], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { $in_cast = true; continue; } @@ -274,12 +273,9 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) // Now check that next token is a function call. if ( T_STRING === $this->tokens[ $i ]['code'] ) { - $ptr = $i; - - $functionName = $this->tokens[ $i ]['content']; - - $function_opener = $this->phpcsFile->findNext( array( T_OPEN_PARENTHESIS ), $i + 1, null, null, null, true ); - + $ptr = $i; + $functionName = $this->tokens[ $i ]['content']; + $function_opener = $this->phpcsFile->findNext( array( T_OPEN_PARENTHESIS ), ( $i + 1 ), null, null, null, true ); $is_formatting_function = isset( self::$formattingFunctions[ $functionName ] ); if ( $function_opener ) { @@ -289,7 +285,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) // Get the first parameter (name of function being used on the array). $mapped_function = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - $function_opener + 1, + ( $function_opener + 1 ), $tokens[ $function_opener ]['parenthesis_closer'], true ); @@ -305,7 +301,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) // If this is a formatting function we just skip over the opening // parenthesis. Otherwise we skip all the way to the closing. if ( $is_formatting_function ) { - $i = $function_opener + 1; + $i = ( $function_opener + 1 ); $watch = true; } else { $i = $this->tokens[ $function_opener ]['parenthesis_closer']; @@ -325,7 +321,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) } else { $content = $this->tokens[ $i ]['content']; - $ptr = $i; + $ptr = $i; } $this->phpcsFile->addError( @@ -338,8 +334,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) return $end_of_statement; - }//end process() - -}//end class + } // end process() -?> +} // end class From f986a923126c0e7e26663385e7fa18acba054031 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 13:39:22 +0200 Subject: [PATCH 057/122] Code style adjustments for all unit tests to comply with WordPress-Core standard. (Not the tests themselves as those are supposed to contain code which will fail.) --- .../ArrayAssignmentRestrictionsUnitTest.php | 80 +++++---- .../Tests/Arrays/ArrayDeclarationUnitTest.php | 72 ++++---- .../ArrayKeySpacingRestrictionsUnitTest.php | 15 +- .../Tests/CSRF/NonceVerificationUnitTest.php | 5 +- .../Tests/Classes/ValidClassNameUnitTest.php | 71 ++++---- WordPress/Tests/Files/FileNameUnitTest.php | 67 ++++---- .../ValidFunctionNameUnitTest.php | 63 ++++--- .../ValidVariableNameUnitTest.php | 8 +- .../PHP/DiscouragedFunctionsUnitTest.php | 103 ++++++------ .../Tests/PHP/StrictComparisonsUnitTest.php | 73 ++++---- .../Tests/PHP/YodaConditionsUnitTest.php | 83 +++++----- .../Tests/VIP/AdminBarRemovalUnitTest.php | 72 ++++---- WordPress/Tests/VIP/CronIntervalUnitTest.php | 66 ++++---- .../Tests/VIP/DirectDatabaseQueryUnitTest.php | 21 +-- .../VIP/FileSystemWritesDisallowUnitTest.php | 21 +-- WordPress/Tests/VIP/OrderByRandUnitTest.php | 58 +++---- .../Tests/VIP/PluginMenuSlugUnitTest.php | 59 +++---- WordPress/Tests/VIP/PostsPerPageUnitTest.php | 67 ++++---- .../Tests/VIP/RestrictedFunctionsUnitTest.php | 156 +++++++++--------- .../Tests/VIP/RestrictedVariablesUnitTest.php | 22 +-- .../VIP/SessionFunctionsUsageUnitTest.php | 21 +-- .../VIP/SessionVariableUsageUnitTest.php | 21 +-- WordPress/Tests/VIP/SlowDBQueryUnitTest.php | 81 +++++---- .../VIP/SuperGlobalInputUsageUnitTest.php | 24 +-- .../Tests/VIP/TimezoneChangeUnitTest.php | 21 +-- .../VIP/ValidatedSanitizedInputUnitTest.php | 19 +-- .../Variables/GlobalVariablesUnitTest.php | 20 +-- .../VariableRestrictionsUnitTest.php | 85 +++++----- .../Tests/WP/EnqueuedResourcesUnitTest.php | 101 ++++++------ WordPress/Tests/WP/I18nUnitTest.php | 9 +- WordPress/Tests/WP/PreparedSQLUnitTest.php | 5 +- .../CastStructureSpacingUnitTest.php | 71 ++++---- .../ControlStructureSpacingUnitTest.php | 133 ++++++++------- .../WhiteSpace/OperatorSpacingUnitTest.php | 65 ++++---- WordPress/Tests/XSS/EscapeOutputUnitTest.php | 55 +++--- 35 files changed, 871 insertions(+), 1042 deletions(-) diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php index 259212372e..98c6c838f1 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php @@ -7,57 +7,53 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_Arrays_ArrayAssignmentRestrictionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_Arrays_ArrayAssignmentRestrictionsUnitTest extends AbstractSniffUnitTest { protected function setUp() { parent::setUp(); WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff::$groups = array( 'posts_per_page' => array( - 'type' => 'error', + 'type' => 'error', 'message' => 'Found assignment value of %s to be %s', - 'keys' => array( + 'keys' => array( 'foo', 'bar', - ), ), - ); + ), + ); } - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 5 => 1, - 7 => 2, - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - ); - - }//end getWarningList() - - -}//end class + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 5 => 1, + 7 => 2, + ); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php index 3d5a98363c..1629e8cde7 100644 --- a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php @@ -28,49 +28,41 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_Arrays_ArrayDeclarationUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_Arrays_ArrayDeclarationUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 7 => 1, + 9 => 1, + 12 => 2, + 16 => 1, + 40 => 2, + 208 => 2, + ); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 7 => 1, - 9 => 1, - 12 => 2, - 16 => 1, - 40 => 2, - 208 => 2, - ); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - ); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php index ec6d607377..d669037d4c 100644 --- a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php @@ -7,8 +7,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_Arrays_ArrayKeySpacingRestrictionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_Arrays_ArrayKeySpacingRestrictionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -18,8 +17,7 @@ class WordPress_Tests_Arrays_ArrayKeySpacingRestrictionsUnitTest extends Abstrac * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 4 => 1, 5 => 1, @@ -35,7 +33,7 @@ public function getErrorList() 29 => 1, 31 => 1, ); - }//end getErrorList() + } // end getErrorList() /** @@ -46,10 +44,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() + } // end getWarningList() -}//end class +} // end class diff --git a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php index 75642783f1..8ebc4fe683 100644 --- a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php +++ b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php @@ -34,7 +34,8 @@ public function getErrorList() { 113 => 1, 114 => 1, ); - } + } // end getErrorList() + /** * Returns the lines where warnings should occur. @@ -46,6 +47,6 @@ public function getErrorList() { */ public function getWarningList() { return array(); - } + } // end getWarningList() } // end class diff --git a/WordPress/Tests/Classes/ValidClassNameUnitTest.php b/WordPress/Tests/Classes/ValidClassNameUnitTest.php index df65840846..b493583c10 100644 --- a/WordPress/Tests/Classes/ValidClassNameUnitTest.php +++ b/WordPress/Tests/Classes/ValidClassNameUnitTest.php @@ -28,42 +28,35 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_Classes_ValidClassNameUnitTest extends AbstractSniffUnitTest -{ - - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 7 => 1, - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - - }//end getWarningList() - - -}//end class - -?> +class WordPress_Tests_Classes_ValidClassNameUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 7 => 1, + ); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/Files/FileNameUnitTest.php b/WordPress/Tests/Files/FileNameUnitTest.php index e5f3f094c2..74ab070b35 100644 --- a/WordPress/Tests/Files/FileNameUnitTest.php +++ b/WordPress/Tests/Files/FileNameUnitTest.php @@ -28,40 +28,33 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_Files_FileNameUnitTest extends AbstractSniffUnitTest -{ - - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array(); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - - }//end getWarningList() - - -}//end class - -?> +class WordPress_Tests_Files_FileNameUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array(); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php index c7497358ab..64879dd601 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php @@ -28,44 +28,37 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_NamingConventions_ValidFunctionNameUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_NamingConventions_ValidFunctionNameUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 13 => 1, + 15 => 1, + ); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 13 => 1, - 15 => 1, - ); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index 8429922e21..5c2ace9a42 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -87,7 +87,8 @@ public function getErrorList() { return $errors; - }//end getErrorList() + } // end getErrorList() + /** * Returns the lines where warnings should occur. @@ -99,5 +100,6 @@ public function getErrorList() { */ public function getWarningList() { return array(); - } -}//end class + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php index 884a08f884..e85d87443a 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php @@ -28,64 +28,57 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_PHP_DiscouragedFunctionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_PHP_DiscouragedFunctionsUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array(); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array(); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 8 => 1, + 9 => 1, + 17 => 1, + 20 => 1, + 23 => 1, + 25 => 1, + 27 => 1, + 33 => 1, + 35 => 1, + 37 => 1, + 39 => 1, + 41 => 1, + 43 => 1, + 45 => 1, + 47 => 1, + 49 => 1, + 51 => 1, + 53 => 1, + 55 => 1, + 63 => 1, + 65 => 1, + 70 => 1, + 72 => 1, + ); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 8 => 1, - 9 => 1, - 17 => 1, - 20 => 1, - 23 => 1, - 25 => 1, - 27 => 1, - 33 => 1, - 35 => 1, - 37 => 1, - 39 => 1, - 41 => 1, - 43 => 1, - 45 => 1, - 47 => 1, - 49 => 1, - 51 => 1, - 53 => 1, - 55 => 1, - 63 => 1, - 65 => 1, - 70 => 1, - 72 => 1, - ); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php index c2cadfdab6..012272a635 100644 --- a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php +++ b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php @@ -24,42 +24,37 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_PHP_StrictComparisonsUnitTest extends AbstractSniffUnitTest -{ - - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array(); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 3 => 1, - 10 => 1, - 12 => 1, - ); - - }//end getWarningList() - - -}//end class +class WordPress_Tests_PHP_StrictComparisonsUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array(); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 3 => 1, + 10 => 1, + 12 => 1, + ); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/PHP/YodaConditionsUnitTest.php b/WordPress/Tests/PHP/YodaConditionsUnitTest.php index 5ad72316ad..9c70a76871 100644 --- a/WordPress/Tests/PHP/YodaConditionsUnitTest.php +++ b/WordPress/Tests/PHP/YodaConditionsUnitTest.php @@ -24,54 +24,47 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_PHP_YodaConditionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_PHP_YodaConditionsUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 2 => 2, + 4 => 2, + 11 => 1, + 18 => 1, + 25 => 1, + 32 => 1, + 49 => 1, + 55 => 1, + 62 => 1, + 68 => 1, + 84 => 1, + 88 => 1, + 90 => 1, + ); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 2 => 2, - 4 => 2, - 11 => 1, - 18 => 1, - 25 => 1, - 32 => 1, - 49 => 1, - 55 => 1, - 62 => 1, - 68 => 1, - 84 => 1, - 88 => 1, - 90 => 1, - ); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php index a1a904b175..e5a7c732a7 100644 --- a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php +++ b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php @@ -7,42 +7,36 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_VIP_AdminBarRemovalUnitTest extends AbstractSniffUnitTest -{ - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 5 => 1, - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - - }//end getWarningList() - - -}//end class - -?> +class WordPress_Tests_VIP_AdminBarRemovalUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 5 => 1, + ); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/VIP/CronIntervalUnitTest.php b/WordPress/Tests/VIP/CronIntervalUnitTest.php index a1378c2422..2351671a27 100644 --- a/WordPress/Tests/VIP/CronIntervalUnitTest.php +++ b/WordPress/Tests/VIP/CronIntervalUnitTest.php @@ -7,44 +7,40 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_VIP_CronIntervalUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_VIP_CronIntervalUnitTest extends AbstractSniffUnitTest { - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 10 => 1, - 15 => 1, - 35 => 1, - 39 => 1, - ); + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 10 => 1, + 15 => 1, + 35 => 1, + 39 => 1, + ); - }//end getErrorList() + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 37 => 1, - ); + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 37 => 1, + ); - }//end getWarningList() + } // end getWarningList() - -}//end class +} // end class diff --git a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php index f6bf3a376e..aa8bde8f95 100644 --- a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php +++ b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_DirectDatabaseQueryUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_DirectDatabaseQueryUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,8 +20,7 @@ class WordPress_Tests_VIP_DirectDatabaseQueryUnitTest extends AbstractSniffUnitT * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 6 => 1, 8 => 1, @@ -33,9 +30,9 @@ public function getErrorList() 78 => 1, 79 => 1, 80 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -46,16 +43,14 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array( 6 => 1, 17 => 1, 38 => 1, 50 => 1, - ); - - }//end getWarningList() + ); + } // end getWarningList() -}//end class +} // end class diff --git a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php index 1802354e06..e88a0484e8 100644 --- a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php +++ b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_FileSystemWritesDisallowUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_FileSystemWritesDisallowUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,16 +20,15 @@ class WordPress_Tests_VIP_FileSystemWritesDisallowUnitTest extends AbstractSniff * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, 9 => 1, 10 => 1, 12 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -42,13 +39,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() - - -}//end class + } // end getWarningList() -?> +} // end class diff --git a/WordPress/Tests/VIP/OrderByRandUnitTest.php b/WordPress/Tests/VIP/OrderByRandUnitTest.php index a2e50f16ba..1aa6ba67ed 100644 --- a/WordPress/Tests/VIP/OrderByRandUnitTest.php +++ b/WordPress/Tests/VIP/OrderByRandUnitTest.php @@ -8,37 +8,37 @@ */ class WordPress_Tests_VIP_OrderByRandUnitTest extends AbstractSniffUnitTest { - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() { - return array( - 4 => 1, - 5 => 1, - 6 => 1, - 9 => 1, - 11 => 1, - ); + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 4 => 1, + 5 => 1, + 6 => 1, + 9 => 1, + 11 => 1, + ); - }//end getErrorList() + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() { - return array(); + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - } //end getWarningList() + } // end getWarningList() -}//end class +} // end class diff --git a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php index adc52502ad..5230231b60 100644 --- a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php +++ b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php @@ -7,41 +7,36 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_VIP_PluginMenuSlugUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_VIP_PluginMenuSlugUnitTest extends AbstractSniffUnitTest { - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 5 => 1, - ); + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 5 => 1, + ); - }//end getErrorList() + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - ); + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - }//end getWarningList() + } // end getWarningList() - -}//end class +} // end class diff --git a/WordPress/Tests/VIP/PostsPerPageUnitTest.php b/WordPress/Tests/VIP/PostsPerPageUnitTest.php index 3567484208..95e22f8d5e 100644 --- a/WordPress/Tests/VIP/PostsPerPageUnitTest.php +++ b/WordPress/Tests/VIP/PostsPerPageUnitTest.php @@ -7,45 +7,40 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_VIP_PostsPerPageUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_VIP_PostsPerPageUnitTest extends AbstractSniffUnitTest { - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 4 => 1, - 5 => 1, - 6 => 1, - 11 => 2, - 13 => 1, - 16 => 1, - ); + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 4 => 1, + 5 => 1, + 6 => 1, + 11 => 2, + 13 => 1, + 16 => 1, + ); - }//end getErrorList() + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - ); + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - }//end getWarningList() + } // end getWarningList() - -}//end class +} // end class diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index c67c3fd847..0800483a63 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -12,89 +12,85 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_RestrictedFunctionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_VIP_RestrictedFunctionsUnitTest extends AbstractSniffUnitTest { - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 5 => 1, - 21 => 1, - 34 => version_compare( PHP_VERSION, '5.3.0', '>=' ) ? 0 : 1, - 36 => 1, - 38 => 1, - 40 => 1, - 42 => 1, - 44 => 1, - 46 => 1, - 48 => 1, - 50 => 1, - 53 => 1, - 54 => 1, - 55 => 1, - 56 => 1, - 57 => 1, - 62 => 1, - 63 => 1, - 64 => 1, - 65 => 1, - 66 => 1, - 67 => 1, - 68 => 1, - 69 => 1, - 70 => 1, - 71 => 1, - 74 => 1, - 75 => 2, - 76 => 1, - 77 => 1, - 78 => 1, - 79 => 1, - 80 => 1, - 81 => 1, - 82 => 1, - 83 => 1, - 84 => 1, - 85 => 1, - ); + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 5 => 1, + 21 => 1, + 34 => version_compare( PHP_VERSION, '5.3.0', '>=' ) ? 0 : 1, + 36 => 1, + 38 => 1, + 40 => 1, + 42 => 1, + 44 => 1, + 46 => 1, + 48 => 1, + 50 => 1, + 53 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 57 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 74 => 1, + 75 => 2, + 76 => 1, + 77 => 1, + 78 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + 82 => 1, + 83 => 1, + 84 => 1, + 85 => 1, + ); - }//end getErrorList() + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 7 => 1, - 9 => 1, - 11 => 1, - 13 => 1, - 15 => 1, - 17 => 1, - 19 => 1, - 58 => 1, - 59 => 1, - 61 => 1, - 72 => 1, - ); + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 7 => 1, + 9 => 1, + 11 => 1, + 13 => 1, + 15 => 1, + 17 => 1, + 19 => 1, + 58 => 1, + 59 => 1, + 61 => 1, + 72 => 1, + ); - }//end getWarningList() + } // end getWarningList() - -}//end class +} // end class diff --git a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php index ef03c83449..e52358515c 100644 --- a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php @@ -12,9 +12,7 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_RestrictedVariablesUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_RestrictedVariablesUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -24,16 +22,15 @@ class WordPress_Tests_VIP_RestrictedVariablesUnitTest extends AbstractSniffUnitT * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, 5 => 1, 7 => 1, 9 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -44,16 +41,13 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array( 13 => 1, 14 => 1, 17 => 1, - ); - - }//end getWarningList() - + ); -}//end class + } // end getWarningList() +} // end class diff --git a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php index 05737d9523..fe2876c9d8 100644 --- a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_SessionFunctionsUsageUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_SessionFunctionsUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,13 +20,12 @@ class WordPress_Tests_VIP_SessionFunctionsUsageUnitTest extends AbstractSniffUni * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -39,13 +36,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() - - -}//end class + } // end getWarningList() -?> +} // end class diff --git a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php index e4737f31f9..89463d88b2 100644 --- a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,14 +20,13 @@ class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnit * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, 4 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -40,13 +37,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() - - -}//end class + } // end getWarningList() -?> +} // end class diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php index 651640d6b7..99eefa562c 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php @@ -7,47 +7,40 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_VIP_SlowDBQueryUnitTest extends AbstractSniffUnitTest -{ - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 4 => 1, - 10 => 1, - 15 => 1, - 16 => 1, - 19 => 2, - 30 => 1, - ); - - }//end getWarningList() - - -}//end class - -?> +class WordPress_Tests_VIP_SlowDBQueryUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array(); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 4 => 1, + 10 => 1, + 15 => 1, + 16 => 1, + 19 => 2, + 30 => 1, + ); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php index d1adf8f119..82181f256e 100644 --- a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php +++ b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_SuperGlobalInputUsageUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_SuperGlobalInputUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,12 +20,10 @@ class WordPress_Tests_VIP_SuperGlobalInputUsageUnitTest extends AbstractSniffUni * * @return array(int => int) */ - public function getErrorList() - { - return array( - ); + public function getErrorList() { + return array(); - }//end getErrorList() + } // end getErrorList() /** @@ -38,16 +34,12 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array( 3 => 1, 11 => 1, 13 => 1, - ); - - }//end getWarningList() - - -}//end class + ); + } // end getWarningList() +} // end class diff --git a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php index 24569b1a7e..69dacb0caf 100644 --- a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php +++ b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_TimezoneChangeUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_TimezoneChangeUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,13 +20,12 @@ class WordPress_Tests_VIP_TimezoneChangeUnitTest extends AbstractSniffUnitTest * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, - ); + ); - }//end getErrorList() + } // end getErrorList() /** @@ -39,13 +36,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() - - -}//end class + } // end getWarningList() -?> +} // end class diff --git a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php index 89625dcd11..616064b135 100644 --- a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php +++ b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php @@ -10,9 +10,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_VIP_ValidatedSanitizedInputUnitTest extends AbstractSniffUnitTest -{ - +class WordPress_Tests_VIP_ValidatedSanitizedInputUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -22,8 +20,7 @@ class WordPress_Tests_VIP_ValidatedSanitizedInputUnitTest extends AbstractSniffU * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 5 => 3, 7 => 1, @@ -46,7 +43,7 @@ public function getErrorList() 114 => 2, ); - }//end getErrorList() + } // end getErrorList() /** @@ -57,13 +54,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { + public function getWarningList() { return array(); - }//end getWarningList() - - -}//end class + } // end getWarningList() -?> +} // end class diff --git a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php index efb8e0ee70..c96d1ef4ee 100644 --- a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php +++ b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php @@ -7,8 +7,7 @@ * @package WordPress_Coding_Standards * @author Shady Sharaf */ -class WordPress_Tests_Variables_GlobalVariablesUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_Variables_GlobalVariablesUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. @@ -18,15 +17,13 @@ class WordPress_Tests_Variables_GlobalVariablesUnitTest extends AbstractSniffUni * * @return array(int => int) */ - public function getErrorList() - { + public function getErrorList() { return array( 3 => 1, 6 => 1, ); - - }//end getErrorList() + } // end getErrorList() /** @@ -37,12 +34,9 @@ public function getErrorList() * * @return array(int => int) */ - public function getWarningList() - { - return array( - ); - - }//end getWarningList() + public function getWarningList() { + return array(); + } // end getWarningList() -}//end class +} // end class diff --git a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php index 3484039be9..3b22fc5243 100644 --- a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php +++ b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php @@ -7,70 +7,65 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_Variables_VariableRestrictionsUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_Variables_VariableRestrictionsUnitTest extends AbstractSniffUnitTest { protected function setUp() { parent::setUp(); WordPress_Sniffs_Variables_VariableRestrictionsSniff::$groups = array( 'test' => array( - 'type' => 'error', - 'message' => 'Detected usage of %s', - 'object_vars' => array( + 'type' => 'error', + 'message' => 'Detected usage of %s', + 'object_vars' => array( '$foo->bar', 'FOO::var', 'FOO::reg*', 'FOO::$static', - ), + ), 'array_members' => array( '$foo[\'test\']', - ), - 'variables' => array( + ), + 'variables' => array( '$taz', - ), - ), - ); + ), + ); } - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 3 => 1, - 5 => 1, - 11 => 1, - 15 => 1, - 17 => 1, - 21 => 1, - 23 => 1, - ); - }//end getErrorList() + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + 5 => 1, + 11 => 1, + 15 => 1, + 17 => 1, + 21 => 1, + 23 => 1, + ); + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - ); - }//end getWarningList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + } // end getWarningList() -}//end class +} // end class diff --git a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php index c63f33c46c..9f8bb8415e 100644 --- a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php +++ b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php @@ -8,55 +8,52 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Tests_WP_EnqueuedResourcesUnitTest extends AbstractSniffUnitTest -{ - - /** - * Skip this test on PHP 5.2. - * - * @since 0.9.0 - * - * @return bool Whether to skip this test. - */ - protected function shouldSkipTest() { - return version_compare( PHP_VERSION, '5.3.0', '<' ); - } - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 1 => 1, - 2 => 1, - 6 => 1, - 7 => 1, - 10 => 1, - 11 => 1, - ); - - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - - }//end getWarningList() - - -}//end class +class WordPress_Tests_WP_EnqueuedResourcesUnitTest extends AbstractSniffUnitTest { + + /** + * Skip this test on PHP 5.2. + * + * @since 0.9.0 + * + * @return bool Whether to skip this test. + */ + protected function shouldSkipTest() { + return version_compare( PHP_VERSION, '5.3.0', '<' ); + } + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 1 => 1, + 2 => 1, + 6 => 1, + 7 => 1, + 10 => 1, + 11 => 1, + ); + + } // end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index dd80e444a8..88f7d12356 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -16,6 +16,7 @@ protected function setUp() { parent::setUp(); } + /** * Returns the lines where errors should occur. * @@ -76,7 +77,8 @@ public function getErrorList() { 106 => 1, 107 => 1, ); - } + } // end getErrorList() + /** * Returns the lines where warnings should occur. @@ -95,5 +97,6 @@ public function getWarningList() { 102 => 1, 103 => 1, ); - } -} + } // end getWarningList() + +} // end class. diff --git a/WordPress/Tests/WP/PreparedSQLUnitTest.php b/WordPress/Tests/WP/PreparedSQLUnitTest.php index 1786a69dac..754951d056 100644 --- a/WordPress/Tests/WP/PreparedSQLUnitTest.php +++ b/WordPress/Tests/WP/PreparedSQLUnitTest.php @@ -29,13 +29,14 @@ public function getErrorList() { 20 => 1, 21 => 1, ); - } + } // end getErrorList() + /** * @since 0.8.0 */ public function getWarningList() { return array(); - } + } // end getWarningList() } // end class. diff --git a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php index 64c470a249..e99473c521 100644 --- a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php @@ -24,48 +24,41 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_WhiteSpace_CastStructureSpacingUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_WhiteSpace_CastStructureSpacingUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array(); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array(); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array( + 3 => 1, + 6 => 1, + 9 => 1, + 12 => 2, + 15 => 1, + 18 => 1, + 21 => 1, + ); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array( - 3 => 1, - 6 => 1, - 9 => 1, - 12 => 2, - 15 => 1, - 18 => 1, - 21 => 1, - ); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php index 070e9d9908..7982c9c6d1 100644 --- a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php @@ -28,81 +28,78 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_WhiteSpace_ControlStructureSpacingUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_WhiteSpace_ControlStructureSpacingUnitTest extends AbstractSniffUnitTest { - /** - * Skip this test on PHP 5.2. - * - * @since 0.9.0 - * - * @return bool Whether to skip this test. - */ - protected function shouldSkipTest() { - return version_compare( PHP_VERSION, '5.3.0', '<' ); - } + /** + * Skip this test on PHP 5.2. + * + * @since 0.9.0 + * + * @return bool Whether to skip this test. + */ + protected function shouldSkipTest() { + return version_compare( PHP_VERSION, '5.3.0', '<' ); + } - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - $ret = array( - 4 => 2, - 17 => 2, - 29 => 5, - 37 => 1, - 41 => 1, - 42 => 1, - 49 => 5, - 58 => 3, - 67 => 1, - 68 => 1, - 69 => 1, - 71 => 1, - 72 => 1, - 81 => 3, - 82 => 1, - 85 => 1, - 91 => 2, - 92 => 1, - 94 => 1, - 95 => 1, - 97 => 1, - 98 => 1, - ); - // Uncomment when "$blank_line_check" parameter will be "true" by default. - /*$ret[29] += 1; - $ret[33] = 1; - $ret[36] = 1; - $ret[38] = 1;*/ + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + $ret = array( + 4 => 2, + 17 => 2, + 29 => 5, + 37 => 1, + 41 => 1, + 42 => 1, + 49 => 5, + 58 => 3, + 67 => 1, + 68 => 1, + 69 => 1, + 71 => 1, + 72 => 1, + 81 => 3, + 82 => 1, + 85 => 1, + 91 => 2, + 92 => 1, + 94 => 1, + 95 => 1, + 97 => 1, + 98 => 1, + ); - return $ret; + // Uncomment when "$blank_line_check" parameter will be "true" by default. + /* + $ret[29] += 1; + $ret[33] = 1; + $ret[36] = 1; + $ret[38] = 1; + */ - }//end getErrorList() + return $ret; + } // end getErrorList() - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); - }//end getWarningList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + } // end getWarningList() -}//end class - -?> +} // end class diff --git a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php index 02d4feecfa..60413c23a6 100644 --- a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php @@ -28,45 +28,38 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_WhiteSpace_OperatorSpacingUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_WhiteSpace_OperatorSpacingUnitTest extends AbstractSniffUnitTest { + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 5 => 4, + 18 => 1, + 45 => 1, + 49 => 1, + ); - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( - 5 => 4, - 18 => 1, - 45 => 1, - 49 => 1, - ); + } // end getErrorList() - }//end getErrorList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); + } // end getWarningList() - }//end getWarningList() - - -}//end class - -?> +} // end class diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.php b/WordPress/Tests/XSS/EscapeOutputUnitTest.php index f585f4592b..649134a14d 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.php +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.php @@ -28,21 +28,18 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Tests_XSS_EscapeOutputUnitTest extends AbstractSniffUnitTest -{ +class WordPress_Tests_XSS_EscapeOutputUnitTest extends AbstractSniffUnitTest { - - /** - * Returns the lines where errors should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) - */ - public function getErrorList() - { - return array( + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( 17 => 1, 19 => 1, 36 => 1, @@ -80,24 +77,20 @@ public function getErrorList() 173 => 1, ); - }//end getErrorList() - - - /** - * Returns the lines where warnings should occur. - * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) - */ - public function getWarningList() - { - return array(); + } // end getErrorList() - }//end getWarningList() + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); -}//end class + } // end getWarningList() -?> +} // end class From d4b4875b12ce25dddba1a30816ee48f28bf72abc Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 13:47:33 +0200 Subject: [PATCH 058/122] Remove commented out code blocks. --- .../Sniffs/Arrays/ArrayDeclarationSniff.php | 168 +----------------- 1 file changed, 1 insertion(+), 167 deletions(-) diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php index c17aaea26e..c1f70dcb7e 100644 --- a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -98,26 +98,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt if ( true === $fix ) { $phpcsFile->fixer->addNewlineBefore( $arrayEnd ); } - /* - } elseif ( $tokens[ $arrayEnd ]['column'] !== $keywordStart ) { - // Check the closing bracket is lined up under the "a" in array. - $expected = ( $keywordStart - 1 ); - $found = ( $tokens[ $arrayEnd ]['column'] - 1 ); - $error = 'Closing parenthesis not aligned correctly; expected %s space(s) but found %s'; - $data = array( - $expected, - $found, - ); - - $fix = $phpcsFile->addFixableError( $error, $arrayEnd, 'CloseBraceNotAligned', $data ); - if ( true === $fix ) { - if ( 0 === $found ) { - $phpcsFile->fixer->addContent( ( $arrayEnd - 1 ), str_repeat(' ', $expected ) ); - } else { - $phpcsFile->fixer->replaceToken( ( $arrayEnd - 1 ), str_repeat(' ', $expected ) ); - } - } - */ } // end if $nextToken = $stackPtr; @@ -224,14 +204,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt continue; } - /* - if ( true === $keyUsed && T_COMMA === $tokens[ $lastToken ]['code'] ) { - $error = 'No key specified for array entry; first entry specifies key'; - $phpcsFile->addError( $error, $nextToken, 'NoKeySpecified' ); - return; - } - */ - if ( false === $keyUsed ) { if ( T_WHITESPACE === $tokens[ ( $nextToken - 1 ) ]['code'] ) { $content = $tokens[ ( $nextToken - 2 ) ]['content']; @@ -269,13 +241,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt } // end if if ( T_DOUBLE_ARROW === $tokens[ $nextToken ]['code'] ) { - /* - if ( true === $singleUsed ) { - $error = 'Key specified for array entry; first entry has no key'; - $phpcsFile->addError( $error, $nextToken, 'KeySpecified' ); - return; - } - */ $currentEntry['arrow'] = $nextToken; $keyUsed = true; @@ -326,38 +291,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt } } - /* - if ( true === $singleValue ) { - // Array cannot be empty, so this is a multi-line array with - // a single value. It should be defined on single line. - $error = 'Multi-line array contains a single value; use single-line array instead'; - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'MultiLineNotAllowed' ); - - if ( true === $fix ) { - $phpcsFile->fixer->beginChangeset(); - for ( $i = ( $arrayStart + 1 ); $i < $arrayEnd; $i++ ) { - if ( T_WHITESPACE !== $tokens[ $i ]['code'] ) { - break; - } - - $phpcsFile->fixer->replaceToken( $i, '' ); - } - - for ( $i = ( $arrayEnd - 1 ); $i > $arrayStart; $i-- ) { - if ( T_WHITESPACE !== $tokens[ $i ]['code'] ) { - break; - } - - $phpcsFile->fixer->replaceToken( $i, '' ); - } - - $phpcsFile->fixer->endChangeset(); - } - - return; - } // end if - */ - /* This section checks for arrays that don't specify keys. @@ -410,29 +343,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt $phpcsFile->fixer->addNewlineBefore( $value['value'] ); } - /* - } elseif ( T_WHITESPACE === $tokens[ ( $value['value'] - 1 ) ]['code'] ) { - $expected = $keywordStart; - - $first = $phpcsFile->findFirstOnLine( T_WHITESPACE, $value['value'], true ); - $found = ($tokens[ $first ]['column'] - 1); - if ( $found !== $expected ) { - $error = 'Array value not aligned correctly; expected %s spaces but found %s'; - $data = array( - $expected, - $found, - ); - - $fix = $phpcsFile->addFixableError( $error, $value['value'], 'ValueNotAligned', $data ); - if ( true === $fix ) { - if ( 0 === $found ) { - $phpcsFile->fixer->addContent( ( $value['value'] - 1 ), str_repeat(' ', $expected ) ); - } else { - $phpcsFile->fixer->replaceToken( ( $value['value'] - 1 ), str_repeat(' ', $expected ) ); - } - } - } - */ } // end if $lastValueLine = $tokens[ $value['value'] ]['line']; @@ -464,7 +374,7 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt In this array, the double arrow is indented too far, but this will also cause an error in the value's alignment. If the arrow were to be moved back one space however, then both errors would be fixed. - */ + */ $numValues = count( $indices ); @@ -514,82 +424,6 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt continue; } - /* - if ( $tokens[ $index['index'] ]['column'] !== $indicesStart ) { - $expected = ( $indicesStart - 1 ); - $found = ( $tokens[ $index['index'] ]['column'] - 1 ); - $error = 'Array key not aligned correctly; expected %s spaces but found %s'; - $data = array( - $expected, - $found, - ); - - $fix = $phpcsFile->addFixableError( $error, $index['index'], 'KeyNotAligned', $data ); - if ( true === $fix ) { - if ( 0 === $found ) { - $phpcsFile->fixer->addContent( ( $index['index'] - 1 ), str_repeat(' ', $expected ) ); - } else { - $phpcsFile->fixer->replaceToken( ( $index['index'] - 1 ), str_repeat(' ', $expected ) ); - } - } - - continue; - } - - if ( $tokens[ $index['arrow'] ]['column'] !== $arrowStart ) { - $expected = ( $arrowStart - ( strlen( $index['index_content'] ) + $tokens[ $index['index'] ]['column'] ) ); - $found = ( $tokens[ $index['arrow'] ]['column'] - ( strlen( $index['index_content'] ) + $tokens[ $index['index'] ]['column'] ) ); - $error = 'Array double arrow not aligned correctly; expected %s space(s) but found %s'; - $data = array( - $expected, - $found, - ); - - $fix = $phpcsFile->addFixableError( $error, $index['arrow'], 'DoubleArrowNotAligned', $data ); - if ( true === $fix ) { - if ( 0 === $found ) { - $phpcsFile->fixer->addContent( ( $index['arrow'] - 1 ), str_repeat(' ', $expected ) ); - } else { - $phpcsFile->fixer->replaceToken( ( $index['arrow'] - 1 ), str_repeat(' ', $expected ) ); - } - } - - continue; - } - - if ( $tokens[ $index['value'] ]['column'] !== $valueStart ) { - $expected = ( $valueStart - ( $tokens[ $index['arrow'] ]['length'] + $tokens[ $index['arrow'] ]['column'] ) ); - $found = ( $tokens[ $index['value'] ]['column'] - ( $tokens[ $index['arrow'] ]['length'] + $tokens[ $index['arrow'] ]['column'] ) ); - if ( $found < 0 ) { - $found = 'newline'; - } - - $error = 'Array value not aligned correctly; expected %s space(s) but found %s'; - $data = array( - $expected, - $found, - ); - - $fix = $phpcsFile->addFixableError( $error, $index['arrow'], 'ValueNotAligned', $data ); - if ( true === $fix ) { - if ( 'newline' === $found ) { - $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $index['value'] - 1 ), null, true ); - $phpcsFile->fixer->beginChangeset(); - for ( $i = ( $prev + 1 ); $i < $index['value']; $i++ ) { - $phpcsFile->fixer->replaceToken( $i, '' ); - } - - $phpcsFile->fixer->replaceToken( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); - $phpcsFile->fixer->endChangeset(); - } elseif ( 0 === $found ) { - $phpcsFile->fixer->addContent( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); - } else { - $phpcsFile->fixer->replaceToken( ( $index['value'] - 1 ), str_repeat(' ', $expected ) ); - } - } - } // end if - */ - // Check each line ends in a comma. $valueLine = $tokens[ $index['value'] ]['line']; $nextComma = false; From 5f3bceedf695c98d90c63b72f19aa436505dfcc0 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 14:01:26 +0200 Subject: [PATCH 059/122] Minor change to get round empty `if()` statement error. As that was the only error left for the WP-Extra ruleset, might as well activate it too. --- WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php | 9 ++++++--- bin/phpcs.xml | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php index fa5894df3d..23521598fc 100644 --- a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -82,10 +82,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { if ( T_BITWISE_AND === $tokens[ $stackPtr ]['code'] ) { // If its not a reference, then we expect one space either side of the // bitwise operator. - if ( false === $phpcsFile->isReference( $stackPtr ) ) { - // @todo Implement ? + // if ( false === $phpcsFile->isReference( $stackPtr ) ) { + // @todo Implement or remove ? + + // } // end if + + return; - } // end if } else { if ( T_MINUS === $tokens[ $stackPtr ]['code'] ) { // Check minus spacing, but make sure we aren't just assigning diff --git a/bin/phpcs.xml b/bin/phpcs.xml index ba0e060e35..aa8ec9d7fc 100644 --- a/bin/phpcs.xml +++ b/bin/phpcs.xml @@ -7,4 +7,6 @@ + + From b358c1850613495bb927e4b9c10b32b834fae5d9 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 23:33:30 +0200 Subject: [PATCH 060/122] Make sure all methods have one line break before and one after. As this clashes with `WordPress.WhiteSpace.ControlStructureSpacing.BlankLineAfterEnd` for the last method in a class, I've - for now - resorted to adding `// end` comments after the method closing brace to bypass that error. --- WordPress/Sniff.php | 3 ++- .../Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php | 6 ++---- WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php | 1 - WordPress/Sniffs/Files/FileNameSniff.php | 1 + WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php | 2 +- .../Sniffs/NamingConventions/ValidFunctionNameSniff.php | 2 -- .../Sniffs/NamingConventions/ValidVariableNameSniff.php | 4 ++-- WordPress/Sniffs/PHP/StrictComparisonsSniff.php | 1 - WordPress/Sniffs/PHP/StrictInArraySniff.php | 5 +++-- WordPress/Sniffs/PHP/YodaConditionsSniff.php | 1 - WordPress/Sniffs/VIP/AdminBarRemovalSniff.php | 1 - WordPress/Sniffs/VIP/CronIntervalSniff.php | 5 ++--- WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php | 1 - WordPress/Sniffs/VIP/OrderByRandSniff.php | 3 ++- WordPress/Sniffs/VIP/PluginMenuSlugSniff.php | 1 - WordPress/Sniffs/VIP/PostsPerPageSniff.php | 3 ++- WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php | 3 ++- WordPress/Sniffs/VIP/RestrictedVariablesSniff.php | 3 ++- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 3 ++- WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php | 1 - WordPress/Sniffs/Variables/GlobalVariablesSniff.php | 5 +++-- WordPress/Sniffs/Variables/VariableRestrictionsSniff.php | 5 ++--- WordPress/Sniffs/WP/EnqueuedResourcesSniff.php | 1 - WordPress/Sniffs/WP/I18nSniff.php | 3 ++- WordPress/Sniffs/WP/PreparedSQLSniff.php | 3 ++- WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php | 1 - .../Sniffs/WhiteSpace/ControlStructureSpacingSniff.php | 2 -- WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php | 2 -- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 2 -- .../Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php | 2 -- WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php | 1 - .../Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php | 3 +-- WordPress/Tests/CSRF/NonceVerificationUnitTest.php | 2 +- WordPress/Tests/Classes/ValidClassNameUnitTest.php | 1 - WordPress/Tests/Files/FileNameUnitTest.php | 1 - .../Tests/NamingConventions/ValidFunctionNameUnitTest.php | 1 - .../Tests/NamingConventions/ValidVariableNameUnitTest.php | 2 +- WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php | 1 - WordPress/Tests/PHP/StrictComparisonsUnitTest.php | 1 - WordPress/Tests/PHP/StrictInArrayUnitTest.php | 7 ++++--- WordPress/Tests/PHP/YodaConditionsUnitTest.php | 1 - WordPress/Tests/VIP/AdminBarRemovalUnitTest.php | 1 - WordPress/Tests/VIP/CronIntervalUnitTest.php | 1 - WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php | 1 - WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php | 1 - WordPress/Tests/VIP/OrderByRandUnitTest.php | 1 - WordPress/Tests/VIP/PluginMenuSlugUnitTest.php | 1 - WordPress/Tests/VIP/PostsPerPageUnitTest.php | 1 - WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php | 1 - WordPress/Tests/VIP/RestrictedVariablesUnitTest.php | 1 - WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php | 1 - WordPress/Tests/VIP/SessionVariableUsageUnitTest.php | 1 - WordPress/Tests/VIP/SlowDBQueryUnitTest.php | 1 - WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php | 1 - WordPress/Tests/VIP/TimezoneChangeUnitTest.php | 1 - WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php | 3 +-- WordPress/Tests/Variables/GlobalVariablesUnitTest.php | 1 - WordPress/Tests/Variables/VariableRestrictionsUnitTest.php | 2 -- WordPress/Tests/WP/EnqueuedResourcesUnitTest.php | 2 -- WordPress/Tests/WP/I18nUnitTest.php | 2 -- WordPress/Tests/WP/PreparedSQLUnitTest.php | 1 - .../Tests/WhiteSpace/CastStructureSpacingUnitTest.php | 1 - .../Tests/WhiteSpace/ControlStructureSpacingUnitTest.php | 2 -- WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php | 1 - WordPress/Tests/XSS/EscapeOutputUnitTest.php | 1 - 65 files changed, 40 insertions(+), 87 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index c3a83755c7..f0ff14a49b 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -1126,5 +1126,6 @@ protected function get_interpolated_variables( $string ) { } } return $variables; - } + } // end get_interpolated_variables() + } diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index 13d675c71a..d3358437ce 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -26,7 +26,6 @@ class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress */ public static $groups = array(); - /** * Returns an array of tokens this test wants to listen for. * @@ -42,7 +41,6 @@ public function register() { } // end register() - /** * Groups of variables to restrict. * This should be overridden in extending classes. @@ -63,7 +61,6 @@ public function getGroups() { return self::$groups; } - /** * Processes this test, when one of its tokens is encountered. * @@ -190,5 +187,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { */ public function callback( $key, $val, $line, $group ) { return true; - } + } // end callback() + } // end class diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php index c1f70dcb7e..8ae9d0dc34 100644 --- a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -82,7 +82,6 @@ public function processSingleLineArray( PHP_CodeSniffer_File $phpcsFile, $stackP } } - /** * @since 0.5.0 */ diff --git a/WordPress/Sniffs/Files/FileNameSniff.php b/WordPress/Sniffs/Files/FileNameSniff.php index 5a2b3c6915..eb15d3843d 100644 --- a/WordPress/Sniffs/Files/FileNameSniff.php +++ b/WordPress/Sniffs/Files/FileNameSniff.php @@ -53,4 +53,5 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return ( $phpcsFile->numTokens + 1 ); } // end process() + } // end class diff --git a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php index 420ed5da2c..d8f74a5b4f 100644 --- a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php +++ b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php @@ -47,7 +47,6 @@ public function getGroups() { return array(); } - /** * Processes this test, when one of its tokens is encountered. * @@ -122,4 +121,5 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } // end process() + } // end class diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index 399cb35fc0..ef60f727b2 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -36,7 +36,6 @@ class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sni 'debugInfo', ); - /** * Processes the tokens outside the scope. * @@ -60,7 +59,6 @@ protected function processTokenOutsideScope( PHP_CodeSniffer_File $phpcsFile, $s } // end processTokenOutsideScope() - /** * Processes the tokens within the scope. * diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 7b3315c394..b94db17279 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -204,7 +204,6 @@ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_pt } - /** * Processes the variable found within a double quoted string. * @@ -242,5 +241,6 @@ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $s */ static function isSnakeCase( $var_name ) { return (bool) preg_match( '/^[a-z0-9_]+$/', $var_name ); - } + } // end isSnakeCase() + } // end class diff --git a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php index 2fe86fdca1..1b6b9368e1 100644 --- a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php +++ b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php @@ -23,7 +23,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index 9545c77acf..368c0c3445 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -71,5 +71,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addWarning( 'Not using strict comparison for in_array(); supply true for third argument.', $lastToken, 'MissingTrueStrict' ); return; } - } -} + } // end process() + +} // end class diff --git a/WordPress/Sniffs/PHP/YodaConditionsSniff.php b/WordPress/Sniffs/PHP/YodaConditionsSniff.php index f53393c8fe..ae07e69f7b 100644 --- a/WordPress/Sniffs/PHP/YodaConditionsSniff.php +++ b/WordPress/Sniffs/PHP/YodaConditionsSniff.php @@ -35,7 +35,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php index b31e65fa75..e0882e1aa5 100644 --- a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php +++ b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php @@ -22,7 +22,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/VIP/CronIntervalSniff.php b/WordPress/Sniffs/VIP/CronIntervalSniff.php index 5294945a68..c777a53696 100644 --- a/WordPress/Sniffs/VIP/CronIntervalSniff.php +++ b/WordPress/Sniffs/VIP/CronIntervalSniff.php @@ -22,7 +22,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * @@ -123,8 +122,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() - public function confused( $phpcsFile, $stackPtr ) { $phpcsFile->addWarning( 'Detected changing of cron_schedules, but could not detect the interval value.', $stackPtr, 'ChangeDetected' ); - } + } // end confused() + } // end class diff --git a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php index 27b41084e8..f0c98cc008 100644 --- a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php +++ b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php @@ -73,7 +73,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/VIP/OrderByRandSniff.php b/WordPress/Sniffs/VIP/OrderByRandSniff.php index b1954d567b..a3e8bfdc17 100644 --- a/WordPress/Sniffs/VIP/OrderByRandSniff.php +++ b/WordPress/Sniffs/VIP/OrderByRandSniff.php @@ -40,5 +40,6 @@ public function callback( $key, $val, $line, $group ) { } else { return false; } - } + } // end callback() + } // end class diff --git a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php index db20dc8677..7ef6066fae 100644 --- a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php +++ b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php @@ -38,7 +38,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index c292cd587b..1d8a0fbc41 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -65,5 +65,6 @@ public function callback( $key, $val, $line, $group ) { return 'Detected high pagination limit, `%s` is set to `%s`'; } } - } + } // end callback() + } // end class diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 8c72951296..c60db82665 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -346,5 +346,6 @@ public function getGroups() { ), ); - } + } // end getGroups() + } // end class diff --git a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php index 8ccd0f125d..49cabb0f5f 100644 --- a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php @@ -45,5 +45,6 @@ public function getGroups() { ), ), ); - } + } // end getGroups() + } // end class diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index 0c1e5dcbe7..1f1df05724 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -57,5 +57,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } parent::process( $phpcsFile, $stackPtr ); - } + } // end process() + } // end class diff --git a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php index 4bff6de2d4..bfc1ab3e8a 100644 --- a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php +++ b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php @@ -21,7 +21,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index 0c370405a8..ca26f59724 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -336,5 +336,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } } - } -} + } // end process() + +} // end class diff --git a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php index f0b6099530..9e76d48797 100644 --- a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php +++ b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php @@ -26,7 +26,6 @@ class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSn */ public static $groups = array(); - /** * Returns an array of tokens this test wants to listen for. * @@ -63,7 +62,6 @@ public function getGroups() { return self::$groups; } - /** * Processes this test, when one of its tokens is encountered. * @@ -168,5 +166,6 @@ private function test_patterns( $pattern ) { $pattern ); return $pattern; - } + } // end test_patterns() + } // end class diff --git a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php index 303ed4f67c..18030db60c 100644 --- a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php +++ b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php @@ -24,7 +24,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 2bffb14ba4..7e93996d52 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -349,5 +349,6 @@ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { if ( empty( $non_placeholder_content ) ) { $phpcs_file->addError( 'Strings should have translatable content', $stack_ptr, 'NoEmptyStrings' ); } - } + } // end check_text() + } diff --git a/WordPress/Sniffs/WP/PreparedSQLSniff.php b/WordPress/Sniffs/WP/PreparedSQLSniff.php index 5fe3bf12b1..dcf99c8310 100644 --- a/WordPress/Sniffs/WP/PreparedSQLSniff.php +++ b/WordPress/Sniffs/WP/PreparedSQLSniff.php @@ -232,5 +232,6 @@ protected function is_wpdb_method_call( $stackPtr ) { } return true; - } + } // is_wpdb_method_call() + } // end class. diff --git a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php index 9feef002e8..24cee0565d 100755 --- a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php @@ -39,7 +39,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index 3fd014f00c..f5088e9cce 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -63,7 +63,6 @@ class WordPress_Sniffs_WhiteSpace_ControlStructureSpacingSniff extends WordPress */ public $spaces_before_closure_open_paren = -1; - /** * Returns an array of tokens this test wants to listen for. * @@ -86,7 +85,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php index 23521598fc..724055bf3b 100644 --- a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -30,7 +30,6 @@ class WordPress_Sniffs_WhiteSpace_OperatorSpacingSniff implements PHP_CodeSniffe 'JS', ); - /** * Returns an array of tokens this test wants to listen for. * @@ -48,7 +47,6 @@ public function register() { } // end register() - /** * Processes this sniff, when one of its tokens is encountered. * diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 71db6ae524..924fc66e4b 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -75,7 +75,6 @@ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { */ public static $addedCustomFunctions = false; - /** * Returns an array of tokens this test wants to listen for. * @@ -91,7 +90,6 @@ public function register() { } // end register() - /** * Processes this test, when one of its tokens is encountered. * diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php index 98c6c838f1..7ee0061cab 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php @@ -24,7 +24,6 @@ protected function setUp() { ); } - /** * Returns the lines where errors should occur. * @@ -42,7 +41,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php index 1629e8cde7..61885be43e 100644 --- a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php @@ -51,7 +51,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php index d669037d4c..ced0f2614d 100644 --- a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php @@ -35,7 +35,6 @@ public function getErrorList() { ); } // end getErrorList() - /** * Returns the lines where warnings should occur. * @@ -46,7 +45,7 @@ public function getErrorList() { */ public function getWarningList() { return array(); - } // end getWarningList() + } // end getWarningList() } // end class diff --git a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php index 8ebc4fe683..55884c3d55 100644 --- a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php +++ b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php @@ -36,7 +36,6 @@ public function getErrorList() { ); } // end getErrorList() - /** * Returns the lines where warnings should occur. * @@ -47,6 +46,7 @@ public function getErrorList() { */ public function getWarningList() { return array(); + } // end getWarningList() } // end class diff --git a/WordPress/Tests/Classes/ValidClassNameUnitTest.php b/WordPress/Tests/Classes/ValidClassNameUnitTest.php index b493583c10..58b42a1ca2 100644 --- a/WordPress/Tests/Classes/ValidClassNameUnitTest.php +++ b/WordPress/Tests/Classes/ValidClassNameUnitTest.php @@ -45,7 +45,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/Files/FileNameUnitTest.php b/WordPress/Tests/Files/FileNameUnitTest.php index 74ab070b35..a352e6f451 100644 --- a/WordPress/Tests/Files/FileNameUnitTest.php +++ b/WordPress/Tests/Files/FileNameUnitTest.php @@ -43,7 +43,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php index 64879dd601..156c00b9ce 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php @@ -47,7 +47,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index 5c2ace9a42..fecb971dfd 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -89,7 +89,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * @@ -100,6 +99,7 @@ public function getErrorList() { */ public function getWarningList() { return array(); + } // end getWarningList() } // end class diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php index e85d87443a..40b2ec26fe 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php @@ -43,7 +43,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php index 012272a635..e99b4bb34a 100644 --- a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php +++ b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php @@ -39,7 +39,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/PHP/StrictInArrayUnitTest.php b/WordPress/Tests/PHP/StrictInArrayUnitTest.php index cff211578f..15bec10acc 100644 --- a/WordPress/Tests/PHP/StrictInArrayUnitTest.php +++ b/WordPress/Tests/PHP/StrictInArrayUnitTest.php @@ -35,7 +35,7 @@ public function getErrorList() { 7 => 1, 20 => 1, ); - } + } // end getErrorList() /** * Returns the lines where warnings should occur. @@ -51,5 +51,6 @@ public function getWarningList() { 9 => 1, 10 => 1, ); - } -} + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/PHP/YodaConditionsUnitTest.php b/WordPress/Tests/PHP/YodaConditionsUnitTest.php index 9c70a76871..660adc234a 100644 --- a/WordPress/Tests/PHP/YodaConditionsUnitTest.php +++ b/WordPress/Tests/PHP/YodaConditionsUnitTest.php @@ -53,7 +53,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php index e5a7c732a7..d544015392 100644 --- a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php +++ b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php @@ -25,7 +25,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/CronIntervalUnitTest.php b/WordPress/Tests/VIP/CronIntervalUnitTest.php index 2351671a27..14f9f7d825 100644 --- a/WordPress/Tests/VIP/CronIntervalUnitTest.php +++ b/WordPress/Tests/VIP/CronIntervalUnitTest.php @@ -27,7 +27,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php index aa8bde8f95..16ef361437 100644 --- a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php +++ b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php @@ -34,7 +34,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php index e88a0484e8..d5552d34ed 100644 --- a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php +++ b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php @@ -30,7 +30,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/OrderByRandUnitTest.php b/WordPress/Tests/VIP/OrderByRandUnitTest.php index 1aa6ba67ed..df85a7109f 100644 --- a/WordPress/Tests/VIP/OrderByRandUnitTest.php +++ b/WordPress/Tests/VIP/OrderByRandUnitTest.php @@ -27,7 +27,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php index 5230231b60..808d98577f 100644 --- a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php +++ b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.php @@ -25,7 +25,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/PostsPerPageUnitTest.php b/WordPress/Tests/VIP/PostsPerPageUnitTest.php index 95e22f8d5e..70511fe49d 100644 --- a/WordPress/Tests/VIP/PostsPerPageUnitTest.php +++ b/WordPress/Tests/VIP/PostsPerPageUnitTest.php @@ -29,7 +29,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index 0800483a63..729121955a 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -67,7 +67,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php index e52358515c..4b5a005b60 100644 --- a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php @@ -32,7 +32,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php index fe2876c9d8..db75b02b02 100644 --- a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php @@ -27,7 +27,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php index 89463d88b2..89f0701dcb 100644 --- a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php @@ -28,7 +28,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php index 99eefa562c..8fd81bb3eb 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php @@ -22,7 +22,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php index 82181f256e..8f58a16e6f 100644 --- a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php +++ b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php @@ -25,7 +25,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php index 69dacb0caf..d7ac7e0f21 100644 --- a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php +++ b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php @@ -27,7 +27,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php index 616064b135..9a8516d899 100644 --- a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php +++ b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php @@ -41,11 +41,10 @@ public function getErrorList() { 104 => 2, 105 => 1, 114 => 2, - ); + ); } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php index c96d1ef4ee..d289daddbe 100644 --- a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php +++ b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php @@ -25,7 +25,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php index 3b22fc5243..689ec75733 100644 --- a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php +++ b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php @@ -32,7 +32,6 @@ protected function setUp() { ); } - /** * Returns the lines where errors should occur. * @@ -54,7 +53,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php index 9f8bb8415e..c0f24d1d90 100644 --- a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php +++ b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php @@ -21,7 +21,6 @@ protected function shouldSkipTest() { return version_compare( PHP_VERSION, '5.3.0', '<' ); } - /** * Returns the lines where errors should occur. * @@ -42,7 +41,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/WP/I18nUnitTest.php b/WordPress/Tests/WP/I18nUnitTest.php index 88f7d12356..66cacef36e 100644 --- a/WordPress/Tests/WP/I18nUnitTest.php +++ b/WordPress/Tests/WP/I18nUnitTest.php @@ -16,7 +16,6 @@ protected function setUp() { parent::setUp(); } - /** * Returns the lines where errors should occur. * @@ -79,7 +78,6 @@ public function getErrorList() { ); } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/WP/PreparedSQLUnitTest.php b/WordPress/Tests/WP/PreparedSQLUnitTest.php index 754951d056..cf2f595db5 100644 --- a/WordPress/Tests/WP/PreparedSQLUnitTest.php +++ b/WordPress/Tests/WP/PreparedSQLUnitTest.php @@ -31,7 +31,6 @@ public function getErrorList() { ); } // end getErrorList() - /** * @since 0.8.0 */ diff --git a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php index e99473c521..4a18ffebef 100644 --- a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php @@ -39,7 +39,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php index 7982c9c6d1..f569a55ffb 100644 --- a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php @@ -41,7 +41,6 @@ protected function shouldSkipTest() { return version_compare( PHP_VERSION, '5.3.0', '<' ); } - /** * Returns the lines where errors should occur. * @@ -88,7 +87,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php index 60413c23a6..8553def0db 100644 --- a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php @@ -48,7 +48,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.php b/WordPress/Tests/XSS/EscapeOutputUnitTest.php index 649134a14d..2b8b7583a2 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.php +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.php @@ -79,7 +79,6 @@ public function getErrorList() { } // end getErrorList() - /** * Returns the lines where warnings should occur. * From 2e5f8fc19581881dfc8befcd69e1e4bed87a9a6c Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 13 Jul 2016 06:02:29 +0200 Subject: [PATCH 061/122] Minor touch-up. * Fix some missed "class opening brackets on different line" issues. There currently is no sniff checking for this, so visual fix. * Fixed one class extending the wrong parent. --- WordPress/Sniffs/PHP/StrictInArraySniff.php | 2 +- WordPress/Sniffs/VIP/CronIntervalSniff.php | 3 +-- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 3 +-- WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php | 3 +-- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index 368c0c3445..77fe5fb47f 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -6,7 +6,7 @@ * @category PHP * @package PHP_CodeSniffer */ -class WordPress_Sniffs_PHP_StrictInArraySniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { +class WordPress_Sniffs_PHP_StrictInArraySniff extends WordPress_Sniff { /** * Returns an array of tokens this test wants to listen for. diff --git a/WordPress/Sniffs/VIP/CronIntervalSniff.php b/WordPress/Sniffs/VIP/CronIntervalSniff.php index c777a53696..dbb8829594 100644 --- a/WordPress/Sniffs/VIP/CronIntervalSniff.php +++ b/WordPress/Sniffs/VIP/CronIntervalSniff.php @@ -6,8 +6,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_CronIntervalSniff implements PHP_CodeSniffer_Sniff -{ +class WordPress_Sniffs_VIP_CronIntervalSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index 1d8a0fbc41..800ff0327e 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -6,8 +6,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_PostsPerPageSniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff -{ +class WordPress_Sniffs_VIP_PostsPerPageSniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { /** * Groups of variables to restrict. diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index c60db82665..a2aec258c4 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -6,8 +6,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_Sniffs_Functions_FunctionRestrictionsSniff -{ +class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_Sniffs_Functions_FunctionRestrictionsSniff { /** * Groups of functions to restrict. From 6b64b1debbf48ca8307ebebbee2eb120c4a2ca20 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 13 Jul 2016 06:08:39 +0200 Subject: [PATCH 062/122] Documentation fixes. * Added generic file docblock to sniff files which didn't have one. * Added/replaced generic file docblock for all unit test files. * Use `@link` rather than `@see` for links to external documentation about a sniff in the file/class docblock. * Consistent placement of the `@link` tag if available and pointing to WPCS relevant info. * Removed `PHP version 5` notes. No longer relevant. * Fixed a few class description referring to the wrong rule/sniff. Docs still need a lot of love to get up to scratch properly. --- WordPress/Sniff.php | 2 -- .../Arrays/ArrayAssignmentRestrictionsSniff.php | 8 ++++++++ WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php | 2 -- .../Arrays/ArrayKeySpacingRestrictionsSniff.php | 10 +++++++++- WordPress/Sniffs/CSRF/NonceVerificationSniff.php | 7 +++---- WordPress/Sniffs/Classes/ValidClassNameSniff.php | 2 -- WordPress/Sniffs/Files/FileNameSniff.php | 5 +---- .../Functions/FunctionRestrictionsSniff.php | 8 ++++++++ .../NamingConventions/ValidFunctionNameSniff.php | 4 +--- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 2 -- WordPress/Sniffs/PHP/StrictComparisonsSniff.php | 10 ++++++++-- WordPress/Sniffs/PHP/StrictInArraySniff.php | 11 ++++++++++- WordPress/Sniffs/PHP/YodaConditionsSniff.php | 4 +--- WordPress/Sniffs/VIP/AdminBarRemovalSniff.php | 8 ++++++++ WordPress/Sniffs/VIP/CronIntervalSniff.php | 8 ++++++++ WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php | 11 +++++++++-- .../Sniffs/VIP/FileSystemWritesDisallowSniff.php | 13 ++++++++++--- WordPress/Sniffs/VIP/OrderByRandSniff.php | 11 ++++++++++- WordPress/Sniffs/VIP/PluginMenuSlugSniff.php | 10 +++++++++- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 8 ++++++++ WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php | 8 ++++++++ WordPress/Sniffs/VIP/RestrictedVariablesSniff.php | 8 ++++++++ .../Sniffs/VIP/SessionFunctionsUsageSniff.php | 11 ++++++++++- .../Sniffs/VIP/SessionVariableUsageSniff.php | 11 ++++++++++- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 8 ++++++++ .../Sniffs/VIP/SuperGlobalInputUsageSniff.php | 11 ++++++++++- WordPress/Sniffs/VIP/TimezoneChangeSniff.php | 11 ++++++++++- .../Sniffs/VIP/ValidatedSanitizedInputSniff.php | 10 ++++++++-- .../Sniffs/Variables/GlobalVariablesSniff.php | 8 ++++++++ .../Variables/VariableRestrictionsSniff.php | 8 ++++++++ WordPress/Sniffs/WP/EnqueuedResourcesSniff.php | 10 +++++++++- WordPress/Sniffs/WP/I18nSniff.php | 10 +++++++++- WordPress/Sniffs/WP/PreparedSQLSniff.php | 8 ++++++++ .../WhiteSpace/CastStructureSpacingSniff.php | 2 -- .../WhiteSpace/ControlStructureSpacingSniff.php | 2 -- .../Sniffs/WhiteSpace/OperatorSpacingSniff.php | 4 +--- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 5 ++--- .../ArrayAssignmentRestrictionsUnitTest.php | 8 ++++++++ .../Tests/Arrays/ArrayDeclarationUnitTest.php | 14 ++++---------- .../ArrayKeySpacingRestrictionsUnitTest.php | 8 ++++++++ .../Tests/CSRF/NonceVerificationUnitTest.php | 10 +++++++--- .../Tests/Classes/ValidClassNameUnitTest.php | 14 ++++---------- WordPress/Tests/Files/FileNameUnitTest.php | 14 ++++---------- .../ValidFunctionNameUnitTest.php | 14 ++++---------- .../ValidVariableNameUnitTest.php | 15 ++++----------- .../Tests/PHP/DiscouragedFunctionsUnitTest.php | 14 ++++---------- WordPress/Tests/PHP/StrictComparisonsUnitTest.php | 12 ++++-------- WordPress/Tests/PHP/StrictInArrayUnitTest.php | 12 ++++-------- WordPress/Tests/PHP/YodaConditionsUnitTest.php | 12 ++++-------- WordPress/Tests/VIP/AdminBarRemovalUnitTest.php | 8 ++++++++ WordPress/Tests/VIP/CronIntervalUnitTest.php | 8 ++++++++ .../Tests/VIP/DirectDatabaseQueryUnitTest.php | 11 ++++++++--- .../VIP/FileSystemWritesDisallowUnitTest.php | 11 ++++++++--- WordPress/Tests/VIP/OrderByRandUnitTest.php | 8 ++++++++ WordPress/Tests/VIP/PluginMenuSlugUnitTest.php | 8 ++++++++ WordPress/Tests/VIP/PostsPerPageUnitTest.php | 8 ++++++++ .../Tests/VIP/RestrictedFunctionsUnitTest.php | 8 ++++++++ .../Tests/VIP/RestrictedVariablesUnitTest.php | 8 ++++++++ .../Tests/VIP/SessionFunctionsUsageUnitTest.php | 11 ++++++++--- .../Tests/VIP/SessionVariableUsageUnitTest.php | 11 ++++++++--- WordPress/Tests/VIP/SlowDBQueryUnitTest.php | 8 ++++++++ .../Tests/VIP/SuperGlobalInputUsageUnitTest.php | 11 ++++++++--- WordPress/Tests/VIP/TimezoneChangeUnitTest.php | 11 ++++++++--- .../Tests/VIP/ValidatedSanitizedInputUnitTest.php | 11 ++++++++--- .../Tests/Variables/GlobalVariablesUnitTest.php | 8 ++++++++ .../Variables/VariableRestrictionsUnitTest.php | 8 ++++++++ WordPress/Tests/WP/EnqueuedResourcesUnitTest.php | 10 ++++++++-- WordPress/Tests/WP/I18nUnitTest.php | 10 ++++++++-- WordPress/Tests/WP/PreparedSQLUnitTest.php | 7 ++++--- .../WhiteSpace/CastStructureSpacingUnitTest.php | 12 ++++-------- .../ControlStructureSpacingUnitTest.php | 14 ++++---------- .../Tests/WhiteSpace/OperatorSpacingUnitTest.php | 14 ++++---------- WordPress/Tests/XSS/EscapeOutputUnitTest.php | 14 ++++---------- 73 files changed, 459 insertions(+), 205 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index f0ff14a49b..a61440cbb6 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -2,8 +2,6 @@ /** * Represents a PHP_CodeSniffer sniff for sniffing WordPress coding standards. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer */ diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index d3358437ce..8505110adb 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -1,4 +1,12 @@ diff --git a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php index bb7742a87c..1950547ed6 100644 --- a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php @@ -1,8 +1,16 @@ - * @link https://developer.wordpress.org/plugins/security/nonces/ Nonces on Plugin Developer Handbook */ class WordPress_Sniffs_CSRF_NonceVerificationSniff extends WordPress_Sniff { diff --git a/WordPress/Sniffs/Classes/ValidClassNameSniff.php b/WordPress/Sniffs/Classes/ValidClassNameSniff.php index 35e513d8aa..c5c2bd31f2 100644 --- a/WordPress/Sniffs/Classes/ValidClassNameSniff.php +++ b/WordPress/Sniffs/Classes/ValidClassNameSniff.php @@ -2,8 +2,6 @@ /** * Modified Squiz_Sniffs_Classes_ValidClassNameSniff. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood diff --git a/WordPress/Sniffs/Files/FileNameSniff.php b/WordPress/Sniffs/Files/FileNameSniff.php index eb15d3843d..4e24b72b8a 100644 --- a/WordPress/Sniffs/Files/FileNameSniff.php +++ b/WordPress/Sniffs/Files/FileNameSniff.php @@ -2,12 +2,9 @@ /** * WordPress Coding Standard. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer - * @author John Godley - * @link http://codex.wordpress.org/WordPress_Coding_Standards + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php index d8f74a5b4f..0c9367ab12 100644 --- a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php +++ b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php @@ -1,4 +1,12 @@ */ /** - * Enforces WordPress array format. + * Enforces WordPress function name format. * * @category PHP * @package PHP_CodeSniffer diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index 898d8b5dc8..9afd07deda 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -2,8 +2,6 @@ /** * WordPress_Sniffs_PHP_DiscouragedFunctionsSniff. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer * @author John Godley diff --git a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php index 1b6b9368e1..8a7f94af98 100644 --- a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php +++ b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php @@ -1,8 +1,14 @@ - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 */ class WordPress_Sniffs_VIP_DirectDatabaseQuerySniff implements PHP_CodeSniffer_Sniff { diff --git a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php index 28749570eb..3e9897e4ff 100644 --- a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php +++ b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php @@ -1,13 +1,20 @@ - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 */ class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { diff --git a/WordPress/Sniffs/VIP/OrderByRandSniff.php b/WordPress/Sniffs/VIP/OrderByRandSniff.php index a3e8bfdc17..fe93e57577 100644 --- a/WordPress/Sniffs/VIP/OrderByRandSniff.php +++ b/WordPress/Sniffs/VIP/OrderByRandSniff.php @@ -1,8 +1,17 @@ rand. * - * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#order-by-rand + * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#order-by-rand + * * @category PHP * @package PHP_CodeSniffer */ diff --git a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php index 7ef6066fae..4a6ea1ba27 100644 --- a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php +++ b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php @@ -1,6 +1,14 @@ - * @see https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ class WordPress_Sniffs_VIP_SessionFunctionsUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { diff --git a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php index b823ace6fa..6b2c73b338 100644 --- a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php @@ -1,14 +1,23 @@ - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index 1f1df05724..d0ad890a5a 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -1,4 +1,12 @@ - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/79 */ class WordPress_Sniffs_VIP_SuperGlobalInputUsageSniff extends WordPress_Sniff { diff --git a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php index 3d771790f9..58dcafe6f8 100644 --- a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php +++ b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php @@ -1,13 +1,22 @@ - * @see http://vip.wordpress.com/documentation/use-current_time-not-date_default_timezone_set/ */ class WordPress_Sniffs_VIP_TimezoneChangeSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { diff --git a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php index 419a176bab..d000d94599 100644 --- a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php +++ b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php @@ -1,14 +1,20 @@ - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 */ class WordPress_Sniffs_VIP_ValidatedSanitizedInputSniff extends WordPress_Sniff { diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index ca26f59724..3fa3fd8c81 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -1,4 +1,12 @@ diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index f5088e9cce..571ffae3b4 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -2,8 +2,6 @@ /** * Enforces spacing around logical operators and assignments, based upon Squiz code. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer * @author John Godley diff --git a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php index 724055bf3b..89941a5c76 100644 --- a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -2,8 +2,6 @@ /** * Modified version of Squiz operator white spacing, based upon Squiz code * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood @@ -11,7 +9,7 @@ */ /** - * Enforces WordPress array format + * Modified version of Squiz operator white spacing. * * @category PHP * @package PHP_CodeSniffer diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 924fc66e4b..3ee31b4a81 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -2,8 +2,6 @@ /** * Squiz_Sniffs_XSS_EscapeOutputSniff. * - * PHP version 5 - * * @category PHP * @package PHP_CodeSniffer * @author Weston Ruter @@ -12,10 +10,11 @@ /** * Verifies that all outputted strings are escaped. * + * @link http://codex.wordpress.org/Data_Validation Data Validation on WordPress Codex + * * @category PHP * @package PHP_CodeSniffer * @author Weston Ruter - * @link http://codex.wordpress.org/Data_Validation Data Validation on WordPress Codex */ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php index 7ee0061cab..32be51af7f 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php @@ -1,4 +1,12 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php index ced0f2614d..0298fe50b5 100644 --- a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.php @@ -1,4 +1,12 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_CSRF_NonceVerificationUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/Classes/ValidClassNameUnitTest.php b/WordPress/Tests/Classes/ValidClassNameUnitTest.php index 58b42a1ca2..2469ffeca7 100644 --- a/WordPress/Tests/Classes/ValidClassNameUnitTest.php +++ b/WordPress/Tests/Classes/ValidClassNameUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/Files/FileNameUnitTest.php b/WordPress/Tests/Files/FileNameUnitTest.php index a352e6f451..7770770826 100644 --- a/WordPress/Tests/Files/FileNameUnitTest.php +++ b/WordPress/Tests/Files/FileNameUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php index 156c00b9ce..d33b7ab8e2 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index fecb971dfd..fbbb92876c 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -1,17 +1,10 @@ - * @author Marc McIntyre - * @author Weston Ruter - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php index 40b2ec26fe..80640d2e62 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php index e99b4bb34a..0c2e6c1888 100644 --- a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php +++ b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php @@ -1,14 +1,10 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_DirectDatabaseQueryUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php index d5552d34ed..575fc68a3b 100644 --- a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php +++ b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php @@ -1,15 +1,20 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_FileSystemWritesDisallowUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/OrderByRandUnitTest.php b/WordPress/Tests/VIP/OrderByRandUnitTest.php index df85a7109f..3faadd2216 100644 --- a/WordPress/Tests/VIP/OrderByRandUnitTest.php +++ b/WordPress/Tests/VIP/OrderByRandUnitTest.php @@ -1,4 +1,12 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_SessionFunctionsUsageUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php index 89f0701dcb..c6cc975887 100644 --- a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php @@ -1,15 +1,20 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php index 8fd81bb3eb..07b3b00a9b 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php @@ -1,4 +1,12 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_SuperGlobalInputUsageUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php index d7ac7e0f21..48247224a6 100644 --- a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php +++ b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php @@ -1,15 +1,20 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_TimezoneChangeUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php index 9a8516d899..1313dcd1f9 100644 --- a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php +++ b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php @@ -1,15 +1,20 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ - class WordPress_Tests_VIP_ValidatedSanitizedInputUnitTest extends AbstractSniffUnitTest { /** diff --git a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php index d289daddbe..2881082b4a 100644 --- a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php +++ b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php @@ -1,4 +1,12 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php index 8553def0db..4f2bab3a05 100644 --- a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.php b/WordPress/Tests/XSS/EscapeOutputUnitTest.php index 2b8b7583a2..c9fb7812fe 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.php +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.php @@ -1,16 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @category PHP + * @package PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ /** From 3b48438ce1848cc0862986f5e71f4e9204ae638c Mon Sep 17 00:00:00 2001 From: Stephen Edgar Date: Wed, 13 Jul 2016 16:08:30 +1000 Subject: [PATCH 063/122] Travis CI: Upgrade the HHVM job to use Ubuntu Trusty, and a more recent version of HHVM. --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index 4905d2588f..3c0f4866df 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,6 +23,9 @@ matrix: env: PHPCS_BRANCH=3.0 # Run against HHVM and PHP nightly. - php: hhvm + sudo: required + dist: trusty + group: edge env: PHPCS_BRANCH=master - php: nightly env: PHPCS_BRANCH=master From 99556d44428837547f15c2c089683c87394cb9fd Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 02:06:34 +0200 Subject: [PATCH 064/122] Add sniff for (no) closing PHP tag at end of file to `core` ruleset. --- WordPress-Core/ruleset.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 35db8e6dbd..76a5004843 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -14,6 +14,7 @@ + From a4879d40a90471afb5c4076957206ca9b72bd695 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 12 Jul 2016 23:53:17 +0200 Subject: [PATCH 065/122] Up the minimum PHPCS version to 2.4.0. --- .travis.yml | 2 +- composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 4905d2588f..55240291a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ php: env: - PHPCS_BRANCH=master - - PHPCS_BRANCH=2.2.0 + - PHPCS_BRANCH=2.4.0 matrix: fast_finish: true diff --git a/composer.json b/composer.json index 22dc43551f..b3566a6ba0 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ } ], "require" : { - "squizlabs/php_codesniffer": "~2.2" + "squizlabs/php_codesniffer": "^2.4" }, "minimum-stability" : "RC", "support" : { From e41418533b7b2de459862745d3152001169b5dd5 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 04:18:04 +0200 Subject: [PATCH 066/122] Add sniff to detect lowercase CONSTANT definitions. --- WordPress-Core/ruleset.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 35db8e6dbd..f268f3f87a 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -21,9 +21,14 @@ + + + + + From 057960bed564448bfb773b7cdf3d0b0e2a6012a6 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 19:10:36 +0200 Subject: [PATCH 067/122] Up the minimum required PHPCS version to 2.6. PHPCS 2.6 contains a fix for the bug reported in issue #698. PHPCS 2.6 also [contains a fix](https://github.com/squizlabs/PHP_CodeSniffer/pull/581) which will allow for checking that [`include/require` statements have DocBlocks](https://make.wordpress.org/core/handbook/best-practices/inline-documentation-standards/php/#3-requires-and-includes) as required by the handbook. Closes #566 --- .travis.yml | 2 +- composer.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 09f338fc5f..ea05038248 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ php: env: - PHPCS_BRANCH=master - - PHPCS_BRANCH=2.4.0 + - PHPCS_BRANCH=2.6.0 matrix: fast_finish: true diff --git a/composer.json b/composer.json index b3566a6ba0..7c047bb9f5 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ } ], "require" : { - "squizlabs/php_codesniffer": "^2.4" + "squizlabs/php_codesniffer": "^2.6" }, "minimum-stability" : "RC", "support" : { From f6af70cee82c30fd7374d3b76d06269e8c604692 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 03:39:27 +0200 Subject: [PATCH 068/122] Add unit test to reproduce the bug. --- .../ControlStructureSpacingUnitTest.inc | 23 +++++++++++++++++++ .../ControlStructureSpacingUnitTest.inc.fixed | 23 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc index 79a5b286d4..076a4d744b 100644 --- a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc +++ b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc @@ -107,3 +107,26 @@ function ( $arg ) {} // OK $closureWithArgsAndVars = function( $arg1, $arg2 ) use ( $var1, $var2 ) {}; // OK $closureWithArgsAndVars = function ( $arg1, $arg2 ) use ( $var1, $var2 ) {}; // OK + +/** + * Test for bug where this sniff was triggering a "Blank line found after control structure" error + * if there is a blank line after the last method in a class. + * + * Bug did not trigger when a comment was found after the closing brace of the method. + * + * Neither of the below examples should trigger the error. + */ +class Bar_Foo { + + function foo() { + } // Now you won't see the bug. + +} + +class Foo_Bar { + + // Now you will. + function bar() { + } + +} diff --git a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed index 0111fd31e6..de40bc4073 100644 --- a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed +++ b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed @@ -103,3 +103,26 @@ function ( $arg ) {} // OK $closureWithArgsAndVars = function( $arg1, $arg2 ) use ( $var1, $var2 ) {}; // OK $closureWithArgsAndVars = function ( $arg1, $arg2 ) use ( $var1, $var2 ) {}; // OK + +/** + * Test for bug where this sniff was triggering a "Blank line found after control structure" error + * if there is a blank line after the last method in a class. + * + * Bug did not trigger when a comment was found after the closing brace of the method. + * + * Neither of the below examples should trigger the error. + */ +class Bar_Foo { + + function foo() { + } // Now you won't see the bug. + +} + +class Foo_Bar { + + // Now you will. + function bar() { + } + +} From eee2279c6231511a2c8cffce067c44b88ae6bc86 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 20:05:51 +0200 Subject: [PATCH 069/122] Fix bug in control structures whitespace sniff triggered on last method of class. --- .../Sniffs/WhiteSpace/ControlStructureSpacingSniff.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index 571ffae3b4..1e901f460f 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -495,9 +495,9 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Another control structure's closing brace. if ( isset( $tokens[ $trailingContent ]['scope_condition'] ) ) { $owner = $tokens[ $trailingContent ]['scope_condition']; - if ( T_FUNCTION === $tokens[ $owner ]['code'] ) { - // The next content is the closing brace of a function - // so normal function rules apply and we can ignore it. + if ( in_array( $tokens[ $owner ]['code'], array( T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT ), true ) ) { + // The next content is the closing brace of a function, class, interface or trait + // so normal function/class rules apply and we can ignore it. return; } } From d6eceb353def4b2367227ec363dff5a71cd1d073 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 20:32:35 +0200 Subject: [PATCH 070/122] Add PHP syntax check sniff to the `core` ruleset. --- WordPress-Core/ruleset.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 76a5004843..5f14ac52e0 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -2,6 +2,9 @@ Non-controversial generally-agreed upon WordPress Coding Standards + + + From 17bfbbc4b60cf5bc67e5b837a1a5ebc64d2cc8ef Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 15 Jul 2016 23:47:53 +0200 Subject: [PATCH 071/122] Turn the three abstract classes into proper abstracts. --- ...stractArrayAssignmentRestrictionsSniff.php | 198 ++++++++++++++++++ .../AbstractFunctionRestrictionsSniff.php | 133 ++++++++++++ .../AbstractVariableRestrictionsSniff.php | 178 ++++++++++++++++ .../ArrayAssignmentRestrictionsSniff.php | 159 +------------- .../Functions/FunctionRestrictionsSniff.php | 105 +--------- WordPress/Sniffs/VIP/OrderByRandSniff.php | 2 +- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 2 +- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 2 +- .../Sniffs/VIP/RestrictedVariablesSniff.php | 2 +- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 17 +- .../Variables/VariableRestrictionsSniff.php | 152 +------------- .../ArrayAssignmentRestrictionsUnitTest.php | 2 +- .../VariableRestrictionsUnitTest.php | 2 +- 13 files changed, 556 insertions(+), 398 deletions(-) create mode 100644 WordPress/AbstractArrayAssignmentRestrictionsSniff.php create mode 100644 WordPress/AbstractFunctionRestrictionsSniff.php create mode 100644 WordPress/AbstractVariableRestrictionsSniff.php diff --git a/WordPress/AbstractArrayAssignmentRestrictionsSniff.php b/WordPress/AbstractArrayAssignmentRestrictionsSniff.php new file mode 100644 index 0000000000..f875bc9d7c --- /dev/null +++ b/WordPress/AbstractArrayAssignmentRestrictionsSniff.php @@ -0,0 +1,198 @@ + + */ +abstract class WordPress_AbstractArrayAssignmentRestrictionsSniff extends WordPress_Sniff { + + /** + * Exclude groups. + * + * Example: 'foo,bar' + * + * @var string Comma-delimited group list. + */ + public $exclude = ''; + + /** + * Groups of variable data to check against. + * Don't use this in extended classes, override getGroups() instead. + * This is only used for Unit tests. + * + * @var array + */ + public static $groups = array(); + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_DOUBLE_ARROW, + T_CLOSE_SQUARE_BRACKET, + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + ); + + } // end register() + + /** + * Groups of variables to restrict. + * + * This method should be overridden in extending classes. + * + * Example: groups => array( + * 'wpdb' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Dont use this one please!', + * 'variables' => array( '$val', '$var' ), + * 'object_vars' => array( '$foo->bar', .. ), + * 'array_members' => array( '$foo['bar']', .. ), + * ) + * ) + * + * @return array + */ + abstract public function getGroups(); + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + + $groups = $this->getGroups(); + + if ( empty( $groups ) ) { + $phpcsFile->removeTokenListener( $this, $this->register() ); + return; + } + + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + $exclude = explode( ',', $this->exclude ); + + if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET ), true ) ) { + $equal = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + if ( T_EQUAL !== $tokens[ $equal ]['code'] ) { + return; // This is not an assignment! + } + } + + // Instances: Multi-dimensional array, keyed by line. + $inst = array(); + + /* + Covers: + $foo = array( 'bar' => 'taz' ); + $foo['bar'] = $taz; + */ + if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET, T_DOUBLE_ARROW ), true ) ) { + if ( T_CLOSE_SQUARE_BRACKET === $token['code'] ) { + $operator = $phpcsFile->findNext( array( T_EQUAL ), ( $stackPtr + 1 ) ); + } elseif ( T_DOUBLE_ARROW === $token['code'] ) { + $operator = $stackPtr; + } + $keyIdx = $phpcsFile->findPrevious( array( T_WHITESPACE, T_CLOSE_SQUARE_BRACKET ), ( $operator - 1 ), null, true ); + if ( ! is_numeric( $tokens[ $keyIdx ]['content'] ) ) { + $key = trim( $tokens[ $keyIdx ]['content'], '\'"' ); + $valStart = $phpcsFile->findNext( array( T_WHITESPACE ), ( $operator + 1 ), null, true ); + $valEnd = $phpcsFile->findNext( array( T_COMMA, T_SEMICOLON ), ( $valStart + 1 ), null, false, null, true ); + $val = $phpcsFile->getTokensAsString( $valStart, ( $valEnd - $valStart ) ); + $val = trim( $val, '\'"' ); + $inst[ $key ][] = array( $val, $token['line'] ); + } + } elseif ( in_array( $token['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { + // $foo = 'bar=taz&other=thing'; + if ( preg_match_all( '#[\'"&]([a-z_]+)=([^\'"&]*)#i', $token['content'], $matches ) <= 0 ) { + return; // No assignments here, nothing to check. + } + foreach ( $matches[1] as $i => $_k ) { + $inst[ $_k ][] = array( $matches[2][ $i ], $token['line'] ); + } + } + + if ( empty( $inst ) ) { + return; + } + + foreach ( $groups as $groupName => $group ) { + + if ( in_array( $groupName, $exclude, true ) ) { + continue; + } + + $callback = ( isset( $group['callback'] ) && is_callable( $group['callback'] ) ) ? $group['callback'] : array( $this, 'callback' ); + + foreach ( $inst as $key => $assignments ) { + foreach ( $assignments as $occurance ) { + list( $val, $line ) = $occurance; + + if ( ! in_array( $key, $group['keys'], true ) ) { + continue; + } + + $output = call_user_func( $callback, $key, $val, $line, $group ); + + if ( ! isset( $output ) || false === $output ) { + continue; + } elseif ( true === $output ) { + $message = $group['message']; + } else { + $message = $output; + } + + if ( 'warning' === $group['type'] ) { + $addWhat = array( $phpcsFile, 'addWarning' ); + } else { + $addWhat = array( $phpcsFile, 'addError' ); + } + + call_user_func( + $addWhat, + $message, + $stackPtr, + $groupName, + array( $key, $val ) + ); + } + } + + // return; // Show one error only. + } + + } // end process() + + /** + * Callback to process each confirmed key, to check value. + * + * This method must be extended to add the logic to check assignment value. + * + * @param string $key Array index / key. + * @param mixed $val Assigned value. + * @param int $line Token line. + * @param array $group Group definition. + * @return mixed FALSE if no match, TRUE if matches, STRING if matches + * with custom error message passed to ->process(). + */ + abstract public function callback( $key, $val, $line, $group ); + +} // end class diff --git a/WordPress/AbstractFunctionRestrictionsSniff.php b/WordPress/AbstractFunctionRestrictionsSniff.php new file mode 100644 index 0000000000..30883926bd --- /dev/null +++ b/WordPress/AbstractFunctionRestrictionsSniff.php @@ -0,0 +1,133 @@ + + */ +abstract class WordPress_AbstractFunctionRestrictionsSniff implements PHP_CodeSniffer_Sniff { + + /** + * Exclude groups. + * + * Example: 'switch_to_blog,user_meta' + * + * @var string Comma-delimited group list. + */ + public $exclude = ''; + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_STRING, + T_EVAL, + ); + + } // end register() + + /** + * Groups of functions to restrict. + * + * This method should be overridden in extending classes. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', + * 'functions' => array( 'eval', 'create_function' ), + * ) + * ) + * + * @return array + */ + abstract public function getGroups(); + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + + // Exclude function definitions, class methods, and namespaced calls. + if ( + T_STRING === $token['code'] + && + ( $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true ) ) + && + ( + // Skip sniffing if calling a method, or on function definitions. + in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) + || + ( + // Skip namespaced functions, ie: \foo\bar() not \bar(). + T_NS_SEPARATOR === $tokens[ $prev ]['code'] + && + ( $pprev = $phpcsFile->findPrevious( T_WHITESPACE, ( $prev - 1 ), null, true ) ) + && + T_STRING === $tokens[ $pprev ]['code'] + ) + ) + ) { + return; + } + + $exclude = explode( ',', $this->exclude ); + + $groups = $this->getGroups(); + + if ( empty( $groups ) ) { + return ( count( $tokens ) + 1 ); + } + + foreach ( $groups as $groupName => $group ) { + + if ( in_array( $groupName, $exclude, true ) ) { + continue; + } + + $functions = implode( '|', $group['functions'] ); + $functions = preg_replace( '#[^\.]\*#', '.*', $functions ); // So you can use * instead of .* + + if ( preg_match( '#\b(' . $functions . ')\b#', $token['content'] ) < 1 ) { + continue; + } + + if ( 'warning' === $group['type'] ) { + $addWhat = array( $phpcsFile, 'addWarning' ); + } else { + $addWhat = array( $phpcsFile, 'addError' ); + } + + call_user_func( + $addWhat, + $group['message'], + $stackPtr, + $groupName, + array( $token['content'] ) + ); + + } + + } // end process() + +} // end class diff --git a/WordPress/AbstractVariableRestrictionsSniff.php b/WordPress/AbstractVariableRestrictionsSniff.php new file mode 100644 index 0000000000..530f809313 --- /dev/null +++ b/WordPress/AbstractVariableRestrictionsSniff.php @@ -0,0 +1,178 @@ + + */ +abstract class WordPress_AbstractVariableRestrictionsSniff implements PHP_CodeSniffer_Sniff { + + /** + * Exclude groups. + * + * Example: 'foo,bar' + * + * @var string Comma-delimited group list. + */ + public $exclude = ''; + + /** + * Groups of variable data to check against. + * Don't use this in extended classes, override getGroups() instead. + * This is only used for Unit tests. + * + * @var array + */ + public static $groups = array(); + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_VARIABLE, + T_OBJECT_OPERATOR, + T_DOUBLE_COLON, + T_OPEN_SQUARE_BRACKET, + T_DOUBLE_QUOTED_STRING, + ); + + } // end register() + + /** + * Groups of variables to restrict. + * + * This method should be overridden in extending classes. + * + * Example: groups => array( + * 'wpdb' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Dont use this one please!', + * 'variables' => array( '$val', '$var' ), + * 'object_vars' => array( '$foo->bar', .. ), + * 'array_members' => array( '$foo['bar']', .. ), + * ) + * ) + * + * @return array + */ + abstract public function getGroups(); + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + $exclude = explode( ',', $this->exclude ); + $groups = $this->getGroups(); + + if ( empty( $groups ) ) { + return ( count( $tokens ) + 1 ); + } + + // Check if it is a function not a variable. + if ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) { // This only works for object vars and array members. + $method = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + $possible_parenthesis = $phpcsFile->findNext( T_WHITESPACE, ( $method + 1 ), null, true ); + if ( T_OPEN_PARENTHESIS === $tokens[ $possible_parenthesis ]['code'] ) { + return; // So .. it is a function after all ! + } + } + + foreach ( $groups as $groupName => $group ) { + + if ( in_array( $groupName, $exclude, true ) ) { + continue; + } + + $patterns = array(); + + // Simple variable. + if ( in_array( $token['code'], array( T_VARIABLE, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['variables'] ) ) { + $patterns = array_merge( $patterns, $group['variables'] ); + $var = $token['content']; + + } elseif ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['object_vars'] ) ) { + // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar + $patterns = array_merge( $patterns, $group['object_vars'] ); + + $owner = $phpcsFile->findPrevious( array( T_VARIABLE, T_STRING ), $stackPtr ); + $child = $phpcsFile->findNext( array( T_STRING, T_VAR, T_VARIABLE ), $stackPtr ); + $var = implode( '', array( $tokens[ $owner ]['content'], $token['content'], $tokens[ $child ]['content'] ) ); + + } elseif ( in_array( $token['code'], array( T_OPEN_SQUARE_BRACKET, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['array_members'] ) ) { + // Array members. + $patterns = array_merge( $patterns, $group['array_members'] ); + + $owner = $phpcsFile->findPrevious( array( T_VARIABLE ), $stackPtr ); + $inside = $phpcsFile->getTokensAsString( $stackPtr, ( $token['bracket_closer'] - $stackPtr + 1 ) ); + $var = implode( '', array( $tokens[ $owner ]['content'], $inside ) ); + } else { + continue; + } + + if ( empty( $patterns ) ) { + continue; + } + + $patterns = array_map( array( $this, 'test_patterns' ), $patterns ); + $pattern = implode( '|', $patterns ); + $delim = ( T_OPEN_SQUARE_BRACKET !== $token['code'] ) ? '\b' : ''; + + if ( T_DOUBLE_QUOTED_STRING === $token['code'] ) { + $var = $token['content']; + } + + if ( preg_match( '#(' . $pattern . ')' . $delim . '#', $var, $match ) !== 1 ) { + continue; + } + + if ( 'warning' === $group['type'] ) { + $addWhat = array( $phpcsFile, 'addWarning' ); + } else { + $addWhat = array( $phpcsFile, 'addError' ); + } + + call_user_func( + $addWhat, + $group['message'], + $stackPtr, + $groupName, + array( $var ) + ); + + return; // Show one error only. + + } + + } // end process() + + private function test_patterns( $pattern ) { + $pattern = preg_quote( $pattern, '#' ); + $pattern = preg_replace( + array( '#\\\\\*#', '[\'"]' ), + array( '.*', '\'' ), + $pattern + ); + return $pattern; + } // end test_patterns() + +} // end class diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index 8505110adb..0fb0f044b9 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -10,48 +10,21 @@ /** * Restricts array assignment of certain keys. * + * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractArrayAssignmentRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * This file is also still used to unit test the abstract class. + * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_Sniff { - - /** - * Exclude groups. - * - * Example: 'foo,bar' - * - * @var string Comma-delimited group list. - */ - public $exclude = ''; - - /** - * Groups of variable data to check against. - * Don't use this in extended classes, override getGroups() instead. - * This is only used for Unit tests. - * - * @var array - */ - public static $groups = array(); - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() { - return array( - T_DOUBLE_ARROW, - T_CLOSE_SQUARE_BRACKET, - T_CONSTANT_ENCAPSED_STRING, - T_DOUBLE_QUOTED_STRING, - ); - - } // end register() +class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { /** * Groups of variables to restrict. - * This should be overridden in extending classes. * * Example: groups => array( * 'wpdb' => array( @@ -66,125 +39,11 @@ public function register() { * @return array */ public function getGroups() { - return self::$groups; + return parent::$groups; } - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { - - $groups = $this->getGroups(); - - if ( empty( $groups ) ) { - $phpcsFile->removeTokenListener( $this, $this->register() ); - return; - } - - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; - $exclude = explode( ',', $this->exclude ); - - if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET ), true ) ) { - $equal = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); - if ( T_EQUAL !== $tokens[ $equal ]['code'] ) { - return; // This is not an assignment! - } - } - - // Instances: Multi-dimensional array, keyed by line. - $inst = array(); - - /* - Covers: - $foo = array( 'bar' => 'taz' ); - $foo['bar'] = $taz; - */ - if ( in_array( $token['code'], array( T_CLOSE_SQUARE_BRACKET, T_DOUBLE_ARROW ), true ) ) { - if ( T_CLOSE_SQUARE_BRACKET === $token['code'] ) { - $operator = $phpcsFile->findNext( array( T_EQUAL ), ( $stackPtr + 1 ) ); - } elseif ( T_DOUBLE_ARROW === $token['code'] ) { - $operator = $stackPtr; - } - $keyIdx = $phpcsFile->findPrevious( array( T_WHITESPACE, T_CLOSE_SQUARE_BRACKET ), ( $operator - 1 ), null, true ); - if ( ! is_numeric( $tokens[ $keyIdx ]['content'] ) ) { - $key = trim( $tokens[ $keyIdx ]['content'], '\'"' ); - $valStart = $phpcsFile->findNext( array( T_WHITESPACE ), ( $operator + 1 ), null, true ); - $valEnd = $phpcsFile->findNext( array( T_COMMA, T_SEMICOLON ), ( $valStart + 1 ), null, false, null, true ); - $val = $phpcsFile->getTokensAsString( $valStart, ( $valEnd - $valStart ) ); - $val = trim( $val, '\'"' ); - $inst[ $key ][] = array( $val, $token['line'] ); - } - } elseif ( in_array( $token['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { - // $foo = 'bar=taz&other=thing'; - if ( preg_match_all( '#[\'"&]([a-z_]+)=([^\'"&]*)#i', $token['content'], $matches ) <= 0 ) { - return; // No assignments here, nothing to check. - } - foreach ( $matches[1] as $i => $_k ) { - $inst[ $_k ][] = array( $matches[2][ $i ], $token['line'] ); - } - } - - if ( empty( $inst ) ) { - return; - } - - foreach ( $groups as $groupName => $group ) { - - if ( in_array( $groupName, $exclude, true ) ) { - continue; - } - - $callback = ( isset( $group['callback'] ) && is_callable( $group['callback'] ) ) ? $group['callback'] : array( $this, 'callback' ); - - foreach ( $inst as $key => $assignments ) { - foreach ( $assignments as $occurance ) { - list( $val, $line ) = $occurance; - - if ( ! in_array( $key, $group['keys'], true ) ) { - continue; - } - - $output = call_user_func( $callback, $key, $val, $line, $group ); - - if ( ! isset( $output ) || false === $output ) { - continue; - } elseif ( true === $output ) { - $message = $group['message']; - } else { - $message = $output; - } - - if ( 'warning' === $group['type'] ) { - $addWhat = array( $phpcsFile, 'addWarning' ); - } else { - $addWhat = array( $phpcsFile, 'addError' ); - } - - call_user_func( - $addWhat, - $message, - $stackPtr, - $groupName, - array( $key, $val ) - ); - } - } - - // return; // Show one error only. - } - - } // end process() - /** * Callback to process each confirmed key, to check value. - * This must be extended to add the logic to check assignment value. * * @param string $key Array index / key. * @param mixed $val Assigned value. diff --git a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php index 0c9367ab12..eeae1eddb0 100644 --- a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php +++ b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php @@ -10,33 +10,17 @@ /** * Restricts usage of some functions. * + * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractFunctionRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_Functions_FunctionRestrictionsSniff implements PHP_CodeSniffer_Sniff { - - /** - * Exclude groups. - * - * Example: 'switch_to_blog,user_meta' - * - * @var string Comma-delimited group list. - */ - public $exclude = ''; - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() { - return array( - T_STRING, - T_EVAL, - ); - - } // end register() +class WordPress_Sniffs_Functions_FunctionRestrictionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { /** * Groups of functions to restrict. @@ -55,79 +39,4 @@ public function getGroups() { return array(); } - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; - - // Exclude function definitions, class methods, and namespaced calls. - if ( - T_STRING === $token['code'] - && - ( $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true ) ) - && - ( - // Skip sniffing if calling a method, or on function definitions. - in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) - || - ( - // Skip namespaced functions, ie: \foo\bar() not \bar(). - T_NS_SEPARATOR === $tokens[ $prev ]['code'] - && - ( $pprev = $phpcsFile->findPrevious( T_WHITESPACE, ( $prev - 1 ), null, true ) ) - && - T_STRING === $tokens[ $pprev ]['code'] - ) - ) - ) { - return; - } - - $exclude = explode( ',', $this->exclude ); - - $groups = $this->getGroups(); - - if ( empty( $groups ) ) { - return ( count( $tokens ) + 1 ); - } - - foreach ( $groups as $groupName => $group ) { - - if ( in_array( $groupName, $exclude, true ) ) { - continue; - } - - $functions = implode( '|', $group['functions'] ); - $functions = preg_replace( '#[^\.]\*#', '.*', $functions ); // So you can use * instead of .* - - if ( preg_match( '#\b(' . $functions . ')\b#', $token['content'] ) < 1 ) { - continue; - } - - if ( 'warning' === $group['type'] ) { - $addWhat = array( $phpcsFile, 'addWarning' ); - } else { - $addWhat = array( $phpcsFile, 'addError' ); - } - - call_user_func( - $addWhat, - $group['message'], - $stackPtr, - $groupName, - array( $token['content'] ) - ); - - } - - } // end process() - } // end class diff --git a/WordPress/Sniffs/VIP/OrderByRandSniff.php b/WordPress/Sniffs/VIP/OrderByRandSniff.php index fe93e57577..9e05d9aae1 100644 --- a/WordPress/Sniffs/VIP/OrderByRandSniff.php +++ b/WordPress/Sniffs/VIP/OrderByRandSniff.php @@ -15,7 +15,7 @@ * @category PHP * @package PHP_CodeSniffer */ -class WordPress_Sniffs_VIP_OrderByRandSniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { +class WordPress_Sniffs_VIP_OrderByRandSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { /** * Groups of variables to restrict. diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index 590c8e6a59..23d456cb6a 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -14,7 +14,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_PostsPerPageSniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { +class WordPress_Sniffs_VIP_PostsPerPageSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { /** * Groups of variables to restrict. diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 0f828ccb45..0976874cb5 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -14,7 +14,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_Sniffs_Functions_FunctionRestrictionsSniff { +class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { /** * Groups of functions to restrict. diff --git a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php index 1ac2ac2f93..cd3a48c059 100644 --- a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php @@ -14,7 +14,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_Sniffs_Variables_VariableRestrictionsSniff { +class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_AbstractVariableRestrictionsSniff { /** * Groups of variables to restrict. diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index d0ad890a5a..1d7dd024d8 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -14,7 +14,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff { +class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { /** * Groups of variables to restrict. @@ -67,4 +67,19 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { parent::process( $phpcsFile, $stackPtr ); } // end process() + /** + * Callback to process each confirmed key, to check value. + * This must be extended to add the logic to check assignment value. + * + * @param string $key Array index / key. + * @param mixed $val Assigned value. + * @param int $line Token line. + * @param array $group Group definition. + * @return mixed FALSE if no match, TRUE if matches, STRING if matches + * with custom error message passed to ->process(). + */ + public function callback( $key, $val, $line, $group ) { + return true; + } // end callback() + } // end class diff --git a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php index e0b99d43ec..6a2e86950e 100644 --- a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php +++ b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php @@ -10,49 +10,21 @@ /** * Restricts usage of some variables. * + * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractVariableRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * This file is also still used to unit test the abstract class. + * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_Variables_VariableRestrictionsSniff implements PHP_CodeSniffer_Sniff { - - /** - * Exclude groups. - * - * Example: 'foo,bar' - * - * @var string Comma-delimited group list. - */ - public $exclude = ''; - - /** - * Groups of variable data to check against. - * Don't use this in extended classes, override getGroups() instead. - * This is only used for Unit tests. - * - * @var array - */ - public static $groups = array(); - - /** - * Returns an array of tokens this test wants to listen for. - * - * @return array - */ - public function register() { - return array( - T_VARIABLE, - T_OBJECT_OPERATOR, - T_DOUBLE_COLON, - T_OPEN_SQUARE_BRACKET, - T_DOUBLE_QUOTED_STRING, - ); - - } // end register() +class WordPress_Sniffs_Variables_VariableRestrictionsSniff extends WordPress_AbstractVariableRestrictionsSniff { /** * Groups of variables to restrict. - * This should be overridden in extending classes. * * Example: groups => array( * 'wpdb' => array( @@ -67,113 +39,7 @@ public function register() { * @return array */ public function getGroups() { - return self::$groups; + return parent::$groups; } - /** - * Processes this test, when one of its tokens is encountered. - * - * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; - $exclude = explode( ',', $this->exclude ); - $groups = $this->getGroups(); - - if ( empty( $groups ) ) { - return ( count( $tokens ) + 1 ); - } - - // Check if it is a function not a variable. - if ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) { // This only works for object vars and array members. - $method = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); - $possible_parenthesis = $phpcsFile->findNext( T_WHITESPACE, ( $method + 1 ), null, true ); - if ( T_OPEN_PARENTHESIS === $tokens[ $possible_parenthesis ]['code'] ) { - return; // So .. it is a function after all ! - } - } - - foreach ( $groups as $groupName => $group ) { - - if ( in_array( $groupName, $exclude, true ) ) { - continue; - } - - $patterns = array(); - - // Simple variable. - if ( in_array( $token['code'], array( T_VARIABLE, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['variables'] ) ) { - $patterns = array_merge( $patterns, $group['variables'] ); - $var = $token['content']; - - } elseif ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['object_vars'] ) ) { - // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar - $patterns = array_merge( $patterns, $group['object_vars'] ); - - $owner = $phpcsFile->findPrevious( array( T_VARIABLE, T_STRING ), $stackPtr ); - $child = $phpcsFile->findNext( array( T_STRING, T_VAR, T_VARIABLE ), $stackPtr ); - $var = implode( '', array( $tokens[ $owner ]['content'], $token['content'], $tokens[ $child ]['content'] ) ); - - } elseif ( in_array( $token['code'], array( T_OPEN_SQUARE_BRACKET, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['array_members'] ) ) { - // Array members. - $patterns = array_merge( $patterns, $group['array_members'] ); - - $owner = $phpcsFile->findPrevious( array( T_VARIABLE ), $stackPtr ); - $inside = $phpcsFile->getTokensAsString( $stackPtr, ( $token['bracket_closer'] - $stackPtr + 1 ) ); - $var = implode( '', array( $tokens[ $owner ]['content'], $inside ) ); - } else { - continue; - } - - if ( empty( $patterns ) ) { - continue; - } - - $patterns = array_map( array( $this, 'test_patterns' ), $patterns ); - $pattern = implode( '|', $patterns ); - $delim = ( T_OPEN_SQUARE_BRACKET !== $token['code'] ) ? '\b' : ''; - - if ( T_DOUBLE_QUOTED_STRING === $token['code'] ) { - $var = $token['content']; - } - - if ( preg_match( '#(' . $pattern . ')' . $delim . '#', $var, $match ) !== 1 ) { - continue; - } - - if ( 'warning' === $group['type'] ) { - $addWhat = array( $phpcsFile, 'addWarning' ); - } else { - $addWhat = array( $phpcsFile, 'addError' ); - } - - call_user_func( - $addWhat, - $group['message'], - $stackPtr, - $groupName, - array( $var ) - ); - - return; // Show one error only. - - } - - } // end process() - - private function test_patterns( $pattern ) { - $pattern = preg_quote( $pattern, '#' ); - $pattern = preg_replace( - array( '#\\\\\*#', '[\'"]' ), - array( '.*', '\'' ), - $pattern - ); - return $pattern; - } // end test_patterns() - } // end class diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php index 32be51af7f..bdebed3728 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php @@ -20,7 +20,7 @@ class WordPress_Tests_Arrays_ArrayAssignmentRestrictionsUnitTest extends Abstrac protected function setUp() { parent::setUp(); - WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff::$groups = array( + WordPress_AbstractArrayAssignmentRestrictionsSniff::$groups = array( 'posts_per_page' => array( 'type' => 'error', 'message' => 'Found assignment value of %s to be %s', diff --git a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php index e180830f02..930a003bdb 100644 --- a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php +++ b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php @@ -20,7 +20,7 @@ class WordPress_Tests_Variables_VariableRestrictionsUnitTest extends AbstractSni protected function setUp() { parent::setUp(); - WordPress_Sniffs_Variables_VariableRestrictionsSniff::$groups = array( + WordPress_AbstractVariableRestrictionsSniff::$groups = array( 'test' => array( 'type' => 'error', 'message' => 'Detected usage of %s', From 602835927f175079dd8ea089a234fbeee73c1d39 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sat, 16 Jul 2016 01:43:44 +0200 Subject: [PATCH 072/122] Separate out the sniffing for `extract()`. Currently only VIP checked for the usage of `extract()`, even though it is an explicit rule for core. Ref: https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#dont-extract Solved #90 for real ;-) --- WordPress-Core/ruleset.xml | 1 + .../Sniffs/Functions/DontExtractSniff.php | 48 +++++++++++++++++ .../Sniffs/VIP/RestrictedFunctionsSniff.php | 8 --- .../Tests/Functions/DontExtractUnitTest.inc | 9 ++++ .../Tests/Functions/DontExtractUnitTest.php | 53 +++++++++++++++++++ .../Tests/VIP/RestrictedFunctionsUnitTest.inc | 2 +- .../Tests/VIP/RestrictedFunctionsUnitTest.php | 1 - 7 files changed, 112 insertions(+), 10 deletions(-) create mode 100644 WordPress/Sniffs/Functions/DontExtractSniff.php create mode 100644 WordPress/Tests/Functions/DontExtractUnitTest.inc create mode 100644 WordPress/Tests/Functions/DontExtractUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index cf7de8371b..965eff8698 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -111,5 +111,6 @@ + diff --git a/WordPress/Sniffs/Functions/DontExtractSniff.php b/WordPress/Sniffs/Functions/DontExtractSniff.php new file mode 100644 index 0000000000..86bdd044ad --- /dev/null +++ b/WordPress/Sniffs/Functions/DontExtractSniff.php @@ -0,0 +1,48 @@ + + */ +class WordPress_Sniffs_Functions_DontExtractSniff extends WordPress_AbstractFunctionRestrictionsSniff { + + /** + * Groups of functions to restrict. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', + * 'functions' => array( 'eval', 'create_function' ), + * ) + * ) + * + * @return array + */ + public function getGroups() { + return array( + + 'extract' => array( + 'type' => 'error', + 'message' => '%s() usage is highly discouraged, due to the complexity and unintended issues it might cause.', + 'functions' => array( + 'extract', + ), + ), + + ); + } // end getGroups() + +} // end class diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 0976874cb5..72111b816a 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -139,14 +139,6 @@ public function getGroups() { ), ), - 'extract' => array( - 'type' => 'warning', - 'message' => '%s() usage is highly discouraged, due to the complexity and unintended issues it might cause.', - 'functions' => array( - 'extract', - ), - ), - 'custom_role' => array( 'type' => 'error', 'message' => 'Use wpcom_vip_add_role() instead of add_role()', diff --git a/WordPress/Tests/Functions/DontExtractUnitTest.inc b/WordPress/Tests/Functions/DontExtractUnitTest.inc new file mode 100644 index 0000000000..f6a12ec66f --- /dev/null +++ b/WordPress/Tests/Functions/DontExtractUnitTest.inc @@ -0,0 +1,9 @@ + 1 ) ); // bad + +// Similarly named functions or methods however are fine. +my_extract(); // Ok. +My_Object::extract(); // Ok. +$this->extract(); // Ok. +$my_object->extract(); // Ok. diff --git a/WordPress/Tests/Functions/DontExtractUnitTest.php b/WordPress/Tests/Functions/DontExtractUnitTest.php new file mode 100644 index 0000000000..de482870a2 --- /dev/null +++ b/WordPress/Tests/Functions/DontExtractUnitTest.php @@ -0,0 +1,53 @@ + + * @author Greg Sherwood + * @author Marc McIntyre + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: @package_version@ + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class WordPress_Tests_Functions_DontExtractUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 3 => 1, + ); + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index b1c8bb1c27..f9726edd57 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -16,7 +16,7 @@ $ch = curl_init(); // bad curl_close( $ch ); // bad -extract( array( 'a' => 1 ) ); // bad +// Empty line - function moved to another sniff. add_role( 'test' ); // bad diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index 7802d8fe2e..92ca6e2a80 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -91,7 +91,6 @@ public function getWarningList() { 13 => 1, 15 => 1, 17 => 1, - 19 => 1, 58 => 1, 59 => 1, 61 => 1, From b379a6c8150c9662a41c1cc078dfc521971f402b Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 01:08:17 +0200 Subject: [PATCH 073/122] Enable the unit test. --- WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php index 80640d2e62..4ef3e1e383 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php @@ -66,6 +66,7 @@ public function getWarningList() { 51 => 1, 53 => 1, 55 => 1, + 57 => 1, 63 => 1, 65 => 1, 70 => 1, From 468d1acf54705436fe8d8c89400c713fd9a539fd Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 02:28:05 +0200 Subject: [PATCH 074/122] Add a work-around for the bug until the upstream PR for this has been merged. --- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index 9afd07deda..806247a124 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -75,4 +75,24 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ */ public $error = false; + /** + * Returns an array of tokens this test wants to listen for. + * + * {@internal Temporarily overrule the parent register() method until bugfix has + * been merged into PHPCS upstream and WPCS minimum PHPCS version has caught up. + * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1076} }} + * + * @return array + */ + public function register() { + $register = parent::register(); + + if ( true !== $this->patternMatch ) { + $this->forbiddenFunctionNames = array_map( 'strtolower', $this->forbiddenFunctionNames ); + $this->forbiddenFunctions = array_combine( $this->forbiddenFunctionNames, $this->forbiddenFunctions ); + } + + return $register; + } + } // end class From 4a527b98713a1cb3c4ae01e710c3e9bfb639630d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 00:25:48 +0200 Subject: [PATCH 075/122] Add unit test for case insensitive function names. --- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc | 3 +++ WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php | 2 ++ 2 files changed, 5 insertions(+) diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index b1c8bb1c27..e22b8ed6f7 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -83,3 +83,6 @@ putenv(); // error set_include_path(); // error restore_include_path(); // error phpinfo(); // error + +PHPINFO(); // error +CURL_getinfo(); // error diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index 7802d8fe2e..5c6d093627 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -71,6 +71,7 @@ public function getErrorList() { 83 => 1, 84 => 1, 85 => 1, + 87 => 1, ); } // end getErrorList() @@ -96,6 +97,7 @@ public function getWarningList() { 59 => 1, 61 => 1, 72 => 1, + 88 => 1, ); } // end getWarningList() From 7fc9df6396cb7a03672ea3c1e6a10f7dbc6ed1bf Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 05:22:07 +0200 Subject: [PATCH 076/122] Add unit test for incorrect wildcard replacement. --- WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index e22b8ed6f7..b3e903cf1c 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -86,3 +86,5 @@ phpinfo(); // error PHPINFO(); // error CURL_getinfo(); // error + +curlyhair(); // ok From 993e9d136ea8ada69a59d4e711086c1a35faa8ce Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 00:26:14 +0200 Subject: [PATCH 077/122] Fix bug in function name comparison. 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. --- .../AbstractFunctionRestrictionsSniff.php | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/WordPress/AbstractFunctionRestrictionsSniff.php b/WordPress/AbstractFunctionRestrictionsSniff.php index 30883926bd..9f731b2ddf 100644 --- a/WordPress/AbstractFunctionRestrictionsSniff.php +++ b/WordPress/AbstractFunctionRestrictionsSniff.php @@ -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; } @@ -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 From 460c8a9f51a97970954ad25277897cb3c857717e Mon Sep 17 00:00:00 2001 From: Gary Jones Date: Sun, 17 Jul 2016 12:06:23 +0100 Subject: [PATCH 078/122] Update WPCS testing procedure --- CONTRIBUTING.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e049262d3b..45720a1d04 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,23 +14,25 @@ Once a commit is made to `develop`, a PR should be opened from `develop` into `m TL;DR -Make sure you have `phpunit` installed and available in your `PATH`. If you have installed `phpcs` and the WordPress-Coding-Standards as [noted in the README](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards#how-to-use-this), then you can navigate to the directory where the `phpcs` repo is checked out and do: +If you have installed `phpcs` and the WordPress-Coding-Standards as [noted in the README](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards#how-to-use-this), then you can navigate to the directory where the `phpcs` repo is checked out and do: -```bash -git checkout phpcs-fixer # needed temporarily until PHPCS 2.0 -phpunit --filter WordPress tests/AllTests.php +```sh +composer install +vendor/bin/phpunit --filter WordPress tests/AllTests.php ``` Expected output: -~~~text -PHPUnit 3.7.18 by Sebastian Bergmann. +~~~sh +PHPUnit 4.8.26 by Sebastian Bergmann and contributors. -............... +.................................... -Time: 1 second, Memory: 37.00Mb +Tests generated 90 unique error codes; 28 were fixable (31.11%) -OK (15 tests, 0 assertions) +Time: 3.08 second, Memory: 24.00MB + +OK (36 tests, 0 assertions) ~~~ You can ignore any skipped tests as these are for `PHP_CodeSniffer` external tools. @@ -70,7 +72,7 @@ Also note the class name convention. The method `getErrorList` MUST return an ar indicating errors (when running `phpcs`) found in `WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc`. If you run: -~~~text +~~~sh $ cd /path-to-cloned/phpcs $ ./scripts/phpcs --standard=Wordpress -s CodeSniffer/Standards/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc ... From 66136c730bfbd81e8bdb3a82279c02a2e153eede Mon Sep 17 00:00:00 2001 From: Gary Jones Date: Sun, 17 Jul 2016 12:34:22 +0100 Subject: [PATCH 079/122] Fix codestyle See #256 --- WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php index 0a218f8f96..5d623a971c 100755 --- a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php @@ -25,7 +25,7 @@ * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -class WordPress_Sniffs_WhiteSpace_CastStructureSpacingSniff implements PHP_CodeSniffer_Sniff{ +class WordPress_Sniffs_WhiteSpace_CastStructureSpacingSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. From 8594451ff0fecb6785a42bc02633fe4927ad1f9d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 11:52:43 +0200 Subject: [PATCH 080/122] Add new sniff to check whether a hook name is valid. Covers the `action` part of this rule in the handbook: > Use lowercase letters in variable, **action**, and function names (never camelCase). Separate words via underscores. Ref: https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions Review appreciated. Also: I've made non-lowercase names an `error` and non-underscore punctuation a `warning`. Should that also be an `error` ? --- WordPress-Core/ruleset.xml | 1 + .../NamingConventions/ValidHookNameSniff.php | 247 ++++++++++++++++++ .../ValidHookNameUnitTest.inc | 82 ++++++ .../ValidHookNameUnitTest.php | 94 +++++++ 4 files changed, 424 insertions(+) create mode 100644 WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php create mode 100644 WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc create mode 100644 WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 965eff8698..33fd4dee2a 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -112,5 +112,6 @@ + diff --git a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php new file mode 100644 index 0000000000..753286f58b --- /dev/null +++ b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php @@ -0,0 +1,247 @@ + + */ +class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeSniffer_Sniff { + + /** + * Functions we're interested in. + * + * Only testing the hook call functions as when using 'add_action'/'add_filter' you can't influence + * the hook name. + * + * @var array + */ + public $hook_functions = array( + 'do_action', + 'do_action_ref_array', + 'apply_filters', + 'apply_filters_ref_array', + ); + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_STRING, + ); + + } // end register() + + /** + * Groups of functions to restrict. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', + * 'functions' => array( 'eval', 'create_function' ), + * ) + * ) + * + * @return array + */ + public function getGroups() { + return array(); + } + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + + // Check if one of the hook functions was found. + if ( false === in_array( $tokens[ $stackPtr ]['content'], $this->hook_functions, true ) ) { + return; + } + + $prev = $phpcsFile->findPrevious( T_WHITESPACE, ( $stackPtr - 1 ), null, true ); + + if ( false !== $prev ) { + // Skip sniffing if calling a same-named method, or on function definitions. + if ( in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) ) { + return; + } + + // Skip namespaced functions, ie: \foo\bar() not \bar(). + $pprev = $phpcsFile->findPrevious( T_WHITESPACE, ( $prev - 1 ), null, true ); + if ( false !== $pprev && T_NS_SEPARATOR === $tokens[ $prev ]['code'] && T_STRING === $tokens[ $pprev ]['code'] ) { + return; + } + } + unset( $prev, $pprev ); + + /* + Ok, so we have a proper hook call, let's find the position of the tokens + which together comprise the hook name. + */ + $start = $phpcsFile->findNext( array( T_WHITESPACE, T_OPEN_PARENTHESIS ), ( $stackPtr + 1 ), null, true, null, true ); + $open = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $stackPtr + 1 ), null, false, null, true ); + $end = $phpcsFile->findNext( T_COMMA, ( $start + 1 ), null, false, null, true ); + if ( false === $end || $end > $tokens[ $open ]['parenthesis_closer'] ) { + $end = $tokens[ $open ]['parenthesis_closer']; + } + if ( T_WHITESPACE === $tokens[ ( $end - 1 ) ]['code'] ) { + $end--; + } + + $case_errors = 0; + $underscores = 0; + $content = array(); + $expected = array(); + + for ( $i = $start; $i < $end; $i++ ) { + $content[ $i ] = $tokens[ $i ]['content']; + $expected[ $i ] = $tokens[ $i ]['content']; + + if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_DOUBLE_QUOTED_STRING ), true ) ) { + /* + Here be dragons - a double quoted string can contain extrapolated variables + which don't have to comply with these rules. + */ + if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { + $string = trim( $tokens[ $i ]['content'], '"' ); + $transform = $this->transform_complex_string( $string ); + $case_transform = $this->transform_complex_string( $string, 'case' ); + $punct_transform = $this->transform_complex_string( $string, 'punctuation' ); + } else { + $string = trim( $tokens[ $i ]['content'], '\'"' ); + $transform = $this->transform( $string ); + $case_transform = $this->transform( $string, 'case' ); + $punct_transform = $this->transform( $string, 'punctuation' ); + } + + if ( $string === $transform ) { + continue; + } + + if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { + $expected[ $i ] = '"' . $transform . '"'; + } else { + $expected[ $i ] = '\'' . $transform . '\''; + } + + if ( $string !== $case_transform ) { + $case_errors++; + } + if ( $string !== $punct_transform ) { + $underscores++; + } + } + } + + $data = array( + implode( '', $expected ), + implode( '', $content ), + ); + + if ( $case_errors > 0 ) { + $error = 'Hook names should be lowercase. Expected: %s, but found: %s.'; + $phpcsFile->addError( $error, $stackPtr, 'NotLowercase', $data ); + } + if ( $underscores > 0 ) { + $error = 'Words in hook names should be separated using underscores. Expected: %s, but found: %s.'; + $phpcsFile->addWarning( $error, $stackPtr, 'UseUnderscores', $data ); + } + + } // end process() + + /** + * Transform an arbitrary string to lowercase and replace punctuation and spaces with underscores. + * + * @param string $string The target string. + * @param string $transform_type Whether to a partial or complete transform. + * Valid values are: 'full', 'case', 'punctuation'. + * @return string + */ + protected function transform( $string, $transform_type = 'full' ) { + switch ( $transform_type ) { + case 'case': + return strtolower( $string ); + + case 'punctuation': + return preg_replace( '`\W`', '_', $string ); + + case 'full': + default: + return preg_replace( '`\W`', '_', strtolower( $string ) ); + } + } // end transform() + + /** + * Transform a complex string which may contain variable extrapolation. + * + * @param string $string The target string. + * @param string $transform_type Whether to a partial or complete transform. + * Valid values are: 'full', 'case', 'punctuation'. + * @return string + */ + protected function transform_complex_string( $string, $transform_type = 'full' ) { + $output = preg_split( '`([\{\}\$\[\] ])`', $string, -1, PREG_SPLIT_DELIM_CAPTURE ); + + $is_variable = false; + $has_braces = false; + $braces = 0; + + foreach ( $output as $i => $part ) { + if ( in_array( $part, array( '$', '{' ), true ) ) { + $is_variable = true; + if ( '{' === $part ) { + $has_braces = true; + $braces++; + } + continue; + } + + if ( true === $is_variable ) { + if ( '[' === $part ) { + $has_braces = true; + $braces++; + } + if ( in_array( $part, array( '}', ']' ), true ) ) { + $braces--; + } + if ( false === $has_braces && ' ' === $part ) { + $is_variable = false; + $output[ $i ] = $this->transform( $part, $transform_type ); + } + + if ( ( true === $has_braces && 0 === $braces ) && false === in_array( $output[ ( $i + 1 ) ], array( '{', '[' ), true ) ) { + $has_braces = false; + $is_variable = false; + } + continue; + } + + $output[ $i ] = $this->transform( $part, $transform_type ); + } + + return implode( '', $output ); + } // end transform_complex_string() + +} // end class diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc new file mode 100644 index 0000000000..e105a9f5b8 --- /dev/null +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc @@ -0,0 +1,82 @@ +do_action( 'someAction' ); // Ok - not WP do_action. +SomeClass::do_action( 'someAction' ); // Ok - not WP do_action. +\SomeClass\do_action( 'someAction' ); // Ok - not WP do_action. + +// Check for incorrect word separators. +do_action( "admin_head-$hook_suffix" ); // Warning - use underscore. +do_action( 'admin_head.media.upload_popup' ); // Warning - use underscore. +apply_filters( "bulk_actions {$this->screen->id}", $this->_actions ); // Warning - use underscore. +apply_filters( "current_theme/supports-{$feature}", true, $args, $_wp_theme_features[$feature] ); // Warning - use underscore. + +// Simple strings. +do_action( "adminHead" ); // Error - use lowercase. +do_action_ref_array( 'ADMINHEAD', array( $variable ) ); // Error - use lowercase. +apply_filters( 'adminHead', $variable ); // Error - use lowercase. +apply_filters_ref_array( 'ADMINHEAD', array( $variable ) ); // Error - use lowercase. + +// Variable hooks. +do_action( $Hook_name ); // Ok. +do_action( "{$Hook_Name}" ); // Ok. + +// Compound hook names. +do_action( 'admin_head_' . $Type . '_action' ); // ok. +do_action( 'admin_head_' . get_ID() . '_action' ); // Ok. +do_action( 'admin_head_' . $post->ID . '_action' ); // Ok. + +do_action( 'admin_Head_' . $Type . '_Action' ); // Error - use lowercase. +do_action( 'admin_Head_' . get_ID() . '_Action' ); // Error - use lowercase. +do_action( 'admin_Head_' . $post->ID . '_Action' ); // Error - use lowercase. + +do_action( + 'admin_Head_' . $type, + $variable +); // Error - use lowercase. + +// More complex strings. +do_action( "admin_head_$Post" ); // Ok. +do_action( "admin_head_$Post[1]_action" ); // Ok. +do_action( "admin_head_$Post[Test]_action" ); // Ok. +do_action( "admin_head_${Post}_action" ); // Ok. +do_action( "admin_head_$Post->ID" ); // Ok. +do_action( "admin_head_{$Post}" ); // Ok. +do_action( "admin_head_{$Post['Key']}_action" ); // Ok. +do_action( "admin_head_{$Post[1][2]}_action" ); // Ok. +do_action( "admin_head_{$post->ID}_action" ); // Ok. +do_action( "admin_head_{$obj->Values[3]->name}_action" ); // Ok. +do_action( "admin_head_{${$Name}}_action" ); // Ok. +do_action( "admin_head_{$foo->{$baz[1]}}_action" ); // Ok. +do_action( "admin_head_{${getName()}}_action" ); // Ok. +do_action( "admin_head_{${$object->getName()}}_action" ); // Ok. + +do_action( "admin_Head_$Post" ); // Error - use lowercase. +do_action( "admin_Head_$Post[1]_Action" ); // Error - use lowercase. +do_action( "admin_Head_$Post[Test]_Action" ); // Error - use lowercase. +do_action( "admin_Head_${Post}_Action" ); // Error - use lowercase. +do_action( "admin_Head_$Post->ID" ); // Error - use lowercase. +do_action( "admin_Head_{$Post}" ); // Error - use lowercase. +do_action( "admin_Head_{$Post['Key']}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$Post[1][2]}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$post->ID}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$obj->Values[3]->name}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{${$Name}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$foo->{$baz[1]}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{${getName()}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{${$object->getName()}}_Action" ); // Error - use lowercase. + +do_action( "admin_Head_$Post admin_Head_$Post" ); // Error - use lowercase + warning about space. +do_action( "admin_Head_$Post[1]_Action_$Post[1]_Action" ); // Error - use lowercase. +do_action( "admin_Head_$Post[Test]_Action_$Post[Test]_Action" ); // Error - use lowercase. +do_action( "admin_Head_${Post}_Action_${Post}_Action" ); // Error - use lowercase. +do_action( "admin_Head_$Post->ID admin_Head_$Post->ID" ); // Error - use lowercase + warning about space. +do_action( "admin_Head_{$Post}_admin_Head_{$Post}" ); // Error - use lowercase. +do_action( "admin_Head_{$Post['Key']}_Action_{$Post['Key']}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$Post[1][2]}_Action_{$Post[1][2]}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$post->ID}_Action_{$post->ID}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$obj->Values[3]->name}-Action_{$obj->Values[3]->name}_Action" ); // Error - use lowercase + warning about dash. +do_action( "admin_Head_{${$Name}}_Action_{${$Name}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{$foo->{$baz[1]}}_Action_{$foo->{$baz[1]}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{${getName()}}_Action_{${getName()}}_Action" ); // Error - use lowercase. +do_action( "admin_Head_{${$object->getName()}}_Action_{${$object->getName()}}_Action" ); // Error - use lowercase. + diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php new file mode 100644 index 0000000000..769f923412 --- /dev/null +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php @@ -0,0 +1,94 @@ + + */ +class WordPress_Tests_NamingConventions_ValidHookNameUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() { + + return array( + 14 => 1, + 15 => 1, + 16 => 1, + 17 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 32 => 1, + 53 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 60 => 1, + 61 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + 73 => 1, + 74 => 1, + 75 => 1, + 76 => 1, + 77 => 1, + 78 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + ); + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() { + return array( + 8 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 68 => 1, + 72 => 1, + 77 => 1, + ); + + } // end getWarningList() + +} // end class From f163241938928f956e3d34f14d17914e797624e4 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 12:35:52 +0200 Subject: [PATCH 081/122] Remove the unit test for namespaced functions. That particular test caused the unit tests to fail on PHP 5.2 and it was only included to ensure that the sniff would *not* run on namespaced functions. --- WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc index e105a9f5b8..0e0f62bbf2 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc @@ -2,7 +2,7 @@ $this->do_action( 'someAction' ); // Ok - not WP do_action. SomeClass::do_action( 'someAction' ); // Ok - not WP do_action. -\SomeClass\do_action( 'someAction' ); // Ok - not WP do_action. +prefix_do_action( 'someAction' ); // Ok - not WP do_action. // Check for incorrect word separators. do_action( "admin_head-$hook_suffix" ); // Warning - use underscore. From a17879d5f7f61eec76841a4a22bf8ebc1fe6e70f Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 15 Jul 2016 22:45:11 +0200 Subject: [PATCH 082/122] Allow for additional word delimiters. Creates the ability to provide additional allowed word delimiters via `phpcs.xml` or via the inline `@codingStandardsChangeSetting` directive. Syntax: ```xml ``` Includes unit tests. --- .../NamingConventions/ValidHookNameSniff.php | 104 ++++++++++---- .../ValidHookNameUnitTest.1.inc | 17 +++ .../ValidHookNameUnitTest.2.inc | 17 +++ .../ValidHookNameUnitTest.inc | 1 - .../ValidHookNameUnitTest.php | 132 +++++++++++------- 5 files changed, 190 insertions(+), 81 deletions(-) create mode 100644 WordPress/Tests/NamingConventions/ValidHookNameUnitTest.1.inc create mode 100644 WordPress/Tests/NamingConventions/ValidHookNameUnitTest.2.inc diff --git a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php index 753286f58b..4e62f9f518 100644 --- a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php @@ -18,6 +18,40 @@ */ class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeSniffer_Sniff { + /** + * Additional word separators. + * + * This public variable allows providing additional word separators which + * will be allowed in hook names via a property in the phpcs.xml config file. + * + * Example usage: + * + * + * + * + * + * + * Provide several extra delimiters as one string: + * + * + * + * + * + * + * @var string + */ + public $additionalWordDelimiters = ''; + + /** + * Regular expression to test for correct punctuation of a hook name. + * + * The placeholder will be replaced by potentially provided additional + * word delimiters in the `prepare_regex()` method. + * + * @var string + */ + protected $punctuation_regex = '`[^\w%s]`'; + /** * Functions we're interested in. * @@ -26,7 +60,7 @@ class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeS * * @var array */ - public $hook_functions = array( + protected $hook_functions = array( 'do_action', 'do_action_ref_array', 'apply_filters', @@ -34,7 +68,9 @@ class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeS ); /** - * Returns an array of tokens this test wants to listen for. + * Register this sniff. + * + * Prepares the punctuation regex and returns an array of tokens this test wants to listen for. * * @return array */ @@ -45,23 +81,6 @@ public function register() { } // end register() - /** - * Groups of functions to restrict. - * - * Example: groups => array( - * 'lambda' => array( - * 'type' => 'error' | 'warning', - * 'message' => 'Use anonymous functions instead please!', - * 'functions' => array( 'eval', 'create_function' ), - * ) - * ) - * - * @return array - */ - public function getGroups() { - return array(); - } - /** * Processes this test, when one of its tokens is encountered. * @@ -74,6 +93,7 @@ public function getGroups() { public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $token = $tokens[ $stackPtr ]; + $regex = $this->prepare_regex(); // Check if one of the hook functions was found. if ( false === in_array( $tokens[ $stackPtr ]['content'], $this->hook_functions, true ) ) { @@ -126,14 +146,14 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { */ if ( T_DOUBLE_QUOTED_STRING === $tokens[ $i ]['code'] ) { $string = trim( $tokens[ $i ]['content'], '"' ); - $transform = $this->transform_complex_string( $string ); - $case_transform = $this->transform_complex_string( $string, 'case' ); - $punct_transform = $this->transform_complex_string( $string, 'punctuation' ); + $transform = $this->transform_complex_string( $string, $regex ); + $case_transform = $this->transform_complex_string( $string, $regex, 'case' ); + $punct_transform = $this->transform_complex_string( $string, $regex, 'punctuation' ); } else { $string = trim( $tokens[ $i ]['content'], '\'"' ); - $transform = $this->transform( $string ); - $case_transform = $this->transform( $string, 'case' ); - $punct_transform = $this->transform( $string, 'punctuation' ); + $transform = $this->transform( $string, $regex ); + $case_transform = $this->transform( $string, $regex, 'case' ); + $punct_transform = $this->transform( $string, $regex, 'punctuation' ); } if ( $string === $transform ) { @@ -171,25 +191,46 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() + /** + * Prepare the punctuation regular expression. + * + * Merges the existing regular expression with potentially provided extra word delimiters to allow. + * This is done 'late' and for each found token as otherwise inline `@codingStandardsChangeSetting` + * directives would be ignored. + * + * @return string + */ + protected function prepare_regex() { + $extra = ''; + if ( '' !== $this->additionalWordDelimiters && is_string( $this->additionalWordDelimiters ) ) { + $extra = preg_quote( $this->additionalWordDelimiters, '`' ); + } + + return sprintf( $this->punctuation_regex, $extra ); + + } // end prepare_regex() + /** * Transform an arbitrary string to lowercase and replace punctuation and spaces with underscores. * * @param string $string The target string. + * @param string $regex The punctuation regular expression to use. * @param string $transform_type Whether to a partial or complete transform. * Valid values are: 'full', 'case', 'punctuation'. * @return string */ - protected function transform( $string, $transform_type = 'full' ) { + protected function transform( $string, $regex, $transform_type = 'full' ) { + switch ( $transform_type ) { case 'case': return strtolower( $string ); case 'punctuation': - return preg_replace( '`\W`', '_', $string ); + return preg_replace( $regex, '_', $string ); case 'full': default: - return preg_replace( '`\W`', '_', strtolower( $string ) ); + return preg_replace( $regex, '_', strtolower( $string ) ); } } // end transform() @@ -197,11 +238,12 @@ protected function transform( $string, $transform_type = 'full' ) { * Transform a complex string which may contain variable extrapolation. * * @param string $string The target string. + * @param string $regex The punctuation regular expression to use. * @param string $transform_type Whether to a partial or complete transform. * Valid values are: 'full', 'case', 'punctuation'. * @return string */ - protected function transform_complex_string( $string, $transform_type = 'full' ) { + protected function transform_complex_string( $string, $regex, $transform_type = 'full' ) { $output = preg_split( '`([\{\}\$\[\] ])`', $string, -1, PREG_SPLIT_DELIM_CAPTURE ); $is_variable = false; @@ -228,7 +270,7 @@ protected function transform_complex_string( $string, $transform_type = 'full' ) } if ( false === $has_braces && ' ' === $part ) { $is_variable = false; - $output[ $i ] = $this->transform( $part, $transform_type ); + $output[ $i ] = $this->transform( $part, $regex, $transform_type ); } if ( ( true === $has_braces && 0 === $braces ) && false === in_array( $output[ ( $i + 1 ) ], array( '{', '[' ), true ) ) { @@ -238,7 +280,7 @@ protected function transform_complex_string( $string, $transform_type = 'full' ) continue; } - $output[ $i ] = $this->transform( $part, $transform_type ); + $output[ $i ] = $this->transform( $part, $regex, $transform_type ); } return implode( '', $output ); diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.1.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.1.inc new file mode 100644 index 0000000000..084a176612 --- /dev/null +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.1.inc @@ -0,0 +1,17 @@ +screen->id}", $this->_actions ); +apply_filters( "current_theme-supports-{$feature}", true, $args, $_wp_theme_features[$feature] ); + +// These should still give warnings. +do_action( "admin_head*$hook_suffix" ); // Warning - use underscore. +do_action( 'admin_head.media.upload_popup' ); // Warning - use underscore. +apply_filters( "bulk_actions {$this->screen->id}", $this->_actions ); // Warning - use underscore. +apply_filters( "current_theme/supports-{$feature}", true, $args, $_wp_theme_features[$feature] ); // Warning - use underscore. + +// @codingStandardsChangeSetting WordPress.NamingConventions.ValidHookName additionalWordDelimiters _ diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.2.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.2.inc new file mode 100644 index 0000000000..e58cc75781 --- /dev/null +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.2.inc @@ -0,0 +1,17 @@ +screen->id}", $this->_actions ); +apply_filters( "current_theme/supports-{$feature}", true, $args, $_wp_theme_features[$feature] ); + +// These should still give warnings. +do_action( "admin_head*$hook_suffix" ); // Warning - use underscore. +do_action( 'admin_head&media+upload_popup' ); // Warning - use underscore. +apply_filters( "bulk_actions {$this->screen->id}", $this->_actions ); // Warning - use underscore. +apply_filters( "current_theme#supports-{$feature}", true, $args, $_wp_theme_features[$feature] ); // Warning - use underscore. + +// @codingStandardsChangeSetting WordPress.NamingConventions.ValidHookName additionalWordDelimiters _ diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc index 0e0f62bbf2..15138abbce 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc @@ -79,4 +79,3 @@ do_action( "admin_Head_{${$Name}}_Action_{${$Name}}_Action" ); // Error - use lo do_action( "admin_Head_{$foo->{$baz[1]}}_Action_{$foo->{$baz[1]}}_Action" ); // Error - use lowercase. do_action( "admin_Head_{${getName()}}_Action_{${getName()}}_Action" ); // Error - use lowercase. do_action( "admin_Head_{${$object->getName()}}_Action_{${$object->getName()}}_Action" ); // Error - use lowercase. - diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php index 769f923412..972596e043 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php @@ -25,48 +25,61 @@ class WordPress_Tests_NamingConventions_ValidHookNameUnitTest extends AbstractSn * The key of the array should represent the line number and the value * should represent the number of errors that should occur on that line. * + * @param string $testFile The name of the file being tested. + * * @return array */ - public function getErrorList() { + public function getErrorList( $testFile = 'ValidHookNameUnitTest.inc' ) { + + switch ( $testFile ) { + case 'ValidHookNameUnitTest.inc': + return array( + 14 => 1, + 15 => 1, + 16 => 1, + 17 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 32 => 1, + 53 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 60 => 1, + 61 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + 73 => 1, + 74 => 1, + 75 => 1, + 76 => 1, + 77 => 1, + 78 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + ); + break; - return array( - 14 => 1, - 15 => 1, - 16 => 1, - 17 => 1, - 28 => 1, - 29 => 1, - 30 => 1, - 32 => 1, - 53 => 1, - 54 => 1, - 55 => 1, - 56 => 1, - 57 => 1, - 58 => 1, - 59 => 1, - 60 => 1, - 61 => 1, - 62 => 1, - 63 => 1, - 64 => 1, - 65 => 1, - 66 => 1, - 68 => 1, - 69 => 1, - 70 => 1, - 71 => 1, - 72 => 1, - 73 => 1, - 74 => 1, - 75 => 1, - 76 => 1, - 77 => 1, - 78 => 1, - 79 => 1, - 80 => 1, - 81 => 1, - ); + case 'ValidHookNameUnitTest.1.inc': + case 'ValidHookNameUnitTest.2.inc': + default: + return array(); + break; + + } // end switch } // end getErrorList() @@ -76,18 +89,39 @@ public function getErrorList() { * The key of the array should represent the line number and the value * should represent the number of warnings that should occur on that line. * + * @param string $testFile The name of the file being tested. + * * @return array */ - public function getWarningList() { - return array( - 8 => 1, - 9 => 1, - 10 => 1, - 11 => 1, - 68 => 1, - 72 => 1, - 77 => 1, - ); + public function getWarningList( $testFile = 'ValidHookNameUnitTest.inc' ) { + + switch ( $testFile ) { + case 'ValidHookNameUnitTest.inc': + return array( + 8 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 68 => 1, + 72 => 1, + 77 => 1, + ); + break; + + case 'ValidHookNameUnitTest.1.inc': + case 'ValidHookNameUnitTest.2.inc': + return array( + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + ); + break; + + default: + return array(); + break; + } // end switch } // end getWarningList() From 6569cc64adc8beafe21a7a8133b837029f67b769 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 18:18:23 +0200 Subject: [PATCH 083/122] Remove superfluous `break`s. --- WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php index 972596e043..4afc403505 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php @@ -71,13 +71,11 @@ public function getErrorList( $testFile = 'ValidHookNameUnitTest.inc' ) { 80 => 1, 81 => 1, ); - break; case 'ValidHookNameUnitTest.1.inc': case 'ValidHookNameUnitTest.2.inc': default: return array(); - break; } // end switch @@ -106,7 +104,6 @@ public function getWarningList( $testFile = 'ValidHookNameUnitTest.inc' ) { 72 => 1, 77 => 1, ); - break; case 'ValidHookNameUnitTest.1.inc': case 'ValidHookNameUnitTest.2.inc': @@ -116,11 +113,10 @@ public function getWarningList( $testFile = 'ValidHookNameUnitTest.inc' ) { 14 => 1, 15 => 1, ); - break; default: return array(); - break; + } // end switch } // end getWarningList() From 8ad78ce9173712138da22409056ee4d953798016 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 20:24:18 +0200 Subject: [PATCH 084/122] Move function name list to `WordPress_Sniff` class. Also: * Add function name list for the other hook functions to the `WordPress_Sniff` class as well. * Ignore deprecated hook names for the purposes of the valid hook name sniff + add unit test verifying that. --- WordPress/Sniff.php | 38 +++++++++++++++++++ .../NamingConventions/ValidHookNameSniff.php | 27 ++++++------- .../ValidHookNameUnitTest.inc | 4 ++ 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index a61440cbb6..d012dacb52 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -400,6 +400,44 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { 'wp_cache_delete' => true, ); + /** + * A list of functions that invoke WP hooks (filters/actions). + * + * @since 0.10.0 + * + * @var array + */ + public static $hookInvokeFunctions = array( + 'do_action' => true, + 'do_action_ref_array' => true, + 'do_action_deprecated' => true, + 'apply_filters' => true, + 'apply_filters_ref_array' => true, + 'apply_filters_deprecated' => true, + ); + + /** + * A list of functions that are used to interact with the WP plugins API. + * + * @since 0.10.0 + * + * @var array => + */ + public static $hookFunctions = array( + 'has_filter' => 1, + 'add_filter' => 1, + 'remove_filter' => 1, + 'remove_all_filters' => 1, + 'doing_filter' => 1, // Hook name optional. + 'has_action' => 1, + 'add_action' => 1, + 'doing_action' => 1, // Hook name optional. + 'did_action' => 1, + 'remove_action' => 1, + 'remove_all_actions' => 1, + 'current_filter' => 0, // No hook name argument. + ); + /** * The current file being sniffed. * diff --git a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php index 4e62f9f518..c322c3dabe 100644 --- a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php @@ -10,6 +10,11 @@ /** * Use lowercase letters in action and filter names. Separate words via underscores. * + * This sniff is only testing the hook invoke functions as when using 'add_action'/'add_filter' + * you can't influence the hook name. + * + * Hook names invoked with `do_action_deprecated()` and `apply_filters_deprecated()` are ignored. + * * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions * * @category PHP @@ -52,21 +57,6 @@ class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeS */ protected $punctuation_regex = '`[^\w%s]`'; - /** - * Functions we're interested in. - * - * Only testing the hook call functions as when using 'add_action'/'add_filter' you can't influence - * the hook name. - * - * @var array - */ - protected $hook_functions = array( - 'do_action', - 'do_action_ref_array', - 'apply_filters', - 'apply_filters_ref_array', - ); - /** * Register this sniff. * @@ -96,7 +86,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $regex = $this->prepare_regex(); // Check if one of the hook functions was found. - if ( false === in_array( $tokens[ $stackPtr ]['content'], $this->hook_functions, true ) ) { + if ( ! isset( WordPress_Sniff::$hookInvokeFunctions[ $tokens[ $stackPtr ]['content'] ] ) ) { + return; + } + + // Ignore deprecated hook names. + if ( strpos( $tokens[ $stackPtr ]['content'], '_deprecated' ) > 0 ) { return; } diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc index 15138abbce..bda73caaf5 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.inc @@ -79,3 +79,7 @@ do_action( "admin_Head_{${$Name}}_Action_{${$Name}}_Action" ); // Error - use lo do_action( "admin_Head_{$foo->{$baz[1]}}_Action_{$foo->{$baz[1]}}_Action" ); // Error - use lowercase. do_action( "admin_Head_{${getName()}}_Action_{${getName()}}_Action" ); // Error - use lowercase. do_action( "admin_Head_{${$object->getName()}}_Action_{${$object->getName()}}_Action" ); // Error - use lowercase. + +// Make sure that deprecated hook names are ignored for this sniff. +do_action_deprecated( "admin_Head_$Post admin_Head_$Post" ); // Ok. +apply_filters_deprecated( "admin_Head_$Post->ID admin_Head_$Post->ID" ); // Ok. From 48c559ad9603f42806b4f04bb3ba35770589363e Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 07:11:11 +0200 Subject: [PATCH 085/122] Disallow direct database calls. --- WordPress-Core/ruleset.xml | 2 + .../Sniffs/DB/RestrictedFunctionsSniff.php | 59 +++++++++++ .../Tests/DB/RestrictedFunctionsUnitTest.inc | 76 +++++++++++++ .../Tests/DB/RestrictedFunctionsUnitTest.php | 100 ++++++++++++++++++ 4 files changed, 237 insertions(+) create mode 100644 WordPress/Sniffs/DB/RestrictedFunctionsSniff.php create mode 100644 WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc create mode 100644 WordPress/Tests/DB/RestrictedFunctionsUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 965eff8698..811203a5f8 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -113,4 +113,6 @@ + + diff --git a/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php new file mode 100644 index 0000000000..72d2cb3f89 --- /dev/null +++ b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php @@ -0,0 +1,59 @@ + + */ +class WordPress_Sniffs_DB_RestrictedFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { + + /** + * Groups of functions to restrict. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', + * 'functions' => array( 'eval', 'create_function' ), + * ) + * ) + * + * @return array + */ + public function getGroups() { + return array( + + 'mysql' => array( + 'type' => 'error', + 'message' => 'Accessing the database directly should be avoided. Please use the $wpdb object and associated functions instead. Found: %s.', + 'functions' => array( + 'mysql_*', + 'mysqli_*', + 'mysqlnd_ms_*', + 'mysqlnd_qc_*', + 'mysqlnd_uh_*', + 'mysqlnd_memcache_*', + 'maxdb_*', + ), + ), + + ); + } + +} // end class diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc new file mode 100644 index 0000000000..dae0896f15 --- /dev/null +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc @@ -0,0 +1,76 @@ +mysql_info(); // ok +$y = Bar::mysql_info(); // ok +\SomeNamespace\mysql_info(); // ok + + +/** + * All the below should give an error. + */ + +// MYSQL Extension. +mysql_affected_rows(); +mysql_connect(); +mysql_close(); +mysql_fetch_row(); +mysql_info(); +mysql_numrows(); +mysql_pconnect(); +mysql_query(); +mysql_result(); + +// MYSQLI Extension. +mysqli_client_encoding(); +mysqli_connect(); +mysqli_escape_string(); +mysqli_execute(); +mysqli_fetch(); +mysqli_get_metadata(); +mysqli_init(); +mysqli_options(); +mysqli_real_connect(); + +// MYSQLND_MS Extension. +mysqlnd_ms_fabric_select_global(); +mysqlnd_ms_get_stats(); +mysqlnd_ms_match_wild(); +mysqlnd_ms_xa_begin(); +mysqlnd_ms_xa_rollback(); + +// MYSQLND_QC Extension. +mysqlnd_qc_clear_cache(); +mysqlnd_qc_get_cache_info(); +mysqlnd_qc_get_query_trace_log(); +mysqlnd_qc_set_cache_condition(); + +// MYSQLND_UH Extension. +mysqlnd_uh_convert_to_mysqlnd(); + +// MYSQLND_MEMCACHE Extension. +mysqlnd_memcache_set(); + +// MAXDB Extension. +maxdb_affected_rows(); +maxdb_close(); +maxdb_connect(); +maxdb_errno(); +maxdb_escape_string(); +maxdb_fetch_assoc +maxdb_init(); +maxdb_num_fields(); +maxdb_prepare(); +maxdb_real_query +maxdb_stat(); diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php new file mode 100644 index 0000000000..1e70d1a433 --- /dev/null +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php @@ -0,0 +1,100 @@ + + * @author Greg Sherwood + * @author Marc McIntyre + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: @package_version@ + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class WordPress_Tests_DB_RestrictedFunctionsUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 25 => 1, + 26 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 32 => 1, + 33 => 1, + + 36 => 1, + 37 => 1, + 38 => 1, + 39 => 1, + 40 => 1, + 41 => 1, + 42 => 1, + 43 => 1, + 44 => 1, + + 47 => 1, + 48 => 1, + 49 => 1, + 50 => 1, + 51 => 1, + + 54 => 1, + 55 => 1, + 56 => 1, + 57 => 1, + + 60 => 1, + + 63 => 1, + + 66 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + 73 => 1, + 74 => 1, + 75 => 1, + 76 => 1, + ); + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class From fd76f39995443232b71f8b0bfce631482af07644 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Jul 2016 21:09:06 +0200 Subject: [PATCH 086/122] Remove the unit test for namespaced functions. That particular test caused the unit tests to fail on PHP 5.2 and it was only included to ensure that the sniff would *not* run on namespaced functions. --- WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc index dae0896f15..5c8c29fc08 100644 --- a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc @@ -14,7 +14,7 @@ class Bar { $x = new Foo(); $x->mysql_info(); // ok $y = Bar::mysql_info(); // ok -\SomeNamespace\mysql_info(); // ok +prefix_mysql_info(); // ok /** From 22e427c551d0d37f99b371c1e1c8ff5c44d0cf2c Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 18 Jul 2016 15:43:31 +0200 Subject: [PATCH 087/122] Update the readme file. * Update the sniff output example (run against core, extra and docs, not vip) * Added section about PHPCompatibility sniffs * Added reference to the wiki --- README.md | 47 +++++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index eb0548aae9..a8c4dae3cc 100644 --- a/README.md +++ b/README.md @@ -67,22 +67,25 @@ Run the `phpcs` command line tool on a given file or directory, for example: Will result in following output: -------------------------------------------------------------------------------- - FOUND 13 ERROR(S) AFFECTING 7 LINE(S) + FOUND 8 ERRORS AND 2 WARNINGS AFFECTING 7 LINES -------------------------------------------------------------------------------- - 1 | ERROR | End of line character is invalid; expected "\n" but found "\r\n" - 22 | ERROR | No space after opening parenthesis of function prohibited - 22 | ERROR | No space before closing parenthesis of function prohibited - 26 | ERROR | No space before closing parenthesis of function prohibited - 31 | ERROR | No space after opening parenthesis of function prohibited - 31 | ERROR | No space before closing parenthesis of function prohibited - 31 | ERROR | No space after opening parenthesis of function prohibited - 31 | ERROR | No space before closing parenthesis of function prohibited - 34 | ERROR | No space after opening parenthesis of function prohibited - 34 | ERROR | No space before closing parenthesis of function prohibited - 55 | ERROR | Detected usage of a non-validated input variable: $_SERVER - 55 | ERROR | Detected usage of a non-sanitized input variable: $_SERVER - 70 | ERROR | String "Create a Configuration File" does not require double - | | quotes; use single quotes instead + 1 | ERROR | [x] End of line character is invalid; expected "\n" but found "\r\n" + 36 | ERROR | [x] Expected 1 spaces before closing bracket; 0 found + 41 | WARNING | [ ] Silencing errors is discouraged + 41 | WARNING | [ ] Silencing errors is discouraged + 48 | ERROR | [ ] Inline comments must end in full-stops, exclamation marks, or + | | question marks + 48 | ERROR | [x] There must be no blank line following an inline comment + 76 | ERROR | [ ] Inline comments must end in full-stops, exclamation marks, or + | | question marks + 92 | ERROR | [x] String "Create a Configuration File" does not require double + | | quotes; use single quotes instead + 94 | ERROR | [ ] Expected next thing to be an escaping function (see Codex for + | | 'Data Validation'), not '$die' + 94 | ERROR | [ ] Expected next thing to be an escaping function (see Codex for + | | 'Data Validation'), not '__' + -------------------------------------------------------------------------------- + PHPCBF CAN FIX THE 4 MARKED SNIFF VIOLATIONS AUTOMATICALLY -------------------------------------------------------------------------------- ### PhpStorm @@ -135,10 +138,22 @@ You can use the following as standard names when invoking `phpcs` to select snif - includes `WordPress-Core` -### Using custom ruleset +### Using a custom ruleset If you need to further customize selection of sniffs for your project — you can create custom `ruleset.xml` standard. See provided [project.ruleset.xml.example](project.ruleset.xml.example) file and [fully annotated example](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml) in PHP_CodeSniffer documentation. +### Recommended additional rulesets + +The [PHPCompatibility](https://github.com/wimg/PHPCompatibility) ruleset comes highly recommended. +The [PHPCompatibility](https://github.com/wimg/PHPCompatibility) sniffs are designed to analyse your code for cross-PHP version compatibility. +Install it as a separate ruleset and either run it separately against your code or add it to your custom ruleset. + + +## Fixing errors or whitelisting them + +You can find information on how to deal with some of the more frequent issues in the [wiki](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki). + + ## Contributing See [CONTRIBUTING](CONTRIBUTING.md), including information about [unit testing](CONTRIBUTING.md#unit-testing). From ba60ba4552063d31860adf3911aa9f7d89cff0ee Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 08:57:12 +0200 Subject: [PATCH 088/122] Remove redundant sniff. Fixed #548 --- WordPress-Core/ruleset.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 965eff8698..0643315627 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -96,6 +96,7 @@ + From 8184bf6000b6c6e8ab482053c6148988472cb812 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 09:24:36 +0200 Subject: [PATCH 089/122] Fix issue with whitelist comment not being recognized if inline comment ends with closing PHP tag. Includes unit test. Also: * added additional unit test for prefixed whitelist comment * minor grammar correction. Fixes #542 --- WordPress/Sniff.php | 4 ++-- WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php | 2 +- WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc | 7 +++++++ WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.php | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index a61440cbb6..0064c2fc5b 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -500,8 +500,8 @@ protected function has_whitelist_comment( $comment, $stackPtr ) { // we need to here. $end_of_statement = $this->phpcsFile->findNext( array( T_CLOSE_TAG, T_SEMICOLON ), $stackPtr ); - // Check at the end of the statement if it comes before the end of the line. - if ( $end_of_statement < $end_of_line ) { + // Check at the end of the statement if it comes before - or is - the end of the line. + if ( $end_of_statement <= $end_of_line ) { // If the statement was ended by a semicolon, we find the next non- // whitespace token. If the semicolon was left out and it was terminated diff --git a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php index ae7d6beb4e..886cd5600e 100644 --- a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php +++ b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php @@ -57,7 +57,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Check for whitelisting comment. if ( ! $this->has_whitelist_comment( 'input var', $stackPtr ) ) { - $phpcsFile->addWarning( 'Detected access of super global var %s, probably need manual inspection.', $stackPtr, 'AccessDetected', array( $varName ) ); + $phpcsFile->addWarning( 'Detected access of super global var %s, probably needs manual inspection.', $stackPtr, 'AccessDetected', array( $varName ) ); } } // end process() diff --git a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc index 36079061e5..19150dd26c 100644 --- a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc +++ b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc @@ -4,6 +4,8 @@ foo( $_GET['bar'] ); foo( $_GET['whitelisted'] ); // input var okay +foo( $_POST['whitelisted_with_prefix'] ); // WPCS: input var okay. + if ( $_GET['test'] && foo() && $bar ) { // input var okay taz(); } @@ -13,3 +15,8 @@ bar( $_POST['foo'] ); // warning quux( $_REQUEST['quux'] ); // warning $_REQUEST['wp_customize'] = 'on'; // ok + +// Issue: https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/542 +if ( isset( $_GET['updated'] ) ) { // input var okay ?> + + 1, - 11 => 1, 13 => 1, + 15 => 1, ); } // end getWarningList() From 9e571795c487b39a883798be874a3eb5da4ff454 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 12:37:30 +0200 Subject: [PATCH 090/122] Use PHPCS build in static token arrays. `PHP_CodeSniffer_Tokens::$emptyTokens` contains `T_WHITESPACE` and all comment tokens making for a more stable check. --- WordPress/Sniffs/PHP/StrictInArraySniff.php | 4 ++-- WordPress/Sniffs/Variables/GlobalVariablesSniff.php | 2 +- WordPress/Sniffs/WP/I18nSniff.php | 2 +- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index 28794b9a38..e197266c66 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -49,7 +49,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - $prevToken = $phpcsFile->findPrevious( array( T_WHITESPACE, T_COMMENT ), ( $stackPtr - 1 ), null, true ); + $prevToken = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); // Skip if this is instance of in_array() not a function call. if ( false === $prevToken || in_array( $tokens[ $prevToken ]['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) { @@ -70,7 +70,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Get last token in the function call. $closeParenthesis = $tokens[ $openParenthesis ]['parenthesis_closer']; - $lastToken = $phpcsFile->findPrevious( array( T_WHITESPACE, T_COMMENT ), ( $closeParenthesis - 1 ), ( $openParenthesis + 1 ), true ); + $lastToken = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $closeParenthesis - 1 ), ( $openParenthesis + 1 ), true ); if ( false === $lastToken ) { $phpcsFile->addError( 'Missing arguments to in_array().', $openParenthesis, 'MissingArguments' ); return; diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index 3fa3fd8c81..8d03d6889c 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -335,7 +335,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Check for assignments to collected global vars. foreach ( $tokens as $ptr => $token ) { if ( T_VARIABLE === $token['code'] && in_array( substr( $token['content'], 1 ), $search, true ) ) { - $next = $phpcsFile->findNext( array( T_WHITESPACE, T_COMMENT ), ( $ptr + 1 ), null, true, null, true ); + $next = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $ptr + 1 ), null, true, null, true ); if ( T_EQUAL === $tokens[ $next ]['code'] ) { if ( ! $this->has_whitelist_comment( 'override', $next ) ) { $phpcsFile->addError( 'Overriding WordPress globals is prohibited', $ptr, 'OverrideProhibited' ); diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 59df276bb1..1b7ea37c4e 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -119,7 +119,7 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { for ( $i = ( $func_open_paren_token + 1 ); $i < $tokens[ $func_open_paren_token ]['parenthesis_closer']; $i += 1 ) { $this_token = $tokens[ $i ]; $this_token['token_index'] = $i; - if ( in_array( $this_token['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { + if ( in_array( $this_token['code'], PHP_CodeSniffer_Tokens::$emptyTokens, true ) ) { continue; } if ( T_COMMA === $this_token['code'] ) { diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 3ee31b4a81..e156334098 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -184,7 +184,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { for ( $i = $stackPtr; $i < $end_of_statement; $i++ ) { // Ignore whitespaces and comments. - if ( in_array( $tokens[ $i ]['code'], array( T_WHITESPACE, T_COMMENT ), true ) ) { + if ( in_array( $tokens[ $i ]['code'], PHP_CodeSniffer_Tokens::$emptyTokens, true ) ) { continue; } From 0a41cd2ab1bffa6ba4189d88dcdb076edc339c5f Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 12:54:09 +0200 Subject: [PATCH 091/122] Add some more PHP magic constants which can be skipped to the EscapeOutputSniff. --- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 3ee31b4a81..1ee7afc002 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -226,7 +226,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Handle magic constants for debug functions. - if ( in_array( $tokens[ $i ]['code'], array( T_METHOD_C, T_FUNC_C, T_FILE, T_CLASS_C ), true ) ) { + if ( in_array( $tokens[ $i ]['code'], array( T_CLASS_C, T_FILE, T_FUNC_C, T_LINE, T_METHOD_C, T_NS_C, T_TRAIT_C ), true ) ) { continue; } From a61084dd10660af71f978a953aa72ebea9f15e6e Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 12:56:55 +0200 Subject: [PATCH 092/122] Add two new function to the `$printingFunctions` array. WP 4.3 introduced `_deprecated_constructor()`. WP 4.6 will introduce `_deprecated_hook()`. --- WordPress/Sniff.php | 34 +++++++++++--------- WordPress/Tests/XSS/EscapeOutputUnitTest.inc | 3 ++ WordPress/Tests/XSS/EscapeOutputUnitTest.php | 1 + 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index a61440cbb6..f1622eb608 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -323,22 +323,24 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * @var array */ public static $printingFunctions = array( - '_deprecated_argument' => true, - '_deprecated_file' => true, - '_deprecated_function' => true, - '_doing_it_wrong' => true, - '_e' => true, - '_ex' => true, - 'die' => true, - 'echo' => true, - 'exit' => true, - 'print' => true, - 'printf' => true, - 'trigger_error' => true, - 'user_error' => true, - 'vprintf' => true, - 'wp_die' => true, - 'wp_dropdown_pages' => true, + '_deprecated_argument' => true, + '_deprecated_constructor' => true, + '_deprecated_file' => true, + '_deprecated_function' => true, + '_deprecated_hook' => true, + '_doing_it_wrong' => true, + '_e' => true, + '_ex' => true, + 'die' => true, + 'echo' => true, + 'exit' => true, + 'print' => true, + 'printf' => true, + 'trigger_error' => true, + 'user_error' => true, + 'vprintf' => true, + 'wp_die' => true, + 'wp_dropdown_pages' => true, ); /** diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.inc b/WordPress/Tests/XSS/EscapeOutputUnitTest.inc index 3132c19ee7..0adf1ebf8b 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.inc +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.inc @@ -177,3 +177,6 @@ echo ''; + +_deprecated_hook( 'some_filter', '1.3.0', esc_html__( 'The $arg is deprecated.' ), 'some_other_filter' ); // OK +_deprecated_hook( "filter_{$context}", '1.3.0', __( 'The $arg is deprecated.' ), sprintf( __( 'Some parsed message %s', $variable ) ) ); // Bad diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.php b/WordPress/Tests/XSS/EscapeOutputUnitTest.php index c9fb7812fe..3d6bae14b8 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.php +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.php @@ -69,6 +69,7 @@ public function getErrorList() { 169 => 1, 172 => 1, 173 => 1, + 182 => 3, ); } // end getErrorList() From 9619ca43d916a07c25f06bde646793bd808ab4e8 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 17:10:42 +0200 Subject: [PATCH 093/122] Carry over changes made in the original class to the overloaded methods. * Defer to the parent class for the list of magic methods - as long as it's up to date, no need to maintain this in WPCS. Historically these properties were `private`, but they have since been changed to `protected` and are therefore now ok to use. * Bow out early for closures. * Allow for `__autoload()` functions outside of the class scope. * Allow for function names only consisting of underscores like `__()`. Last relevant change to the parent class was made in v2.5.1 and as the WPCS minimum version requirement is currently 2.6.0, we're good. --- .../ValidFunctionNameSniff.php | 77 +++++++++++++------ 1 file changed, 53 insertions(+), 24 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index feefc43c70..a247a2b227 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -10,28 +10,15 @@ /** * Enforces WordPress function name format. * + * Last synced with parent class July 2016 at commit 916b09a. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php + * * @category PHP * @package PHP_CodeSniffer * @author John Godley */ class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff { - private $_magicMethods = array( - 'construct', - 'destruct', - 'call', - 'callStatic', - 'get', - 'set', - 'isset', - 'unset', - 'sleep', - 'wakeup', - 'toString', - 'set_state', - 'clone', - 'invoke', - 'debugInfo', ); /** @@ -46,13 +33,40 @@ class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sni protected function processTokenOutsideScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $functionName = $phpcsFile->getDeclarationName( $stackPtr ); + if ( ! isset( $functionName ) ) { + // Ignore closures. + return; + } + + if ( '' === ltrim( $functionName, '_' ) ) { + // Ignore special functions. + return; + } + + // Is this a magic function ? I.e., it is prefixed with "__" ? + // Outside class scope this basically just means __autoload(). + if ( 0 === strpos( $functionName, '__' ) ) { + $magicPart = strtolower( substr( $functionName, 2 ) ); + if ( ! isset( $this->magicFunctions[ $magicPart ] ) ) { + $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $errorData = array( $functionName ); + $phpcsFile->addError( $error, $stackPtr, 'FunctionDoubleUnderscore', $errorData ); + } + + return; + } + if ( strtolower( $functionName ) !== $functionName ) { $suggested = preg_replace( '/([A-Z])/', '_$1', $functionName ); $suggested = strtolower( $suggested ); $suggested = str_replace( '__', '_', $suggested ); - $error = "Function name \"$functionName\" is in camel caps format, try '{$suggested}'"; - $phpcsFile->addError( $error, $stackPtr, 'FunctionNameInvalid' ); + $error = 'Function name "%s" is not in snake case format, try "%s"'; + $errorData = array( + $functionName, + $suggested, + ); + $phpcsFile->addError( $error, $stackPtr, 'FunctionNameInvalid', $errorData ); } } // end processTokenOutsideScope() @@ -68,20 +82,32 @@ protected function processTokenOutsideScope( PHP_CodeSniffer_File $phpcsFile, $s * @return void */ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $currScope ) { - $className = $phpcsFile->getDeclarationName( $currScope ); $methodName = $phpcsFile->getDeclarationName( $stackPtr ); - // Is this a magic method. IE. is prefixed with "__". + if ( ! isset( $methodName ) ) { + // Ignore closures. + return; + } + + $className = $phpcsFile->getDeclarationName( $currScope ); + + // Is this a magic method ? I.e. is it prefixed with "__" ? if ( 0 === strpos( $methodName, '__' ) ) { - $magicPart = substr( $methodName, 2 ); - if ( false === in_array( $magicPart, $this->_magicMethods, true ) ) { - $error = "Method name \"$className::$methodName\" is invalid; only PHP magic methods should be prefixed with a double underscore"; - $phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore' ); + $magicPart = strtolower( substr( $methodName, 2 ) ); + if ( ! isset( $this->magicMethods[ $magicPart ] ) ) { + $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $errorData = array( $className . '::' . $methodName ); + $phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore', $errorData ); } return; } + // Ignore special functions. + if ( '' === ltrim( $methodName, '_' ) ) { + return; + } + // PHP4 constructors are allowed to break our rules. if ( $methodName === $className ) { return; @@ -115,6 +141,9 @@ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $st $testMethodName = $methodName; if ( false === $scopeSpecified && '_' === $methodName{0} ) { $testMethodName = substr( $methodName, 1 ); + // Ignore special functions. + if ( '' === ltrim( $methodName, '_' ) ) { + return; } if ( strtolower( $testMethodName ) !== $testMethodName ) { From 350cc25a31b07de5145800847422b4d5d16161a8 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 17:13:45 +0200 Subject: [PATCH 094/122] Remove a block of superfluous code which was no longer needed after the check for prefixed private methods had been removed. --- .../ValidFunctionNameSniff.php | 25 +------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index a247a2b227..5a22fc8c1c 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -123,30 +123,7 @@ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $st return; } - $methodProps = $phpcsFile->getMethodProperties( $stackPtr ); - $scope = $methodProps['scope']; - $scopeSpecified = $methodProps['scope_specified']; - - if ( 'private' === $methodProps['scope'] ) { - $isPublic = false; - } else { - $isPublic = true; - } - - // If the scope was specified on the method, then the method must be - // camel caps and an underscore should be checked for. If it wasn't - // specified, treat it like a public method and remove the underscore - // prefix if there is one because we can't determine if it is private or - // public. - $testMethodName = $methodName; - if ( false === $scopeSpecified && '_' === $methodName{0} ) { - $testMethodName = substr( $methodName, 1 ); - // Ignore special functions. - if ( '' === ltrim( $methodName, '_' ) ) { - return; - } - - if ( strtolower( $testMethodName ) !== $testMethodName ) { + if ( strtolower( $methodName ) !== $methodName ) { $suggested = preg_replace( '/([A-Z])/', '_$1', $methodName ); $suggested = strtolower( $suggested ); $suggested = str_replace( '__', '_', $suggested ); From 55ea310d82c68feabd6d1d39ad07afd263a4fb6b Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 17:51:15 +0200 Subject: [PATCH 095/122] Fix issue with double underscore prefixed methods in extended classes. Includes reordering of the various conditions within the function for optimal performance. Fixes #507. --- .../ValidFunctionNameSniff.php | 52 ++++++++++++++----- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index 5a22fc8c1c..61cee42d7a 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -19,6 +19,27 @@ */ class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff { + /** + * Additional double underscore prefixed methods specific to certain PHP native extensions. + * + * Currently only handles the SoapClient Extension. + * + * @link http://php.net/manual/en/class.soapclient.php + * + * @var array => + */ + private $methodsDoubleUnderscore = array( + 'doRequest' => 'SoapClient', + 'getFunctions' => 'SoapClient', + 'getLastRequest' => 'SoapClient', + 'getLastRequestHeaders' => 'SoapClient', + 'getLastResponse' => 'SoapClient', + 'getLastResponseHeaders' => 'SoapClient', + 'getTypes' => 'SoapClient', + 'setCookie' => 'SoapClient', + 'setLocation' => 'SoapClient', + 'setSoapHeaders' => 'SoapClient', + 'soapCall' => 'SoapClient', ); /** @@ -91,18 +112,6 @@ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $st $className = $phpcsFile->getDeclarationName( $currScope ); - // Is this a magic method ? I.e. is it prefixed with "__" ? - if ( 0 === strpos( $methodName, '__' ) ) { - $magicPart = strtolower( substr( $methodName, 2 ) ); - if ( ! isset( $this->magicMethods[ $magicPart ] ) ) { - $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; - $errorData = array( $className . '::' . $methodName ); - $phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore', $errorData ); - } - - return; - } - // Ignore special functions. if ( '' === ltrim( $methodName, '_' ) ) { return; @@ -118,8 +127,23 @@ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $st return; } - // If this is a child class, it may have to use camelCase. - if ( $phpcsFile->findExtendedClassName( $currScope ) || $this->findImplementedInterfaceName( $currScope, $phpcsFile ) ) { + $extended = $phpcsFile->findExtendedClassName( $currScope ); + $interface = $this->findImplementedInterfaceName( $currScope, $phpcsFile ); + + // If this is a child class or interface implementation, it may have to use camelCase or double underscores. + if ( $extended || $interface ) { + return; + } + + // Is this a magic method ? I.e. is it prefixed with "__" ? + if ( 0 === strpos( $methodName, '__' ) ) { + $magicPart = strtolower( substr( $methodName, 2 ) ); + if ( ! isset( $this->magicMethods[ $magicPart ] ) && ! isset( $this->methodsDoubleUnderscore[ $magicPart ] ) ) { + $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $errorData = array( $className . '::' . $methodName ); + $phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore', $errorData ); + } + return; } From 833feeae22f186203f77edf45d8e7b0336af38ef Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 18:04:16 +0200 Subject: [PATCH 096/122] Polish it off. * Fix wrong error code for MethodNameInvalid. * Make sure suggested alternative names don't start or end with an underscore. * Add a number of unit tests for: - PHP magic methods (now handled via parent) - SoapClient methods * Minor documentation fixes. * Minor improvement of the MethodNameInvalid error message. --- .../ValidFunctionNameSniff.php | 20 +++-- .../ValidFunctionNameUnitTest.inc | 75 ++++++++++++++++++- .../ValidFunctionNameUnitTest.php | 12 +++ 3 files changed, 98 insertions(+), 9 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index 61cee42d7a..055afe5645 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -1,6 +1,6 @@ addError( $error, $stackPtr, 'FunctionNameInvalid' ); + $error = 'Method name "%s" in class %s is not in snake case format, try "%s"'; + $errorData = array( + $methodName, + $className, + $suggested, + ); + $phpcsFile->addError( $error, $stackPtr, 'MethodNameInvalid', $errorData ); } } // end processTokenWithinScope() diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc index d66445aeee..176bcaeea3 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc @@ -6,7 +6,7 @@ function my_template_tags() {} // Good function _my_template_tags() {} // OK -function __my_template_tags() {} // OK +function __my_template_tags() {} // Bad class My_Plugin { @@ -21,6 +21,9 @@ class My_Plugin { public function __invoke() {} // OK } +/** + * Verify that CamelCase is not checked for extended classes or interfaces. + */ class Test extends WP_UnitTestCase { public function setUp() {} // OK @@ -28,10 +31,74 @@ class Test extends WP_UnitTestCase { class Foo implements ArrayAccess { function offsetSet( $key, $value ) {} // OK - function offsetUnset( $key ) {} // OK - function offsetExists( $key ) {} // OK - function offsetGet( $key ) {} // OK } + + +/** + * Verify all PHP supported magic methods. + */ +class Its_A_Kind_Of_Magic { + function __construct() {} // Ok. + function __destruct() {} // Ok. + function __call() {} // Ok. + function __callStatic() {} // Ok. + function __get() {} // Ok. + function __set() {} // Ok. + function __isset() {} // Ok. + function __unset() {} // Ok. + function __sleep() {} // Ok. + function __wakeup() {} // Ok. + function __toString() {} // Ok. + function __set_state() {} // Ok. + function __clone() {} // Ok. + function __invoke() {} // Ok. + function __debugInfo() {} // Ok. +} + +/** + * Verify SoapClient magic methods. + */ +class My_Soap extends SoapClient { + public function __doRequest() {} // Ok. + public function __getFunctions() {} // Ok. + public function __getLastRequest() {} // Ok. + public function __getLastRequestHeaders() {} // Ok. + public function __getLastResponse() {} // Ok. + public function __getLastResponseHeaders() {} // Ok. + public function __getTypes() {} // Ok. + public function __setCookie() {} // Ok. + public function __setLocation() {} // Ok. + public function __setSoapHeaders() {} // Ok. + public function __soapCall() {} // Ok. +} + +class My_Soap { + public function __doRequest() {} // Bad. + private function __getFunctions() {} // Bad. + protected function __getLastRequest() {} // Bad. + public function __getLastRequestHeaders() {} // Bad. + public function __getLastResponse() {} // Bad. + public function __getLastResponseHeaders() {} // Bad. + public function __getTypes() {} // Bad. + public function __setCookie() {} // Bad. + public function __setLocation() {} // Bad. + public function __setSoapHeaders() {} // Bad. + public function __soapCall() {} // Bad. +} + +class My_Soap extends somethingElse { + public function __doRequest() {} // Ok - as somethingElse might be extended from SoapClient again. + private function __getFunctions() {} // Ok. + protected function __getLastRequest() {} // Ok. + public function __getLastRequestHeaders() {} // Ok. + public function __getLastResponse() {} // Ok. + public function __getLastResponseHeaders() {} // Ok. + public function __getTypes() {} // Ok. + public function __setCookie() {} // Ok. + public function __setLocation() {} // Ok. + public function __setSoapHeaders() {} // Ok. + public function __soapCall() {} // Ok. +} diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php index d33b7ab8e2..c11cce2650 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.php @@ -35,8 +35,20 @@ class WordPress_Tests_NamingConventions_ValidFunctionNameUnitTest extends Abstra public function getErrorList() { return array( 3 => 1, + 9 => 1, 13 => 1, 15 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + 82 => 1, + 83 => 1, + 84 => 1, + 85 => 1, + 86 => 1, + 87 => 1, + 88 => 1, + 89 => 1, ); } // end getErrorList() From 3b9ae92607295548df357e108fd27090cf89d1d7 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 18 Jul 2016 14:06:52 +0200 Subject: [PATCH 097/122] Add sniff for Restricted Database Classes. * Add `AbstractClassRestrictionsSniff` which can sniff for the use of (namespaced) classes. The abstract class does currently not support `use` statement aliased namespaces. * Refactored the `AbstractFunctionRestrictionsSniff` somewhat to make parts more reusable and extended the `AbstractClassRestrictionsSniff` from this class. * This refactoring includes a small efficiency improvement where the function regular expressions are no longer rebuild for every token, but only build once. * Add `DB/RestrictedClassesSniff` to actually sniff for the Restricted DB Classes. * Added extensive unit tests which test both the `DB/RestrictedClassesSniff` as well as the complete functionality of the Abstract class. If at some point in the future the `AbstractFunctionRestrictionsSniff` would need to support namespaces too, this will not be too hard to do. Some functions would need to be moved from the `AbstractClassRestrictionsSniff` to the `AbstractFunctionRestrictionsSniff` and the the functionname determination would need to start using them, but the underlying logic has already been build. --- WordPress-Core/ruleset.xml | 3 +- WordPress/AbstractClassRestrictionsSniff.php | 263 ++++++++++++++++++ .../AbstractFunctionRestrictionsSniff.php | 101 +++++-- .../Sniffs/DB/RestrictedClassesSniff.php | 55 ++++ .../Tests/DB/RestrictedClassesUnitTest.1.inc | 41 +++ .../Tests/DB/RestrictedClassesUnitTest.2.inc | 47 ++++ .../Tests/DB/RestrictedClassesUnitTest.3.inc | 92 ++++++ .../Tests/DB/RestrictedClassesUnitTest.php | 157 +++++++++++ 8 files changed, 736 insertions(+), 23 deletions(-) create mode 100644 WordPress/AbstractClassRestrictionsSniff.php create mode 100644 WordPress/Sniffs/DB/RestrictedClassesSniff.php create mode 100644 WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc create mode 100644 WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc create mode 100644 WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc create mode 100644 WordPress/Tests/DB/RestrictedClassesUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 0375c06d42..c2d1a687b9 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -114,7 +114,8 @@ - + + diff --git a/WordPress/AbstractClassRestrictionsSniff.php b/WordPress/AbstractClassRestrictionsSniff.php new file mode 100644 index 0000000000..bcb2164958 --- /dev/null +++ b/WordPress/AbstractClassRestrictionsSniff.php @@ -0,0 +1,263 @@ + + */ +abstract class WordPress_AbstractClassRestrictionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { + + /** + * Groups of function data to check against. + * Don't use this in extended classes, override getGroups() instead. + * This is only used for Unit tests. + * + * @var array + */ + public static $unittest_groups = array(); + + /** + * Regex pattern with placeholder for the function names. + * + * @var string + */ + protected $regex_pattern = '`^\\\\(?:%s)$`i'; + + /** + * Groups of classes to restrict. + * + * This method should be overridden in extending classes. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Avoid direct calls to the database.', + * 'classes' => array( 'PDO', '\Namespace\Classname' ), + * ) + * ) + * + * You can use * wildcards to target a group of (namespaced) classes. + * Aliased namespaces (use ..) are currently not supported. + * + * Documented here for clarity. Not (re)defined as it is already defined in the parent class. + * + * @return array + */ + // abstract public function getGroups(); + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + // Prepare the function group regular expressions only once. + if ( false === $this->setup_groups( 'classes' ) ) { + return array(); + } + + return array( + T_DOUBLE_COLON, + T_NEW, + T_EXTENDS, + T_IMPLEMENTS, + ); + + } // end register() + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + $classname = ''; + + if ( in_array( $token['code'], array( T_NEW, T_EXTENDS, T_IMPLEMENTS ), true ) ) { + if ( T_NEW === $token['code'] ) { + $nameEnd = ( $phpcsFile->findNext( array( T_OPEN_PARENTHESIS, T_WHITESPACE, T_SEMICOLON, T_OBJECT_OPERATOR ), ( $stackPtr + 2 ) ) - 1 ); + } else { + $nameEnd = ( $phpcsFile->findNext( array( T_CLOSE_CURLY_BRACKET, T_WHITESPACE ), ( $stackPtr + 2 ) ) - 1 ); + } + + $length = ( $nameEnd - ( $stackPtr + 1 ) ); + $classname = $phpcsFile->getTokensAsString( ( $stackPtr + 2 ), $length ); + + if ( T_NS_SEPARATOR !== $tokens[ ( $stackPtr + 2 ) ]['code'] ) { + $classname = $this->get_namespaced_classname( $classname, $phpcsFile, $tokens, ( $stackPtr - 1 ) ); + } + } + + if ( T_DOUBLE_COLON === $token['code'] ) { + $nameEnd = $phpcsFile->findPrevious( array( T_STRING ), ( $stackPtr - 1 ) ); + $nameStart = ( $phpcsFile->findPrevious( array( T_STRING, T_NS_SEPARATOR, T_NAMESPACE ), ( $nameEnd - 1 ), null, true, null, true ) + 1 ); + $length = ( $nameEnd - ( $nameStart - 1) ); + $classname = $phpcsFile->getTokensAsString( $nameStart, $length ); + + if ( T_NS_SEPARATOR !== $tokens[ $nameStart ]['code'] ) { + $classname = $this->get_namespaced_classname( $classname, $phpcsFile, $tokens, ( $nameStart - 1 ) ); + } + } + + // Stop if we couldn't determine a classname. + if ( empty( $classname ) ) { + return; + } + + // Nothing to do if 'parent', 'self' or 'static'. + if ( in_array( $classname, array( 'parent', 'self', 'static' ), true ) ) { + return; + } + + $exclude = explode( ',', $this->exclude ); + + foreach ( $this->groups as $groupName => $group ) { + + if ( in_array( $groupName, $exclude, true ) ) { + continue; + } + + if ( preg_match( $group['regex'], $classname ) < 1 ) { + continue; + } + + if ( 'warning' === $group['type'] ) { + $addWhat = array( $phpcsFile, 'addWarning' ); + } else { + $addWhat = array( $phpcsFile, 'addError' ); + } + + call_user_func( + $addWhat, + $group['message'], + $stackPtr, + $groupName, + array( $classname ) + ); + + } + + } // end process() + + /** + * Prepare the class name for use in a regular expression. + * + * The getGroups() method allows for providing class names with a wildcard * to target + * a group of classes within a namespace. It also allows for providing class names as + * 'ordinary' names or prefixed with one or more namespaces. + * This prepare routine takes that into account while still safely escaping the + * class name for use in a regular expression. + * + * @param string $classname Class name, potentially prefixed with namespaces. + * @return string Regex escaped class name. + */ + protected function prepare_name_for_regex( $classname ) { + $classname = trim( $classname, '\\' ); // Make sure all classnames have a \ prefix, but only one. + $classname = str_replace( array( '.*', '*' ) , '#', $classname ); // Replace wildcards with placeholder. + $classname = preg_quote( $classname, '`' ); + $classname = str_replace( '#', '.*', $classname ); // Replace placeholder with regex wildcard. + + return $classname; + } + + /** + * See if the classname was found in a namespaced file and if so, add the namespace to the classname. + * + * @param string $classname The full classname as found. + * @param object $phpcsFile Instance of phpcsFile. + * @param array $tokens The token stack for this file. + * @param int $search_from The token position to search up from. + * @return string Classname, potentially prefixed with the namespace. + */ + protected function get_namespaced_classname( $classname, $phpcsFile, $tokens, $search_from ) { + // Don't do anything if this is already a fully qualified classname. + if ( empty( $classname ) || '\\' === $classname[0] ) { + return $classname; + } + + // Remove the namespace keyword if used. + if ( 0 === strpos( $classname, 'namespace\\' ) ) { + $classname = substr( $classname, 10 ); + } + + $namespace_keyword = $phpcsFile->findPrevious( T_NAMESPACE, $search_from ); + if ( false === $namespace_keyword ) { + // No namespace keyword found at all, so global namespace. + $classname = '\\' . $classname; + } else { + $namespace = $this->determine_namespace( $phpcsFile, $tokens, $search_from ); + + if ( ! empty( $namespace ) ) { + $classname = '\\' . $namespace . '\\' . $classname; + } else { + // No actual namespace found, so global namespace. + $classname = '\\' . $classname; + } + } + + return $classname; + } + + /** + * Determine the namespace name based on whether this is a scoped namespace or a file namespace. + * + * @param object $phpcsFile Instance of phpcsFile. + * @param array $tokens The token stack for this file. + * @param int $search_from The token position to search up from. + * @return string Namespace name or empty string if it couldn't be determined or no namespace applied. + */ + protected function determine_namespace( $phpcsFile, $tokens, $search_from ) { + $namespace = ''; + + if ( ! empty( $tokens[ $search_from ]['conditions'] ) ) { + // Scoped namespace {}. + foreach ( $tokens[ $search_from ]['conditions'] as $pointer => $type ) { + if ( T_NAMESPACE === $type && $tokens[ $pointer ]['scope_closer'] > $search_from ) { + $namespace = $this->get_namespace_name( $phpcsFile, $tokens, $pointer ); + } + break; // We only need to check the highest level condition. + } + } else { + // Let's see if we can find a file namespace instead. + $first = $phpcsFile->findNext( array( T_NAMESPACE ), 0, $search_from ); + + if ( empty( $tokens[ $first ]['scope_condition'] ) ) { + $namespace = $this->get_namespace_name( $phpcsFile, $tokens, $first ); + } + } + + return $namespace; + } + + /** + * Get the namespace name based on the position of the namespace scope opener. + * + * @param object $phpcsFile Instance of phpcsFile. + * @param array $tokens The token stack for this file. + * @param int $t_namespace_token The token position to search from. + * @return string Namespace name. + */ + protected function get_namespace_name( $phpcsFile, $tokens, $t_namespace_token ) { + $nameEnd = ( $phpcsFile->findNext( array( T_OPEN_CURLY_BRACKET, T_WHITESPACE, T_SEMICOLON ), ( $t_namespace_token + 2 ) ) - 1 ); + $length = ( $nameEnd - ( $t_namespace_token + 1 ) ); + $namespace = $phpcsFile->getTokensAsString( ( $t_namespace_token + 2 ), $length ); + + return $namespace; + } + +} // end class diff --git a/WordPress/AbstractFunctionRestrictionsSniff.php b/WordPress/AbstractFunctionRestrictionsSniff.php index 9f731b2ddf..dca37bd78a 100644 --- a/WordPress/AbstractFunctionRestrictionsSniff.php +++ b/WordPress/AbstractFunctionRestrictionsSniff.php @@ -26,17 +26,27 @@ abstract class WordPress_AbstractFunctionRestrictionsSniff implements PHP_CodeSn public $exclude = ''; /** - * Returns an array of tokens this test wants to listen for. + * Groups of function data to check against. + * Don't use this in extended classes, override getGroups() instead. + * This is only used for Unit tests. * - * @return array + * @var array */ - public function register() { - return array( - T_STRING, - T_EVAL, - ); + public static $unittest_groups = array(); - } // end register() + /** + * Regex pattern with placeholder for the function names. + * + * @var string + */ + protected $regex_pattern = '`\b(?:%s)\b`i'; + + /** + * Cache for the group information. + * + * @var array + */ + protected $groups = array(); /** * Groups of functions to restrict. @@ -51,10 +61,66 @@ public function register() { * ) * ) * + * You can use * wildcards to target a group of functions. + * * @return array */ abstract public function getGroups(); + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + // Prepare the function group regular expressions only once. + if ( false === $this->setup_groups( 'functions' ) ) { + return array(); + } + + return array( + T_STRING, + T_EVAL, + ); + } + + /** + * Set up the regular expressions for each group. + * + * @param string $key The group array index key where the input for the regular expression can be found. + * @return bool True is the groups were setup. False if not. + */ + protected function setup_groups( $key ) { + // Prepare the function group regular expressions only once. + $this->groups = $this->getGroups(); + + if ( empty( $this->groups ) && empty( self::$unittest_groups ) ) { + return false; + } + + // Allow for adding extra unit tests. + if ( ! empty( self::$unittest_groups ) ) { + $this->groups = array_merge( $this->groups, self::$unittest_groups ); + } + + foreach ( $this->groups as $groupName => $group ) { + if ( empty( $group[ $key ] ) ) { + unset( $this->groups[ $groupName ] ); + } else { + $items = array_map( array( $this, 'prepare_name_for_regex' ), $group[ $key ] ); + $items = implode( '|', $items ); + + $this->groups[ $groupName ]['regex'] = sprintf( $this->regex_pattern, $items ); + } + } + + if ( empty( $this->groups ) ) { + return false; + } + + return true; + } + /** * Processes this test, when one of its tokens is encountered. * @@ -93,22 +159,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $exclude = explode( ',', $this->exclude ); - $groups = $this->getGroups(); - - if ( empty( $groups ) ) { - return ( count( $tokens ) + 1 ); - } - - foreach ( $groups as $groupName => $group ) { + foreach ( $this->groups as $groupName => $group ) { if ( in_array( $groupName, $exclude, true ) ) { continue; } - $functions = array_map( array( $this, 'prepare_functionname_for_regex' ), $group['functions'] ); - $functions = implode( '|', $functions ); - - if ( preg_match( '`\b(?:' . $functions . ')\b`i', $token['content'] ) < 1 ) { + if ( preg_match( $group['regex'], $token['content'] ) < 1 ) { continue; } @@ -133,14 +190,14 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { /** * Prepare the function name for use in a regular expression. * - * The getGroups() method allows for providing function with a wildcard * to target + * The getGroups() method allows for providing function names 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. + * @return string Regex escaped function name. */ - protected function prepare_functionname_for_regex( $function ) { + protected function prepare_name_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. diff --git a/WordPress/Sniffs/DB/RestrictedClassesSniff.php b/WordPress/Sniffs/DB/RestrictedClassesSniff.php new file mode 100644 index 0000000000..f036014a2c --- /dev/null +++ b/WordPress/Sniffs/DB/RestrictedClassesSniff.php @@ -0,0 +1,55 @@ + + */ +class WordPress_Sniffs_DB_RestrictedClassesSniff extends WordPress_AbstractClassRestrictionsSniff { + + /** + * Groups of classes to restrict. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Avoid direct calls to the database.', + * 'classes' => array( 'PDO', '\Namespace\Classname' ), + * ) + * ) + * + * @return array + */ + public function getGroups() { + return array( + + 'mysql' => array( + 'type' => 'error', + 'message' => 'Accessing the database directly should be avoided. Please use the $wpdb object and associated functions instead. Found: %s.', + 'classes' => array( + 'mysqli', + 'PDO', + 'PDOStatement', + ), + ), + + ); + } + +} // end class diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc new file mode 100644 index 0000000000..03af35213e --- /dev/null +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc @@ -0,0 +1,41 @@ +exec(); +PDO::getAvailableDrivers() + +$db7 = new PDOStatement; +$db8 = new \PDOStatement(); + diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc new file mode 100644 index 0000000000..b4fad2d8e1 --- /dev/null +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc @@ -0,0 +1,47 @@ + resolves to \My\PDO +} + +class DBextendes implements \PDO { // Bad -> fully qualified as \PDO +} + +$db0 = new \DBlayer; // Ok - fully qualified as \DBlayer +$db1 = new DBlayer; // Bad - resolves to \My\DBlayer +$db2 = new DBlayer(); // Bad - resolves to \My\DBlayer + +echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer +echo DBlayer::$property; // Bad - resolves to \My\DBlayer +echo DBlayer::connect(); // Bad - resolves to \My\DBlayer + +$db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer + +echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer +echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer +echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer + +$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer + +echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer + +echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer +echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer +echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc new file mode 100644 index 0000000000..fd1ddf14a8 --- /dev/null +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc @@ -0,0 +1,92 @@ + resolves to \My\PDO + } + + class DBextendes implements \PDO { // Bad -> fully qualified as \PDO + } + + $db0 = new \DBlayer; // Ok - fully qualified as \DBlayer + $db1 = new DBlayer; // Bad - resolves to \My\DBlayer + $db2 = new DBlayer(); // Bad - resolves to \My\DBlayer + + echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer + echo DBlayer::$property; // Bad - resolves to \My\DBlayer + echo DBlayer::connect(); // Bad - resolves to \My\DBlayer + + $db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer + + echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer + echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer + echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer + + $db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer + + echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer + echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer + echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer + + echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer + echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer + echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer + +} + +// Now we're outside the namespace, so things should work differently +$db0 = new \DBlayer; // Ok. +$db1 = new DBlayer; // Ok. +$db2 = new DBlayer(); // Ok. + +echo DBlayer::VERSION; // Ok. +echo DBlayer::$property; // Ok. +echo DBlayer::connect(); // Ok. + +$db3 = new Yours\DBlayer; // Ok - resolves to \Yours\DBlayer + +echo Yours\DBlayer::VERSION; // Ok - resolves to \Yours\DBlayer +echo Yours\DBlayer::$property; // Ok - resolves to \Yours\DBlayer +echo Yours\DBlayer::connect(); // Ok - resolves to \Yours\DBlayer + +$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer + +echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer + +echo namespace\DBlayer::VERSION; // Ok. +echo namespace\DBlayer::$property; // Ok. +echo namespace\DBlayer::connect(); // Ok. + + +// Testing second namespace within one file. +namespace AdoDb { + + class Test {} + + class Tester {} + + class TestAgain extends Test {} // Bad. + + class TestYetAgain extends Tester {} // Bad. + + $db5 = new Test; // Bad + $db6 = new Tester(); // Bad +} + +$db7 = new Test; // Ok diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.php b/WordPress/Tests/DB/RestrictedClassesUnitTest.php new file mode 100644 index 0000000000..2c8eef383f --- /dev/null +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.php @@ -0,0 +1,157 @@ + + * @author Greg Sherwood + * @author Marc McIntyre + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: @package_version@ + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class WordPress_Tests_DB_RestrictedClassesUnitTest extends AbstractSniffUnitTest { + + /** + * Add a number of extra restricted classes to unit test the abstract + * ClassRestrictions class. + * + * Note: as that class extends the abstract FunctionRestrictions class, that's + * where we are passing the parameters to. + */ + protected function setUp() { + parent::setUp(); + + WordPress_AbstractFunctionRestrictionsSniff::$unittest_groups = array( + 'test' => array( + 'type' => 'error', + 'message' => 'Detected usage of %s.', + 'classes' => array( + '\My\DBlayer', + 'AdoDb\Test*', + ), + ), + ); + } + + /** + * Skip this test on PHP 5.2 as otherwise testing the namespace resolving would fail. + * + * @return bool Whether to skip this test. + */ + protected function shouldSkipTest() { + return version_compare( PHP_VERSION, '5.3.0', '<' ); + } + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array(int => int) + */ + public function getErrorList( $testFile = '' ) { + switch ( $testFile ) { + case 'RestrictedClassesUnitTest.1.inc': + return array( + 17 => 1, + 18 => 1, + 19 => 1, + 20 => 1, + 22 => 1, + 23 => 1, + 24 => 1, + 25 => 1, + 26 => 1, + 27 => 1, + 29 => 1, + 30 => 1, + 32 => 1, + 33 => 1, + 35 => 1, + 36 => 1, + 37 => 1, + 39 => 1, + 40 => 1, + ); + + case 'RestrictedClassesUnitTest.2.inc': + return array( + 16 => 1, + 22 => 1, + 26 => 1, + 27 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 39 => 1, + 41 => 1, + 42 => 1, + 43 => 1, + 45 => 1, + 46 => 1, + 47 => 1, + ); + + case 'RestrictedClassesUnitTest.3.inc': + return array( + 16 => 1, + 22 => 1, + 26 => 1, + 27 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 39 => 1, + 41 => 1, + 42 => 1, + 43 => 1, + 45 => 1, + 46 => 1, + 47 => 1, + 66 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 84 => 1, + 86 => 1, + 88 => 1, + 89 => 1, + ); + + default: + return array(); + + } + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } + +} // end class From be7951c130b15b49531f23dc974e57bb511a71ae Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 23:53:11 +0200 Subject: [PATCH 098/122] Change the list of PHP magic constants to a class property. --- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 1ee7afc002..33a0e03fdf 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -74,6 +74,21 @@ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { */ public static $addedCustomFunctions = false; + /** + * List of names of the tokens representing PHP magic constants. + * + * @var array + */ + private $magic_constant_tokens = array( + 'T_CLASS_C' => true, // __CLASS__ + 'T_FILE' => true, // __FILE__ + 'T_FUNC_C' => true, // __FUNCTION__ + 'T_LINE' => true, // __LINE__ + 'T_METHOD_C' => true, // __METHOD__ + 'T_NS_C' => true, // __NAMESPACE__ + 'T_TRAIT_C' => true, // __TRAIT__ + ); + /** * Returns an array of tokens this test wants to listen for. * @@ -226,7 +241,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Handle magic constants for debug functions. - if ( in_array( $tokens[ $i ]['code'], array( T_CLASS_C, T_FILE, T_FUNC_C, T_LINE, T_METHOD_C, T_NS_C, T_TRAIT_C ), true ) ) { + if ( isset( $this->magic_constant_tokens[ $tokens[ $i ]['type'] ] ) ) { continue; } From f57842bd58022579493098d6bdbc638f76ce8621 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 20 Jul 2016 01:02:40 +0200 Subject: [PATCH 099/122] Add strict type checking for array_search() and array_keys(). Will only check for the `$strict` parameter for `array_keys()` if the second parameter has been set. Fixes #503. The file/sniff name is now a bit dated as the sniff checks for more than just `in_array()`, but changing the file/sniff/classname would break backward compatibility. What do you think ? --- WordPress/Sniffs/PHP/StrictInArraySniff.php | 59 ++++++++++++++++--- WordPress/Tests/PHP/StrictInArrayUnitTest.inc | 20 +++++++ WordPress/Tests/PHP/StrictInArrayUnitTest.php | 8 +++ 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index e197266c66..019e8e4a11 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -8,7 +8,7 @@ */ /** - * Flag calling in_array() without true as the third parameter. + * Flag calling in_array(), array_search() and array_keys() without true as the third parameter. * * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#using-in_array-without-strict-parameter * @@ -17,6 +17,26 @@ */ class WordPress_Sniffs_PHP_StrictInArraySniff extends WordPress_Sniff { + /** + * List of array functions to which a $strict parameter can be passed. + * + * The $strict parameter is the third and last parameter for each of these functions. + * + * The array_keys() function only requires the $strict parameter when the optional + * second parameter $search has been set. + * + * @link http://php.net/in-array + * @link http://php.net/array-search + * @link http://php.net/array-keys + * + * @var array => + */ + protected $array_functions = array( + 'in_array' => true, + 'array_search' => true, + 'array_keys' => false, + ); + /** * Returns an array of tokens this test wants to listen for. * @@ -39,9 +59,10 @@ public function register() { */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); + $token = strtolower( $tokens[ $stackPtr ]['content'] ); - // Skip any token that is not 'in_array'. - if ( 'in_array' !== strtolower( $tokens[ $stackPtr ]['content'] ) ) { + // Bail out if not one of the targetted functions. + if ( ! isset( $this->array_functions[ $token ] ) ) { return; } @@ -49,12 +70,21 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - $prevToken = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); + $prev = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); - // Skip if this is instance of in_array() not a function call. - if ( false === $prevToken || in_array( $tokens[ $prevToken ]['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) { - return; + if ( false !== $prev ) { + // Skip sniffing if calling a same-named method, or on function definitions. + if ( in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) ) { + return; + } + + // Skip namespaced functions, ie: \foo\bar() not \bar(). + $pprev = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $prev - 1 ), null, true ); + if ( false !== $pprev && T_NS_SEPARATOR === $tokens[ $prev ]['code'] && T_STRING === $tokens[ $pprev ]['code'] ) { + return; + } } + unset( $prev, $pprev ); // Get the closing parenthesis. $openParenthesis = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $stackPtr + 1 ) ); @@ -71,13 +101,24 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Get last token in the function call. $closeParenthesis = $tokens[ $openParenthesis ]['parenthesis_closer']; $lastToken = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $closeParenthesis - 1 ), ( $openParenthesis + 1 ), true ); + + // Check if the strict check is actually needed. + if ( false === $this->array_functions[ $token ] ) { + $hasComma = $phpcsFile->findPrevious( T_COMMA, ( $closeParenthesis - 1 ), ( $openParenthesis + 1 ) ); + if ( false === $hasComma || end( $tokens[ $hasComma ]['nested_parenthesis'] ) !== $closeParenthesis ) { + return; + } + } + + $errorData = array( $token ); + if ( false === $lastToken ) { - $phpcsFile->addError( 'Missing arguments to in_array().', $openParenthesis, 'MissingArguments' ); + $phpcsFile->addError( 'Missing arguments to %s.', $openParenthesis, 'MissingArguments', $errorData ); return; } if ( T_TRUE !== $tokens[ $lastToken ]['code'] ) { - $phpcsFile->addWarning( 'Not using strict comparison for in_array(); supply true for third argument.', $lastToken, 'MissingTrueStrict' ); + $phpcsFile->addWarning( 'Not using strict comparison for %s; supply true for third argument.', $lastToken, 'MissingTrueStrict', $errorData ); return; } } // end process() diff --git a/WordPress/Tests/PHP/StrictInArrayUnitTest.inc b/WordPress/Tests/PHP/StrictInArrayUnitTest.inc index a0522f0a0d..a23ab1f3fb 100644 --- a/WordPress/Tests/PHP/StrictInArrayUnitTest.inc +++ b/WordPress/Tests/PHP/StrictInArrayUnitTest.inc @@ -18,3 +18,23 @@ $bar-> in_array( 1, array( '1', 1, true ) ); // OK in_array(); // Error + + +array_search( 1, $array, true ); // Ok. +$my->array_search( $array, $needle ); // Ok. + +array_search( 1, $array, false ); // Warning. +array_search( 1, $array ); // Warning. +Array_Search( 1, $array ); // Warning. +ARRAY_SEARCH( 1, array( '1', 1, true ) ); // Warning. + + +array_keys( $testing ); // Ok. +array_keys( array( '1', 1, true ) ); // Ok. +array_keys( $testing, 'my_key', true ); // Ok. +array_keys( array( '1', 1, true ), 'my_key', true ); // Ok. + +array_keys( $testing, 'my_key' ); // Warning. +array_keys( array( '1', 1, true ), 'my_key' ); // Warning. +array_keys( $testing, 'my_key', false ); // Warning. +array_keys( array( '1', 1, true ), 'my_key', false ); // Warning. diff --git a/WordPress/Tests/PHP/StrictInArrayUnitTest.php b/WordPress/Tests/PHP/StrictInArrayUnitTest.php index 18a4a8fbcc..9966470356 100644 --- a/WordPress/Tests/PHP/StrictInArrayUnitTest.php +++ b/WordPress/Tests/PHP/StrictInArrayUnitTest.php @@ -46,6 +46,14 @@ public function getWarningList() { 5 => 1, 9 => 1, 10 => 1, + 26 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 37 => 1, + 38 => 1, + 39 => 1, + 40 => 1, ); } // end getWarningList() From e9eeb8ab4ea1d91b90e33016b479a62a3656da4d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 20 Jul 2016 02:27:15 +0200 Subject: [PATCH 100/122] Fix one error missing identifier. Also unduplicated error data in same sniff. --- WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php index d000d94599..8f89c997d6 100644 --- a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php +++ b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php @@ -102,7 +102,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->get_interpolated_variables( $tokens[ $stackPtr ]['content'] ) ); foreach ( array_intersect( $interpolated_variables, $superglobals ) as $bad_variable ) { - $phpcsFile->addError( 'Detected usage of a non-sanitized, non-validated input variable %s: %s', $stackPtr, null, array( $bad_variable, $tokens[ $stackPtr ]['content'] ) ); + $phpcsFile->addError( 'Detected usage of a non-sanitized, non-validated input variable %s: %s', $stackPtr, 'InputNotValidatedNotSanitized', array( $bad_variable, $tokens[ $stackPtr ]['content'] ) ); } return; @@ -129,9 +129,11 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } + $error_data = array( $tokens[ $stackPtr ]['content'] ); + // Check for validation first. if ( ! $this->is_validated( $stackPtr, $array_key, $this->check_validation_in_scope_only ) ) { - $phpcsFile->addError( 'Detected usage of a non-validated input variable: %s', $stackPtr, 'InputNotValidated', array( $tokens[ $stackPtr ]['content'] ) ); + $phpcsFile->addError( 'Detected usage of a non-validated input variable: %s', $stackPtr, 'InputNotValidated', $error_data ); // return; // Should we just return and not look for sanitizing functions ? } @@ -146,7 +148,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Now look for sanitizing functions. if ( ! $this->is_sanitized( $stackPtr, true ) ) { - $phpcsFile->addError( 'Detected usage of a non-sanitized input variable: %s', $stackPtr, 'InputNotSanitized', array( $tokens[ $stackPtr ]['content'] ) ); + $phpcsFile->addError( 'Detected usage of a non-sanitized input variable: %s', $stackPtr, 'InputNotSanitized', $error_data ); } return; From 449840391bba1b1a89476df1d7ce93410a49d68d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 20 Jul 2016 18:20:09 +0200 Subject: [PATCH 101/122] Add ability to whitelist specific functions to the `AbstractFunctionRestrictions` class. This is only useful when used in combination with blocking a function group using a wildcard in the function name. However, it does make it more forward compatible. This allows to still block a complete (PHP) extension , even for new functions being added to the extension, while whitelisting - for instance - a WP native function which was named a bit unfortunately. --- WordPress/AbstractFunctionRestrictionsSniff.php | 4 ++++ WordPress/Sniffs/DB/RestrictedFunctionsSniff.php | 3 +++ WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc | 14 ++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/WordPress/AbstractFunctionRestrictionsSniff.php b/WordPress/AbstractFunctionRestrictionsSniff.php index dca37bd78a..4598c1a742 100644 --- a/WordPress/AbstractFunctionRestrictionsSniff.php +++ b/WordPress/AbstractFunctionRestrictionsSniff.php @@ -165,6 +165,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { continue; } + if ( isset( $group['whitelist'][ $token['content'] ] ) ) { + continue; + } + if ( preg_match( $group['regex'], $token['content'] ) < 1 ) { continue; } diff --git a/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php index 72d2cb3f89..8fb9735aa2 100644 --- a/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php @@ -51,6 +51,9 @@ public function getGroups() { 'mysqlnd_memcache_*', 'maxdb_*', ), + 'whitelist' => array( + 'mysql_to_rfc3339' => true, + ), ), ); diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc index 5c8c29fc08..821abf7c38 100644 --- a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc @@ -74,3 +74,17 @@ maxdb_num_fields(); maxdb_prepare(); maxdb_real_query maxdb_stat(); + + +/** + * And these shouldn't give an error. + */ + +// WP Native function which was named a bit unfortunately. +mysql_to_rfc3339(); // Ok. + +// Other WP Native functions which shouldn't give a problem anyway. +mysql2date(); // Ok. +wp_check_mysql_version(); // Ok. +wp_check_php_mysql_version(); // Ok. +WP_Date_Query::build_mysql_datetime(); // Ok. From 961d13c3f1bfb13a82954793d1879a8974db3bbf Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 13 Jul 2016 21:13:06 +0200 Subject: [PATCH 102/122] Add sniff to disallow alternative PHP open tags. Fixes #580 This should be removed again if the upstream issue squizlabs/PHP_CodeSniffer#1063 would get traction and the associated PR would be merged *and* the minimum PHPCS version for WPCS would become higher than the version in which the PR is merged ;-) --- WordPress-Core/ruleset.xml | 1 + .../PHP/DisallowAlternativeOpenTagSniff.php | 123 ++++++++++++++++++ .../DisallowAlternativeOpenTagUnitTest.inc | 9 ++ .../DisallowAlternativeOpenTagUnitTest.php | 77 +++++++++++ 4 files changed, 210 insertions(+) create mode 100644 WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php create mode 100644 WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.inc create mode 100644 WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index c2d1a687b9..321bbf652c 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -21,6 +21,7 @@ + diff --git a/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php b/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php new file mode 100644 index 0000000000..7a2afb601c --- /dev/null +++ b/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php @@ -0,0 +1,123 @@ + + */ +class WordPress_Sniffs_PHP_DisallowAlternativeOpenTagSniff implements PHP_CodeSniffer_Sniff { + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + $tokens = array( + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ); + + $asp_enabled = (boolean) ini_get( 'asp_tags' ); + $short_enabled = (boolean) ini_get( 'short_open_tag' ); + + if ( false === $asp_enabled || ( true === $asp_enabled && false === $short_enabled ) ) { + $tokens[] = T_INLINE_HTML; + } + + return $tokens; + + } // end register() + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $openTag = $tokens[ $stackPtr ]; + $asp_enabled = (boolean) ini_get( 'asp_tags' ); + $short_enabled = (boolean) ini_get( 'short_open_tag' ); + + if ( T_OPEN_TAG === $openTag['code'] ) { + if ( '<%' === $openTag['content'] ) { + $error = 'ASP style opening tag used; expected "addError( $error, $stackPtr, 'ASPOpenTagFound', $data ); + } + + if ( ' + diff --git a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php b/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php new file mode 100644 index 0000000000..71e536b2e0 --- /dev/null +++ b/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php @@ -0,0 +1,77 @@ + + */ +class WordPress_Tests_PHP_DisallowAlternativeOpenTagUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() { + $asp_enabled = (boolean) ini_get( 'asp_tags' ); + $short_enabled = (boolean) ini_get( 'short_open_tag' ); + + $errors = array( + 6 => 1, + ); + + if ( true === $asp_enabled ) { + $errors[4] = 1; + } + if ( true === $asp_enabled && ( true === $short_enabled || defined( 'HHVM_VERSION' ) === true ) ) { + $errors[5] = 1; + } + + return $errors; + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() { + $asp_enabled = (boolean) ini_get( 'asp_tags' ); + $short_enabled = (boolean) ini_get( 'short_open_tag' ); + + $warnings = array(); + + if ( false === $asp_enabled ) { + $warnings = array( + 4 => 1, + 5 => 1, + ); + } elseif ( false === $short_enabled && false === defined( 'HHVM_VERSION' ) ) { + $warnings = array( + 5 => 1, + ); + } + + return $warnings; + + } // end getWarningList() + +} // end class From 2cdba84ca7f55dabcc65ee6118da286ca7db6541 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 12:31:12 +0200 Subject: [PATCH 103/122] Make alternative openings tags fixable. Only implemented for when we are sure we've found alternative opening tags. The 'maybe' causes which need manual inspection should not be auto-fixable. --- .../PHP/DisallowAlternativeOpenTagSniff.php | 72 ++++++++++++++++++- .../DisallowAlternativeOpenTagUnitTest.fixed | 9 +++ 2 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed diff --git a/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php b/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php index 7a2afb601c..42c8d0eb6a 100644 --- a/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php +++ b/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php @@ -59,13 +59,33 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { if ( '<%' === $openTag['content'] ) { $error = 'ASP style opening tag used; expected "addError( $error, $stackPtr, 'ASPOpenTagFound', $data ); + + $closer = $this->find_closing_tag( $phpcsFile, $tokens, $stackPtr, '%>' ); + + if ( false === $closer ) { + $phpcsFile->addError( $error, $stackPtr, 'ASPOpenTagFound', $data ); + } else { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ASPOpenTagFound', $data ); + if ( true === $fix ) { + $this->add_changeset( $phpcsFile, $stackPtr, $closer ); + } + } } if ( '' ); + + if ( false === $closer ) { + $phpcsFile->addError( $error, $stackPtr, 'ScriptOpenTagFound', $data ); + } else { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ScriptOpenTagFound', $data ); + if ( true === $fix ) { + $this->add_changeset( $phpcsFile, $stackPtr, $closer ); + } + } } } @@ -77,7 +97,17 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $openTag['content'], $nextVar['content'], ); - $phpcsFile->addError( $error, $stackPtr, 'ASPShortOpenTagFound', $data ); + + $closer = $this->find_closing_tag( $phpcsFile, $tokens, $stackPtr, '%>' ); + + if ( false === $closer ) { + $phpcsFile->addError( $error, $stackPtr, 'ASPShortOpenTagFound', $data ); + } else { + $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ASPShortOpenTagFound', $data ); + if ( true === $fix ) { + $this->add_changeset( $phpcsFile, $stackPtr, $closer ); + } + } } if ( ( true === $asp_enabled && false === $short_enabled ) && ( T_INLINE_HTML === $openTag['code'] && 0 === strpos( $openTag['content'], '<%=' ) ) ) { @@ -120,4 +150,40 @@ private function get_snippet( $content, $length = 40 ) { return $snippet; } // end get_snippet() + /** + * Try and find a matching PHP closing tag. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tokens The token stack. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param string $content The expected content of the closing tag to match the opener. + * @return int|false Pointer to the position in the stack for the closing tag or false if not found. + */ + private function find_closing_tag( PHP_CodeSniffer_File $phpcsFile, $tokens, $stackPtr, $content ) { + $closer = $phpcsFile->findNext( T_CLOSE_TAG, ( $stackPtr + 1 ) ); + + if ( false !== $closer ) { + if ( $content === $tokens[ $closer ]['content'] ) { + return $closer; + } + } + + return false; + } // end find_closing_tag() + + /** + * Add a changeset to replace the alternative PHP tags. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $open_tag_pointer Stack pointer to the PHP open tag. + * @param int $close_tag_pointer Stack pointer to the PHP close tag. + */ + private function add_changeset( $phpcsFile, $open_tag_pointer, $close_tag_pointer ) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken( $open_tag_pointer, 'fixer->replaceToken( $close_tag_pointer, '?>' ); + $phpcsFile->fixer->endChangeset(); + } // end add_changeset() + } // end class diff --git a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed b/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed new file mode 100644 index 0000000000..93ae12630a --- /dev/null +++ b/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed @@ -0,0 +1,9 @@ +
+ +Some content here. + + + +
From be045879d75884c16b722988eba4b2cbea55d498 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 19:32:20 +0200 Subject: [PATCH 104/122] Rename sniff to `DisallowAlternativePHPTags`. --- WordPress-Core/ruleset.xml | 2 +- ...OpenTagSniff.php => DisallowAlternativePHPTagsSniff.php} | 6 ++++-- ...tTest.fixed => DisallowAlternativePHPTagsUnitTest.fixed} | 0 ...gUnitTest.inc => DisallowAlternativePHPTagsUnitTest.inc} | 0 ...gUnitTest.php => DisallowAlternativePHPTagsUnitTest.php} | 4 ++-- 5 files changed, 7 insertions(+), 5 deletions(-) rename WordPress/Sniffs/PHP/{DisallowAlternativeOpenTagSniff.php => DisallowAlternativePHPTagsSniff.php} (96%) rename WordPress/Tests/PHP/{DisallowAlternativeOpenTagUnitTest.fixed => DisallowAlternativePHPTagsUnitTest.fixed} (100%) rename WordPress/Tests/PHP/{DisallowAlternativeOpenTagUnitTest.inc => DisallowAlternativePHPTagsUnitTest.inc} (100%) rename WordPress/Tests/PHP/{DisallowAlternativeOpenTagUnitTest.php => DisallowAlternativePHPTagsUnitTest.php} (93%) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 321bbf652c..b4e973a70f 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -21,7 +21,7 @@ - + diff --git a/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php similarity index 96% rename from WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php rename to WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php index 42c8d0eb6a..b2270e3387 100644 --- a/WordPress/Sniffs/PHP/DisallowAlternativeOpenTagSniff.php +++ b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php @@ -8,7 +8,9 @@ */ /** - * Makes sure that no alternative PHP open tags are used. + * Verifies that no alternative PHP open tags are used. + * + * If alternative PHP open tags are found, this sniff can fix both the open and close tags. * * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/580 * @@ -16,7 +18,7 @@ * @package PHP_CodeSniffer * @author Juliette Reinders Folmer */ -class WordPress_Sniffs_PHP_DisallowAlternativeOpenTagSniff implements PHP_CodeSniffer_Sniff { +class WordPress_Sniffs_PHP_DisallowAlternativePHPTagsSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. diff --git a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.fixed similarity index 100% rename from WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.fixed rename to WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.fixed diff --git a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.inc b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc similarity index 100% rename from WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.inc rename to WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc diff --git a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php similarity index 93% rename from WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php rename to WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php index 71e536b2e0..f27083a7ca 100644 --- a/WordPress/Tests/PHP/DisallowAlternativeOpenTagUnitTest.php +++ b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php @@ -8,7 +8,7 @@ */ /** - * Unit test class for the DisallowAlternativeOpenTag sniff. + * Unit test class for the DisallowAlternativePHPTags sniff. * * A sniff unit test checks a .inc file for expected violations of a single * coding standard. Expected errors and warnings are stored in this class. @@ -17,7 +17,7 @@ * @package PHP_CodeSniffer * @author Juliette Reinders Folmer */ -class WordPress_Tests_PHP_DisallowAlternativeOpenTagUnitTest extends AbstractSniffUnitTest { +class WordPress_Tests_PHP_DisallowAlternativePHPTagsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. From 34d436f567e69d36f6d94f6a5abdf8331c2c3385 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 22 Jul 2016 02:10:38 +0200 Subject: [PATCH 105/122] Revisit the complete logic of the `DisallowAlternativePHPTags` Sniff. New & improved version. Includes additional unit tests. --- .travis.yml | 1 + .../PHP/DisallowAlternativePHPTagsSniff.php | 178 +++++++++++------- .../DisallowAlternativePHPTagsUnitTest.fixed | 9 - .../DisallowAlternativePHPTagsUnitTest.inc | 11 +- ...sallowAlternativePHPTagsUnitTest.inc.fixed | 18 ++ .../DisallowAlternativePHPTagsUnitTest.php | 63 ++++--- myconfig.ini | 3 + 7 files changed, 179 insertions(+), 104 deletions(-) delete mode 100644 WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.fixed create mode 100644 WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc.fixed create mode 100644 myconfig.ini diff --git a/.travis.yml b/.travis.yml index ea05038248..500c1a8546 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,6 +36,7 @@ matrix: - env: PHPCS_BRANCH=3.0 before_script: + - if [[ $TRAVIS_PHP_VERSION != "7.0" && $TRAVIS_PHP_VERSION != "nightly" && $TRAVIS_PHP_VERSION != "hhvm" ]]; then phpenv config-add myconfig.ini; fi - export PHPCS_DIR=/tmp/phpcs - export PHPCS_BIN=$(if [[ $PHPCS_BRANCH == 3.0 ]]; then echo $PHPCS_DIR/bin/phpcs; else echo $PHPCS_DIR/scripts/phpcs; fi) - mkdir -p $PHPCS_DIR && git clone --depth 1 https://github.com/squizlabs/PHP_CodeSniffer.git -b $PHPCS_BRANCH $PHPCS_DIR diff --git a/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php index b2270e3387..e2690c16b6 100644 --- a/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php +++ b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php @@ -3,7 +3,7 @@ * WordPress Coding Standard. * * @category PHP - * @package PHP_CodeSniffer + * @package PHP\CodeSniffer\WordPress-Coding-Standards * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ @@ -15,31 +15,34 @@ * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/580 * * @category PHP - * @package PHP_CodeSniffer + * @package PHP\CodeSniffer\WordPress-Coding-Standards * @author Juliette Reinders Folmer */ class WordPress_Sniffs_PHP_DisallowAlternativePHPTagsSniff implements PHP_CodeSniffer_Sniff { + /** + * Whether ASP tags are enabled or not. + * + * @var bool + */ + private $asp_tags = false; + /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { - $tokens = array( + if ( version_compare( PHP_VERSION, '7.0.0alpha1', '<' ) ) { + $this->asp_tags = (bool) ini_get( 'asp_tags' ); + } + + return array( T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, + T_INLINE_HTML, ); - $asp_enabled = (boolean) ini_get( 'asp_tags' ); - $short_enabled = (boolean) ini_get( 'short_open_tag' ); - - if ( false === $asp_enabled || ( true === $asp_enabled && false === $short_enabled ) ) { - $tokens[] = T_INLINE_HTML; - } - - return $tokens; - } // end register() /** @@ -52,52 +55,51 @@ public function register() { * @return void */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { - $tokens = $phpcsFile->getTokens(); - $openTag = $tokens[ $stackPtr ]; - $asp_enabled = (boolean) ini_get( 'asp_tags' ); - $short_enabled = (boolean) ini_get( 'short_open_tag' ); + $tokens = $phpcsFile->getTokens(); + $openTag = $tokens[ $stackPtr ]; + $content = $openTag['content']; + + if ( '' === trim( $content ) ) { + return; + } if ( T_OPEN_TAG === $openTag['code'] ) { - if ( '<%' === $openTag['content'] ) { - $error = 'ASP style opening tag used; expected "find_closing_tag( $phpcsFile, $tokens, $stackPtr, '%>' ); + if ( '<%' === $content ) { + $error = 'ASP style opening tag used; expected "find_closing_tag( $phpcsFile, $tokens, $stackPtr, '%>' ); + $error_id = 'ASPOpenTagFound'; - if ( false === $closer ) { - $phpcsFile->addError( $error, $stackPtr, 'ASPOpenTagFound', $data ); - } else { - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ASPOpenTagFound', $data ); - if ( true === $fix ) { - $this->add_changeset( $phpcsFile, $stackPtr, $closer ); - } - } + } elseif ( false !== strpos( $content, '' ); + $error_id = 'ScriptOpenTagFound'; } - if ( '' ); + if ( isset( $error, $closer, $error_id ) ) { + $data = array( $content ); if ( false === $closer ) { - $phpcsFile->addError( $error, $stackPtr, 'ScriptOpenTagFound', $data ); + $phpcsFile->addError( $error, $stackPtr, $error_id, $data ); } else { - $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ScriptOpenTagFound', $data ); + $fix = $phpcsFile->addFixableError( $error, $stackPtr, $error_id, $data ); if ( true === $fix ) { - $this->add_changeset( $phpcsFile, $stackPtr, $closer ); + $this->add_changeset( $phpcsFile, $tokens, $stackPtr, $closer ); } } } + + return; } - if ( T_OPEN_TAG_WITH_ECHO === $openTag['code'] && '<%=' === $openTag['content'] ) { + if ( T_OPEN_TAG_WITH_ECHO === $openTag['code'] && '<%=' === $content ) { $error = 'ASP style opening tag used with echo; expected "findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ) ]; + $nextVar = $phpcsFile->findNext( T_WHITESPACE, ( $stackPtr + 1 ), null, true ); + $snippet = $this->get_snippet( $tokens[ $nextVar ]['content'] ); $data = array( - $nextVar['content'], - $openTag['content'], - $nextVar['content'], + $snippet, + $content, + $snippet, ); $closer = $this->find_closing_tag( $phpcsFile, $tokens, $stackPtr, '%>' ); @@ -107,50 +109,67 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } else { $fix = $phpcsFile->addFixableError( $error, $stackPtr, 'ASPShortOpenTagFound', $data ); if ( true === $fix ) { - $this->add_changeset( $phpcsFile, $stackPtr, $closer ); + $this->add_changeset( $phpcsFile, $tokens, $stackPtr, $closer, true ); } } + + return; } - if ( ( true === $asp_enabled && false === $short_enabled ) && ( T_INLINE_HTML === $openTag['code'] && 0 === strpos( $openTag['content'], '<%=' ) ) ) { + // Account for incorrect script open tags. The "(?:]+)?language=[\'"]?php[\'"]?(?:[^>]+)?>)`i', $content, $match ) ) { + $error = 'Script style opening tag used; expected "get_snippet( $content, $match[1] ); + $data = array( $match[1] . $snippet ); - $error = 'Possible use of ASP style short opening tags. Needs manual inspection. Found: %s'; - $data = array( $this->get_snippet( $openTag['content'] ) ); - $phpcsFile->addWarning( $error, $stackPtr, 'MaybeASPShortOpenTagFound', $data ); - } + $phpcsFile->addError( $error, $stackPtr, 'ScriptOpenTagFound', $data ); - if ( false === $asp_enabled && T_INLINE_HTML === $openTag['code'] ) { + return; + } - $data = array( $this->get_snippet( $openTag['content'] ) ); + if ( T_INLINE_HTML === $openTag['code'] && false === $this->asp_tags ) { + if ( false !== strpos( $content, '<%=' ) ) { + $error = 'Possible use of ASP style short opening tags detected. Needs manual inspection. Found: %s'; + $snippet = $this->get_snippet( $content, '<%=' ); + $data = array( '<%=' . $snippet ); - if ( 0 === strpos( $openTag['content'], '<%=' ) ) { - $error = 'Possible use of ASP style short opening tags. Needs manual inspection. Found: %s'; $phpcsFile->addWarning( $error, $stackPtr, 'MaybeASPShortOpenTagFound', $data ); - } elseif ( 0 === strpos( $openTag['content'], '<%' ) ) { - $error = 'Possible use of ASP style opening tags. Needs manual inspection. Found: %s'; + + } elseif ( false !== strpos( $content, '<%' ) ) { + $error = 'Possible use of ASP style opening tags detected. Needs manual inspection. Found: %s'; + $snippet = $this->get_snippet( $content, '<%' ); + $data = array( '<%' . $snippet ); + $phpcsFile->addWarning( $error, $stackPtr, 'MaybeASPOpenTagFound', $data ); - } elseif ( 0 === strpos( $openTag['content'], ' + + + diff --git a/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc.fixed b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc.fixed new file mode 100644 index 0000000000..2b1c151387 --- /dev/null +++ b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.inc.fixed @@ -0,0 +1,18 @@ +
+ +Some content here. + +

Some text and some more text

+ +

Some text and some more text

+ + + + +
diff --git a/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php index f27083a7ca..f68c4a94de 100644 --- a/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php +++ b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php @@ -3,7 +3,7 @@ * Unit test class for WordPress Coding Standard. * * @category PHP - * @package PHP_CodeSniffer + * @package PHP\CodeSniffer\WordPress-Coding-Standards * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ @@ -14,11 +14,38 @@ * coding standard. Expected errors and warnings are stored in this class. * * @category PHP - * @package PHP_CodeSniffer + * @package PHP\CodeSniffer\WordPress-Coding-Standards * @author Juliette Reinders Folmer */ class WordPress_Tests_PHP_DisallowAlternativePHPTagsUnitTest extends AbstractSniffUnitTest { + /** + * Whether ASP tags are enabled or not. + * + * @var bool + */ + private $asp_tags = false; + + /** + * Get the ini values only once. + */ + protected function setUp() { + parent::setUp(); + + if ( version_compare( PHP_VERSION, '7.0.0alpha1', '<' ) ) { + $this->asp_tags = (bool) ini_get( 'asp_tags' ); + } + } + + /** + * Skip this test on HHVM. + * + * @return bool Whether to skip this test. + */ + protected function shouldSkipTest() { + return defined( 'HHVM_VERSION' ); + } + /** * Returns the lines where errors should occur. * @@ -28,22 +55,22 @@ class WordPress_Tests_PHP_DisallowAlternativePHPTagsUnitTest extends AbstractSni * @return array */ public function getErrorList() { - $asp_enabled = (boolean) ini_get( 'asp_tags' ); - $short_enabled = (boolean) ini_get( 'short_open_tag' ); - $errors = array( - 6 => 1, + 8 => 1, + 11 => 1, + 12 => 1, + 15 => 1, ); - if ( true === $asp_enabled ) { + if ( true === $this->asp_tags ) { $errors[4] = 1; - } - if ( true === $asp_enabled && ( true === $short_enabled || defined( 'HHVM_VERSION' ) === true ) ) { $errors[5] = 1; + $errors[6] = 1; + $errors[7] = 1; } return $errors; - } // end getErrorList() + } /** * Returns the lines where warnings should occur. @@ -54,24 +81,18 @@ public function getErrorList() { * @return array */ public function getWarningList() { - $asp_enabled = (boolean) ini_get( 'asp_tags' ); - $short_enabled = (boolean) ini_get( 'short_open_tag' ); - $warnings = array(); - if ( false === $asp_enabled ) { + if ( false === $this->asp_tags ) { $warnings = array( 4 => 1, 5 => 1, - ); - } elseif ( false === $short_enabled && false === defined( 'HHVM_VERSION' ) ) { - $warnings = array( - 5 => 1, + 6 => 1, + 7 => 1, ); } return $warnings; + } - } // end getWarningList() - -} // end class +} // End class. diff --git a/myconfig.ini b/myconfig.ini new file mode 100644 index 0000000000..8c5f68f520 --- /dev/null +++ b/myconfig.ini @@ -0,0 +1,3 @@ +; Allow ASP-style <% %> tags. +; http://php.net/asp-tags +asp_tags = On From 3ad591e97851390ba9e4acd0526c1caf55ed66a1 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 14 Jul 2016 01:52:26 +0200 Subject: [PATCH 106/122] Add (new) sniff for class opening brace on same line to `core` ruleset. Checks that the opening brace of a class or interface is on the same line as the class declaration. Also checks that the brace is the last thing on that line and has precisely one space before it. --- WordPress-Core/ruleset.xml | 1 + .../Classes/OpeningBraceSameLineSniff.php | 137 ++++++++++++++++++ .../Classes/OpeningBraceSameLineUnitTest.inc | 51 +++++++ .../Classes/OpeningBraceSameLineUnitTest.php | 61 ++++++++ 4 files changed, 250 insertions(+) create mode 100644 WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php create mode 100644 WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc create mode 100644 WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index b4e973a70f..3f6d20b7f5 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -77,6 +77,7 @@ + diff --git a/WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php b/WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php new file mode 100644 index 0000000000..b984dad901 --- /dev/null +++ b/WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php @@ -0,0 +1,137 @@ + + */ +class WordPress_Sniffs_Classes_OpeningBraceSameLineSniff implements PHP_CodeSniffer_Sniff { + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() { + return array( + T_CLASS, + T_INTERFACE, + T_TRAIT, + ); + + } // end register() + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $scope_identifier = $phpcsFile->findNext( T_STRING, ( $stackPtr + 1 ) ); + $errorData = array( + strtolower( $tokens[ $stackPtr ]['content'] ) . ' ' . $tokens[ $scope_identifier ]['content'] + ); + + if ( ! isset( $tokens[ $stackPtr ]['scope_opener'] ) ) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $phpcsFile->addWarning( $error, $stackPtr, 'MissingBrace', $errorData ); + return; + } + + $openingBrace = $tokens[ $stackPtr ]['scope_opener']; + + /* + * Is the brace on the same line as the class/interface/trait declaration ? + */ + $classLine = $tokens[ $stackPtr ]['line']; + $braceLine = $tokens[ $openingBrace ]['line']; + $lineDifference = ( $braceLine - $classLine ); + + if ( $lineDifference > 0 ) { + $phpcsFile->recordMetric( $stackPtr, 'Class opening brace placement', 'new line' ); + $error = 'Opening brace should be on the same line as the declaration for %s'; + $fix = $phpcsFile->addFixableError( $error, $openingBrace, 'BraceOnNewLine', $errorData ); + if ( true === $fix ) { + $prev = $phpcsFile->findPrevious( T_STRING, ( $openingBrace - 1 ), $stackPtr ); + + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent( $prev, ' {' ); + $phpcsFile->fixer->replaceToken( $openingBrace, '' ); + $phpcsFile->fixer->endChangeset(); + + unset( $prev ); + } + } else { + $phpcsFile->recordMetric( $stackPtr, 'Class opening brace placement', 'same line' ); + } + + /* + * Is the opening brace the last thing on the line ? + */ + $next = $phpcsFile->findNext( T_WHITESPACE, ( $openingBrace + 1 ), null, true ); + if ( $tokens[ $next ]['line'] === $tokens[ $openingBrace ]['line'] ) { + if ( $next === $tokens[ $stackPtr ]['scope_closer'] ) { + // Ignore empty classes. + return; + } + + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError( $error, $openingBrace, 'ContentAfterBrace' ); + if ( true === $fix ) { + $phpcsFile->fixer->addNewline( $openingBrace ); + } + } + + // Only continue checking if the opening brace looks good. + if ( $lineDifference > 0 ) { + return; + } + + /* + * Is there precisely one space before the opening brace ? + */ + if ( T_WHITESPACE !== $tokens[ ( $openingBrace - 1 ) ]['code'] ) { + $length = 0; + } elseif ( "\t" === $tokens[ ( $openingBrace - 1 ) ]['content'] ) { + $length = '\t'; + } else { + $length = strlen( $tokens[ ( $openingBrace - 1 ) ]['content'] ); + } + + if ( 1 !== $length ) { + $error = 'Expected 1 space before opening brace; found %s'; + $data = array( $length ); + $fix = $phpcsFile->addFixableError( $error, $openingBrace, 'SpaceBeforeBrace', $data ); + if ( true === $fix ) { + if ( 0 === $length || '\t' === $length ) { + $phpcsFile->fixer->addContentBefore( $openingBrace, ' ' ); + } else { + $phpcsFile->fixer->replaceToken( ( $openingBrace - 1 ), ' ' ); + } + } + } + + } // end process() + +} // end class diff --git a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc b/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc new file mode 100644 index 0000000000..079bc4131f --- /dev/null +++ b/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc @@ -0,0 +1,51 @@ + + */ +class WordPress_Tests_Classes_OpeningBraceSameLineUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() { + + return array( + 19 => 2, + 23 => 1, + 28 => 2, + 34 => 1, + 34 => 1, + 38 => 1, + 41 => 1, + 44 => 1, + 47 => 1, + ); + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() { + return array( + 51 => 1, + ); + + } // end getWarningList() + +} // end class From fd1f14eadf045a1cc9c0438a0f6e7c52e8ef1f43 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 15 Jul 2016 03:20:48 +0200 Subject: [PATCH 107/122] Add "fixed" file for this sniff. And fix one minor spacing issue picked up by this new rule ;-) --- .../OpeningBraceSameLineUnitTest.inc.fixed | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed diff --git a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed b/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed new file mode 100644 index 0000000000..eae729d08f --- /dev/null +++ b/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed @@ -0,0 +1,51 @@ + Date: Fri, 15 Jul 2016 07:46:26 +0200 Subject: [PATCH 108/122] Give the class opener sniff a more meaningful name. --- WordPress-Core/ruleset.xml | 2 +- ...gBraceSameLineSniff.php => ClassOpeningStatementSniff.php} | 4 ++-- ...SameLineUnitTest.inc => ClassOpeningStatementUnitTest.inc} | 0 ...Test.inc.fixed => ClassOpeningStatementUnitTest.inc.fixed} | 0 ...SameLineUnitTest.php => ClassOpeningStatementUnitTest.php} | 4 ++-- 5 files changed, 5 insertions(+), 5 deletions(-) rename WordPress/Sniffs/Classes/{OpeningBraceSameLineSniff.php => ClassOpeningStatementSniff.php} (96%) rename WordPress/Tests/Classes/{OpeningBraceSameLineUnitTest.inc => ClassOpeningStatementUnitTest.inc} (100%) rename WordPress/Tests/Classes/{OpeningBraceSameLineUnitTest.inc.fixed => ClassOpeningStatementUnitTest.inc.fixed} (100%) rename WordPress/Tests/Classes/{OpeningBraceSameLineUnitTest.php => ClassOpeningStatementUnitTest.php} (89%) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 3f6d20b7f5..f55c1bff57 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -77,7 +77,7 @@ - + diff --git a/WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php similarity index 96% rename from WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php rename to WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php index b984dad901..bc1e8ec7c7 100644 --- a/WordPress/Sniffs/Classes/OpeningBraceSameLineSniff.php +++ b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php @@ -8,7 +8,7 @@ */ /** - * WordPress_Classes_OpeningBraceSameLineSniff. + * WordPress_Classes_ClassOpeningStatementSniff. * * Checks that the opening brace of a class or interface is on the same line * as the class declaration. @@ -21,7 +21,7 @@ * @package PHP_CodeSniffer * @author Juliette Reinders Folmer */ -class WordPress_Sniffs_Classes_OpeningBraceSameLineSniff implements PHP_CodeSniffer_Sniff { +class WordPress_Sniffs_Classes_ClassOpeningStatementSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. diff --git a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc similarity index 100% rename from WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc rename to WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc diff --git a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed similarity index 100% rename from WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.inc.fixed rename to WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed diff --git a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.php b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php similarity index 89% rename from WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.php rename to WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php index 7a8763f3f5..3adab51df2 100644 --- a/WordPress/Tests/Classes/OpeningBraceSameLineUnitTest.php +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php @@ -8,7 +8,7 @@ */ /** - * Unit test class for the OpeningBraceSameLine sniff. + * Unit test class for the ClassOpeningStatement sniff. * * A sniff unit test checks a .inc file for expected violations of a single * coding standard. Expected errors and warnings are stored in this class. @@ -17,7 +17,7 @@ * @package PHP_CodeSniffer * @author Juliette Reinders Folmer */ -class WordPress_Tests_Classes_OpeningBraceSameLineUnitTest extends AbstractSniffUnitTest { +class WordPress_Tests_Classes_ClassOpeningStatementUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. From 4ba0cd23e87cbbaadbdcebfaf96df65b51276344 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 15 Jul 2016 08:17:29 +0200 Subject: [PATCH 109/122] Whitespace can be a pain to commit. --- .../Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed index eae729d08f..45b85aa4bf 100644 --- a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed @@ -16,11 +16,11 @@ class Test_Class_Ok_C implements Test_Interface_Ok_A { // These are all incorrect. interface Test_Interface_Bad_A { -// There should be no content after the brace. + // There should be no content after the brace. } class Test_Class_Bad_A { - + } class Test_Class_Bad_B extends Test_Class_Bad_A { @@ -38,7 +38,7 @@ class Test_Class_Bad_C implements Test_Interface_Bad_A { interface Test_Interface_Bad_C { } -class Test_Class_Bad_G { +class Test_Class_Bad_G { } class Test_Class_Bad_H extends Test_Class_Bad_G { From c9aa2eb930ebe38d09196f047523982263a71d1d Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 26 Jul 2016 01:23:29 +0200 Subject: [PATCH 110/122] Allow for multi-line class declarations. --- .../Classes/ClassOpeningStatementSniff.php | 13 ++++---- .../Classes/ClassOpeningStatementUnitTest.inc | 30 +++++++++++++++++++ .../ClassOpeningStatementUnitTest.inc.fixed | 30 +++++++++++++++++++ .../Classes/ClassOpeningStatementUnitTest.php | 2 ++ 4 files changed, 67 insertions(+), 8 deletions(-) diff --git a/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php index bc1e8ec7c7..23d432836b 100644 --- a/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php +++ b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php @@ -64,23 +64,20 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { /* * Is the brace on the same line as the class/interface/trait declaration ? */ - $classLine = $tokens[ $stackPtr ]['line']; - $braceLine = $tokens[ $openingBrace ]['line']; - $lineDifference = ( $braceLine - $classLine ); + $lastClassLineToken = $phpcsFile->findPrevious( T_STRING, ( $openingBrace - 1 ), $stackPtr ); + $lastClassLine = $tokens[ $lastClassLineToken ]['line']; + $braceLine = $tokens[ $openingBrace ]['line']; + $lineDifference = ( $braceLine - $lastClassLine ); if ( $lineDifference > 0 ) { $phpcsFile->recordMetric( $stackPtr, 'Class opening brace placement', 'new line' ); $error = 'Opening brace should be on the same line as the declaration for %s'; $fix = $phpcsFile->addFixableError( $error, $openingBrace, 'BraceOnNewLine', $errorData ); if ( true === $fix ) { - $prev = $phpcsFile->findPrevious( T_STRING, ( $openingBrace - 1 ), $stackPtr ); - $phpcsFile->fixer->beginChangeset(); - $phpcsFile->fixer->addContent( $prev, ' {' ); + $phpcsFile->fixer->addContent( $lastClassLineToken, ' {' ); $phpcsFile->fixer->replaceToken( $openingBrace, '' ); $phpcsFile->fixer->endChangeset(); - - unset( $prev ); } } else { $phpcsFile->recordMetric( $stackPtr, 'Class opening brace placement', 'same line' ); diff --git a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc index 079bc4131f..1356e5b146 100644 --- a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc @@ -49,3 +49,33 @@ class Test_Class_Bad_I implements Test_Interface_Bad_C{ // This one should be flagged as a potential parse error. class Test_Class_Bad_H + +// This is OK. +class A_Class_With_Really_Long_Name + extends Another_Class_With_A_Really_Long_Name { + +} + +// This is OK too. +class A_Class_With_Really_Long_Name_2 + extends Another_Class_With_A_Really_Long_Name + implements Some_Interface_With_A_Long_Name, + Another_Interface_With_A_Long_Name { + +} + +// But this is not. +class A_Class_With_Really_Long_Name_3 + extends Another_Class_With_A_Really_Long_Name + { + +} + +// Nor is this. +class A_Class_With_Really_Long_Name_4 + extends Another_Class_With_A_Really_Long_Name + implements Some_Interface_With_A_Long_Name, + Another_Interface_With_A_Long_Name +{ + +} diff --git a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed index 45b85aa4bf..2b4358f0ee 100644 --- a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.inc.fixed @@ -49,3 +49,33 @@ class Test_Class_Bad_I implements Test_Interface_Bad_C { // This one should be flagged as a potential parse error. class Test_Class_Bad_H + +// This is OK. +class A_Class_With_Really_Long_Name + extends Another_Class_With_A_Really_Long_Name { + +} + +// This is OK too. +class A_Class_With_Really_Long_Name_2 + extends Another_Class_With_A_Really_Long_Name + implements Some_Interface_With_A_Long_Name, + Another_Interface_With_A_Long_Name { + +} + +// But this is not. +class A_Class_With_Really_Long_Name_3 + extends Another_Class_With_A_Really_Long_Name { + + +} + +// Nor is this. +class A_Class_With_Really_Long_Name_4 + extends Another_Class_With_A_Really_Long_Name + implements Some_Interface_With_A_Long_Name, + Another_Interface_With_A_Long_Name { + + +} diff --git a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php index 3adab51df2..7bbbd9ebf5 100644 --- a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php @@ -39,6 +39,8 @@ public function getErrorList() { 41 => 1, 44 => 1, 47 => 1, + 70 => 1, + 79 => 1, ); } // end getErrorList() From 674c3e94157a302f2c2caacf1d45badfc186b3e4 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 26 Jul 2016 04:08:09 +0200 Subject: [PATCH 111/122] Prevent WPCS throwing an "undefined offset" notice during live code review. Fixes #628 --- WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index 1e901f460f..19f0b72ce2 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -100,7 +100,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); - if ( T_WHITESPACE !== $tokens[ ( $stackPtr + 1) ]['code'] + if ( isset( $tokens[ ( $stackPtr + 1 ) ] ) && T_WHITESPACE !== $tokens[ ( $stackPtr + 1 ) ]['code'] && ! ( T_ELSE === $tokens[ $stackPtr ]['code'] && T_COLON === $tokens[ ( $stackPtr + 1 ) ]['code'] ) && ! ( T_CLOSURE === $tokens[ $stackPtr ]['code'] From 7721698ac99e3dfe2f6317d7074d4af5895977aa Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 18 Jul 2016 00:49:24 +0200 Subject: [PATCH 112/122] Split off POSIX Functions restrictions to its own sniff. * Removes similar checks from existing sniffs (PHP.DiscouragedFunctions and VIP.RestrictedFunctions). * Makes sure that *all* functions in the POSIX extension are covered by this check - they previously were not. * Add unit tests for the new sniff covering *all* POSIX functions. --- WordPress-Core/ruleset.xml | 3 +- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 7 -- WordPress/Sniffs/PHP/POSIXFunctionsSniff.php | 69 +++++++++++++++++++ .../Sniffs/VIP/RestrictedFunctionsSniff.php | 32 --------- .../PHP/DiscouragedFunctionsUnitTest.inc | 18 ----- .../PHP/DiscouragedFunctionsUnitTest.php | 19 ++--- .../Tests/PHP/POSIXFunctionsUnitTest.inc | 26 +++++++ .../Tests/PHP/POSIXFunctionsUnitTest.php | 61 ++++++++++++++++ 8 files changed, 165 insertions(+), 70 deletions(-) create mode 100644 WordPress/Sniffs/PHP/POSIXFunctionsSniff.php create mode 100644 WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc create mode 100644 WordPress/Tests/PHP/POSIXFunctionsUnitTest.php diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index b4e973a70f..d80ddefa2f 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -116,7 +116,8 @@ - + + diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index 806247a124..34068bd57e 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -31,13 +31,6 @@ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ * @var array(string => string|null) */ public $forbiddenFunctions = array( - // Deprecated. - 'ereg_replace' => 'preg_replace', - 'ereg' => null, - 'eregi_replace' => 'preg_replace', - 'split' => null, - 'spliti' => null, - // Development. 'print_r' => null, 'debug_print_backtrace' => null, diff --git a/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php b/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php new file mode 100644 index 0000000000..2ab56a9a99 --- /dev/null +++ b/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php @@ -0,0 +1,69 @@ + + */ +class WordPress_Sniffs_PHP_POSIXFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { + + /** + * Groups of functions to restrict. + * + * Example: groups => array( + * 'lambda' => array( + * 'type' => 'error' | 'warning', + * 'message' => 'Use anonymous functions instead please!', + * 'functions' => array( 'eval', 'create_function' ), + * ) + * ) + * + * @return array + */ + public function getGroups() { + return array( + 'ereg' => array( + 'type' => 'error', + 'message' => '%s has been deprecated since PHP 5.3 and removed in PHP 7.0, please use preg_match() instead.', + 'functions' => array( + 'ereg', + 'eregi', + 'sql_regcase', + ), + ), + + 'ereg_replace' => array( + 'type' => 'error', + 'message' => '%s has been deprecated since PHP 5.3 and removed in PHP 7.0, please use preg_replace() instead.', + 'functions' => array( + 'ereg_replace', + 'eregi_replace', + ), + ), + + 'split' => array( + 'type' => 'error', + 'message' => '%s has been deprecated since PHP 5.3 and removed in PHP 7.0, please use explode(), str_split() or preg_split() instead.', + 'functions' => array( + 'split', + 'spliti', + ), + ), + + ); + } // end getGroups() + +} // end class diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 72111b816a..50ccb710ec 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -285,38 +285,6 @@ public function getGroups() { ), ), - 'ereg' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_match() instead. See http://php.net/manual/en/function.ereg.php', - 'functions' => array( - 'ereg', - ), - ), - - 'eregi' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_match() with i modifier instead. See http://php.net/manual/en/function.eregi.php', - 'functions' => array( - 'eregi', - ), - ), - - 'ereg_replace' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use preg_replace() instead. See http://php.net/manual/en/function.ereg-replace.php', - 'functions' => array( - 'ereg_replace', - ), - ), - - 'split' => array( - 'type' => 'error', - 'message' => '%s is prohibited, please use explode() or preg_split() instead. See http://php.net/manual/en/function.split.php', - 'functions' => array( - 'split', - ), - ), - 'runtime_configuration' => array( 'type' => 'error', 'message' => '%s is prohibited, changing configuration at runtime is not allowed on VIP Production.', diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc index 2852bfcd72..0c1733e3b7 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc @@ -9,24 +9,6 @@ var_dump( $post_id ); // Bad, forbidden use print_r( $post_ID ); // Bad, forbidden use -// DEPRECATED PHP FUNCTIONS -// ------------------------ - -$title = get_the_title(); - -$title = ereg_replace( 'cool', 'not cool', get_the_title() ); // Bad, ereg_replace has been deprecated. Use preg_replace instead. -$title = preg_replace( 'cool', 'not cool', get_the_title() ); // Good - -if ( ereg( '[A-Za-z]+', $title, $regs ) ) // Bad, ereg also deprecated. Use preg_match instead. - die( $regs ); - -$title = eregi_replace( 'cool', 'not cool', get_the_title() ); // Bad, eregi_replace also deprecated. Use preg_replace instead. - -list( $year, $month, $day ) = split( ':', $date ); // Bad, split has been deprecated. Use preg_split or explode instead. - -$title_parts = spliti( ' ', get_the_title(), 4 ); // Bad, spliti also deprecated. Use preg_split instead. - - // DEPRECATED WORDPRESS FUNCTIONS // ------------------------------ diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php index 4ef3e1e383..e59a7cc11e 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.php @@ -49,28 +49,23 @@ public function getWarningList() { return array( 8 => 1, 9 => 1, + 15 => 1, 17 => 1, - 20 => 1, + 19 => 1, + 21 => 1, 23 => 1, 25 => 1, 27 => 1, + 29 => 1, + 31 => 1, 33 => 1, 35 => 1, 37 => 1, 39 => 1, - 41 => 1, - 43 => 1, 45 => 1, 47 => 1, - 49 => 1, - 51 => 1, - 53 => 1, - 55 => 1, - 57 => 1, - 63 => 1, - 65 => 1, - 70 => 1, - 72 => 1, + 52 => 1, + 54 => 1, ); } // end getWarningList() diff --git a/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc b/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc new file mode 100644 index 0000000000..bad1dd5372 --- /dev/null +++ b/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc @@ -0,0 +1,26 @@ + + * @author Greg Sherwood + * @author Marc McIntyre + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: @package_version@ + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class WordPress_Tests_PHP_POSIXFunctionsUnitTest extends AbstractSniffUnitTest { + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array(int => int) + */ + public function getErrorList() { + return array( + 13 => 1, + 16 => 1, + 18 => 1, + 20 => 1, + 22 => 1, + 24 => 1, + 26 => 1, + ); + + } // end getErrorList() + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array(int => int) + */ + public function getWarningList() { + return array(); + + } // end getWarningList() + +} // end class From 358bc2b1311fbdbf1fc77edeb4db410cb7d3ff7d Mon Sep 17 00:00:00 2001 From: "J.D. Grimes" Date: Wed, 27 Jul 2016 08:56:54 -0400 Subject: [PATCH 113/122] Remove extra tab --- WordPress-Core/ruleset.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index d80ddefa2f..2835d85cb4 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -118,6 +118,6 @@ - + From f4b798ed21005e32067fba8e73b8ec96117435b4 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 28 Jul 2016 20:10:03 +0200 Subject: [PATCH 114/122] Order the `core` ruleset according to the handbook. This PR does not add or remove any new rules, it just re-orders the core ruleset to follow the handbook and documents the rules as they are in the handbook - both covered and not covered. Closes #602 For any core rules which are not yet covered, but *could* possibly *be* covered, a new issue has been opened if one didn't exist already and the link to the issue is included in the ruleset. Rules included, but not (explicitly) covered in the handbook are listed in their own section at the bottom of the ruleset. I've made three changes which should be noted: * Removed the `WordPress.WP.I18n` sniff from the `extra` ruleset as it is included in the `core` ruleset and `core` is included in `extra`. * Moved the `WordPress.WP.PreparedSQL` sniff from `extra` to `core` as the checks included in that sniff are actually part of the core rules. * Moved the `Generic.PHP.Syntax` to `extra` as IRL often enough there will be code which will only be loaded for higher PHP versions with a wrapper and fall-backs for lower PHP versions. Feedback welcome. Review is probably easiest by just looking at the new version of the file as the diff will be horrible ;-) --- WordPress-Core/ruleset.xml | 407 +++++++++++++++++++++++++----------- WordPress-Extra/ruleset.xml | 10 +- 2 files changed, 295 insertions(+), 122 deletions(-) diff --git a/WordPress-Core/ruleset.xml b/WordPress-Core/ruleset.xml index 47b56b68de..ae39cc8960 100644 --- a/WordPress-Core/ruleset.xml +++ b/WordPress-Core/ruleset.xml @@ -2,123 +2,294 @@ Non-controversial generally-agreed upon WordPress Coding Standards - - - - - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WordPress-Extra/ruleset.xml b/WordPress-Extra/ruleset.xml index f7853ab8c2..b4f6cf0f27 100644 --- a/WordPress-Extra/ruleset.xml +++ b/WordPress-Extra/ruleset.xml @@ -15,11 +15,11 @@ - + - + @@ -30,11 +30,13 @@ - - + + + + From de73645c9003e5be8f9f9cb79e62f1c7d69c4abc Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 19 Jul 2016 08:40:37 +0200 Subject: [PATCH 115/122] Consistent class exists check for extended classes. Ensure that any sniff with a dependency on an external sniff has a consistent `class_exists()` check and throws an appropriate error message. --- WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php | 4 ++++ WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php | 4 ++++ WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php | 2 +- WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php | 2 +- WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php | 4 ++++ WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php | 4 ++++ WordPress/Sniffs/VIP/SessionVariableUsageSniff.php | 4 ++++ WordPress/Sniffs/VIP/TimezoneChangeSniff.php | 4 ++++ 8 files changed, 26 insertions(+), 2 deletions(-) diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php index b2d20de751..49c4675033 100644 --- a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -9,6 +9,10 @@ * @author Marc McIntyre */ +if ( ! class_exists( 'Squiz_Sniffs_Arrays_ArrayDeclarationSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Squiz_Sniffs_Arrays_ArrayDeclarationSniff not found' ); +} + /** * Enforces WordPress array format. * diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index 055afe5645..ee98295cab 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -7,6 +7,10 @@ * @author John Godley */ +if ( ! class_exists( 'PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff not found' ); +} + /** * Enforces WordPress function name and method name format, based upon Squiz code. * diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index b94db17279..655fbd8bee 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -15,7 +15,7 @@ * @link http://pear.php.net/package/PHP_CodeSniffer */ -if ( class_exists( 'PHP_CodeSniffer_Standards_AbstractVariableSniff', true ) === false ) { +if ( ! class_exists( 'PHP_CodeSniffer_Standards_AbstractVariableSniff', true ) ) { throw new PHP_CodeSniffer_Exception( 'Class PHP_CodeSniffer_Standards_AbstractVariableSniff not found' ); } diff --git a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php index 34068bd57e..d92e371ebd 100644 --- a/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -7,7 +7,7 @@ * @author John Godley */ -if ( false === class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { +if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); } diff --git a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php index 3e9897e4ff..ba53a7429d 100644 --- a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php +++ b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php @@ -7,6 +7,10 @@ * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ +if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); +} + /** * Disallow Filesystem writes. * diff --git a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php index b231e4f8ec..7901677144 100644 --- a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php @@ -7,6 +7,10 @@ * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ +if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); +} + /** * WordPress_Sniffs_VIP_SessionFunctionsUsageSniff. * diff --git a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php index 6b2c73b338..bc04c77462 100644 --- a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php @@ -7,6 +7,10 @@ * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ +if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); +} + /** * WordPress_Sniffs_VIP_SessionVariableUsageSniff * diff --git a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php index 58dcafe6f8..6e650b52ca 100644 --- a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php +++ b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php @@ -7,6 +7,10 @@ * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ +if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { + throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); +} + /** * WordPress_Sniffs_VIP_TimezoneChangeSniff. * From 8760c44cdddc3fb9a5faa26cd42f89c655384bb0 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 29 Jul 2016 07:57:45 +0200 Subject: [PATCH 116/122] Verify the extended classes Verified that classes which extend a parent actually *use* that parent and if not, removed the `extend`. If they use the parent, leverage the properties available in the parent and remove duplicate function calls. --- WordPress/Sniff.php | 9 +- .../Sniffs/CSRF/NonceVerificationSniff.php | 3 +- .../Sniffs/PHP/StrictComparisonsSniff.php | 3 +- WordPress/Sniffs/PHP/StrictInArraySniff.php | 2 +- .../Sniffs/VIP/SessionVariableUsageSniff.php | 6 +- .../Sniffs/VIP/SuperGlobalInputUsageSniff.php | 5 +- .../VIP/ValidatedSanitizedInputSniff.php | 21 ++- .../Sniffs/Variables/GlobalVariablesSniff.php | 19 ++- WordPress/Sniffs/WP/PreparedSQLSniff.php | 28 ++-- .../ControlStructureSpacingSniff.php | 120 +++++++++--------- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 53 ++++---- 11 files changed, 131 insertions(+), 138 deletions(-) diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index 4361863cf7..ee010cd4f8 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -465,7 +465,14 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { * * @var string[] */ - protected static $input_superglobals = array( '$_COOKIE', '$_GET', '$_FILES', '$_POST', '$_REQUEST', '$_SERVER' ); + protected static $input_superglobals = array( + '$_COOKIE', + '$_GET', + '$_FILES', + '$_POST', + '$_REQUEST', + '$_SERVER', + ); /** * Initialize the class for the current process. diff --git a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php index 84629da527..7bc92b3a3b 100644 --- a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php +++ b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php @@ -94,8 +94,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); - $instance = $tokens[ $stackPtr ]; + $instance = $this->tokens[ $stackPtr ]; $superglobals = array_merge( $this->errorForSuperGlobals diff --git a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php index 8a7f94af98..1f42761541 100644 --- a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php +++ b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php @@ -42,8 +42,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); if ( ! $this->has_whitelist_comment( 'loose comparison', $stackPtr ) ) { - $tokens = $phpcsFile->getTokens(); - $error = 'Found: ' . $tokens[ $stackPtr ]['content'] . '. Use strict comparisons (=== or !==).'; + $error = 'Found: ' . $this->tokens[ $stackPtr ]['content'] . '. Use strict comparisons (=== or !==).'; $phpcsFile->addWarning( $error, $stackPtr, 'LooseComparison' ); } diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index 019e8e4a11..bda11b7932 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -15,7 +15,7 @@ * @category PHP * @package PHP_CodeSniffer */ -class WordPress_Sniffs_PHP_StrictInArraySniff extends WordPress_Sniff { +class WordPress_Sniffs_PHP_StrictInArraySniff implements PHP_CodeSniffer_Sniff { /** * List of array functions to which a $strict parameter can be passed. diff --git a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php index bc04c77462..30e968d2b8 100644 --- a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php @@ -7,10 +7,6 @@ * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ */ -if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { - throw new PHP_CodeSniffer_Exception( 'Class Generic_Sniffs_PHP_ForbiddenFunctionsSniff not found' ); -} - /** * WordPress_Sniffs_VIP_SessionVariableUsageSniff * @@ -23,7 +19,7 @@ * @package PHP_CodeSniffer * @author Shady Sharaf */ -class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { +class WordPress_Sniffs_VIP_SessionVariableUsageSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. diff --git a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php index 886cd5600e..d7b8c76798 100644 --- a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php +++ b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php @@ -41,14 +41,13 @@ public function register() { */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); // Check for global input variable. - if ( ! in_array( $tokens[ $stackPtr ]['content'], WordPress_Sniff::$input_superglobals, true ) ) { + if ( ! in_array( $this->tokens[ $stackPtr ]['content'], self::$input_superglobals, true ) ) { return; } - $varName = $tokens[ $stackPtr ]['content']; + $varName = $this->tokens[ $stackPtr ]['content']; // If we're overriding a superglobal with an assignment, no need to test. if ( $this->is_assignment( $stackPtr ) ) { diff --git a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php index 8f89c997d6..bc62c72459 100644 --- a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php +++ b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php @@ -78,13 +78,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Merge any custom functions with the defaults, if we haven't already. if ( ! self::$addedCustomFunctions ) { - WordPress_Sniff::$sanitizingFunctions = array_merge( - WordPress_Sniff::$sanitizingFunctions, + self::$sanitizingFunctions = array_merge( + self::$sanitizingFunctions, array_flip( $this->customSanitizingFunctions ) ); - WordPress_Sniff::$unslashingSanitizingFunctions = array_merge( - WordPress_Sniff::$unslashingSanitizingFunctions, + self::$unslashingSanitizingFunctions = array_merge( + self::$unslashingSanitizingFunctions, array_flip( $this->customUnslashingSanitizingFunctions ) ); @@ -92,24 +92,23 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } $this->init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); - $superglobals = WordPress_Sniff::$input_superglobals; + $superglobals = self::$input_superglobals; // Handling string interpolation. - if ( T_DOUBLE_QUOTED_STRING === $tokens[ $stackPtr ]['code'] ) { + if ( T_DOUBLE_QUOTED_STRING === $this->tokens[ $stackPtr ]['code'] ) { $interpolated_variables = array_map( create_function( '$symbol', 'return "$" . $symbol;' ), // Replace with closure when 5.3 is minimum requirement for PHPCS. - $this->get_interpolated_variables( $tokens[ $stackPtr ]['content'] ) + $this->get_interpolated_variables( $this->tokens[ $stackPtr ]['content'] ) ); foreach ( array_intersect( $interpolated_variables, $superglobals ) as $bad_variable ) { - $phpcsFile->addError( 'Detected usage of a non-sanitized, non-validated input variable %s: %s', $stackPtr, 'InputNotValidatedNotSanitized', array( $bad_variable, $tokens[ $stackPtr ]['content'] ) ); + $phpcsFile->addError( 'Detected usage of a non-sanitized, non-validated input variable %s: %s', $stackPtr, 'InputNotValidatedNotSanitized', array( $bad_variable, $this->tokens[ $stackPtr ]['content'] ) ); } return; } // Check if this is a superglobal. - if ( ! in_array( $tokens[ $stackPtr ]['content'], $superglobals, true ) ) { + if ( ! in_array( $this->tokens[ $stackPtr ]['content'], $superglobals, true ) ) { return; } @@ -129,7 +128,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } - $error_data = array( $tokens[ $stackPtr ]['content'] ); + $error_data = array( $this->tokens[ $stackPtr ]['content'] ); // Check for validation first. if ( ! $this->is_validated( $stackPtr, $array_key, $this->check_validation_in_scope_only ) ) { diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index 8d03d6889c..16f8a51e2a 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -282,28 +282,27 @@ public function register() { */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; + $token = $this->tokens[ $stackPtr ]; $search = array(); // Array of globals to watch for. if ( T_VARIABLE === $token['code'] && '$GLOBALS' === $token['content'] ) { $bracketPtr = $phpcsFile->findNext( array( T_WHITESPACE ), ( $stackPtr + 1 ), null, true ); - if ( T_OPEN_SQUARE_BRACKET !== $tokens[ $bracketPtr ]['code'] ) { + if ( T_OPEN_SQUARE_BRACKET !== $this->tokens[ $bracketPtr ]['code'] ) { return; } - $varPtr = $phpcsFile->findNext( T_WHITESPACE, ( $bracketPtr + 1 ), $tokens[ $bracketPtr ]['bracket_closer'], true ); - $varToken = $tokens[ $varPtr ]; + $varPtr = $phpcsFile->findNext( T_WHITESPACE, ( $bracketPtr + 1 ), $this->tokens[ $bracketPtr ]['bracket_closer'], true ); + $varToken = $this->tokens[ $varPtr ]; if ( ! in_array( trim( $varToken['content'], '\'"' ), $this->globals, true ) ) { return; } - $assignment = $phpcsFile->findNext( T_WHITESPACE, ( $tokens[ $bracketPtr ]['bracket_closer'] + 1 ), null, true ); + $assignment = $phpcsFile->findNext( T_WHITESPACE, ( $this->tokens[ $bracketPtr ]['bracket_closer'] + 1 ), null, true ); - if ( $assignment && T_EQUAL === $tokens[ $assignment ]['code'] ) { + if ( $assignment && T_EQUAL === $this->tokens[ $assignment ]['code'] ) { if ( ! $this->has_whitelist_comment( 'override', $assignment ) ) { $phpcsFile->addError( 'Overriding WordPress globals is prohibited', $stackPtr, 'OverrideProhibited' ); return; @@ -316,7 +315,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $ptr = ( $stackPtr + 1 ); while ( $ptr ) { $ptr++; - $var = $tokens[ $ptr ]; + $var = $this->tokens[ $ptr ]; if ( T_VARIABLE === $var['code'] ) { $varname = substr( $var['content'], 1 ); if ( in_array( $varname, $this->globals, true ) ) { @@ -333,10 +332,10 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Check for assignments to collected global vars. - foreach ( $tokens as $ptr => $token ) { + foreach ( $this->tokens as $ptr => $token ) { if ( T_VARIABLE === $token['code'] && in_array( substr( $token['content'], 1 ), $search, true ) ) { $next = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $ptr + 1 ), null, true, null, true ); - if ( T_EQUAL === $tokens[ $next ]['code'] ) { + if ( T_EQUAL === $this->tokens[ $next ]['code'] ) { if ( ! $this->has_whitelist_comment( 'override', $next ) ) { $phpcsFile->addError( 'Overriding WordPress globals is prohibited', $ptr, 'OverrideProhibited' ); } diff --git a/WordPress/Sniffs/WP/PreparedSQLSniff.php b/WordPress/Sniffs/WP/PreparedSQLSniff.php index f9d8455595..1bfcf9793a 100644 --- a/WordPress/Sniffs/WP/PreparedSQLSniff.php +++ b/WordPress/Sniffs/WP/PreparedSQLSniff.php @@ -101,15 +101,13 @@ public function register() { */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { - $tokens = $phpcsFile->getTokens(); + $this->init( $phpcsFile ); // Check for $wpdb variable. - if ( '$wpdb' !== $tokens[ $stackPtr ]['content'] ) { + if ( '$wpdb' !== $this->tokens[ $stackPtr ]['content'] ) { return; } - $this->init( $phpcsFile ); - if ( ! $this->is_wpdb_method_call( $stackPtr ) ) { return; } @@ -120,14 +118,14 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { for ( $this->i; $this->i < $this->end; $this->i++ ) { - if ( isset( $this->ignored_tokens[ $tokens[ $this->i ]['code'] ] ) ) { + if ( isset( $this->ignored_tokens[ $this->tokens[ $this->i ]['code'] ] ) ) { continue; } - if ( T_DOUBLE_QUOTED_STRING === $tokens[ $this->i ]['code'] ) { + if ( T_DOUBLE_QUOTED_STRING === $this->tokens[ $this->i ]['code'] ) { $bad_variables = array_filter( - $this->get_interpolated_variables( $tokens[ $this->i ]['content'] ), + $this->get_interpolated_variables( $this->tokens[ $this->i ]['content'] ), create_function( '$symbol', 'return ! in_array( $symbol, array( "wpdb" ), true );' ) // Replace this with closure once 5.3 is minimum requirement. ); @@ -138,25 +136,25 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { 'NotPrepared', array( $bad_variable, - $tokens[ $this->i ]['content'], + $this->tokens[ $this->i ]['content'], ) ); } continue; } - if ( T_VARIABLE === $tokens[ $this->i ]['code'] ) { - if ( '$wpdb' === $tokens[ $this->i ]['content'] ) { + if ( T_VARIABLE === $this->tokens[ $this->i ]['code'] ) { + if ( '$wpdb' === $this->tokens[ $this->i ]['content'] ) { $this->is_wpdb_method_call( $this->i ); continue; } } - if ( T_STRING === $tokens[ $this->i ]['code'] ) { + if ( T_STRING === $this->tokens[ $this->i ]['code'] ) { if ( - isset( self::$SQLEscapingFunctions[ $tokens[ $this->i ]['content'] ] ) - || isset( self::$SQLAutoEscapedFunctions[ $tokens[ $this->i ]['content'] ] ) + isset( self::$SQLEscapingFunctions[ $this->tokens[ $this->i ]['content'] ] ) + || isset( self::$SQLAutoEscapedFunctions[ $this->tokens[ $this->i ]['content'] ] ) ) { // Find the opening parenthesis. @@ -171,7 +169,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->i = $this->tokens[ $opening_paren ]['parenthesis_closer']; continue; } - } elseif ( isset( self::$formattingFunctions[ $tokens[ $this->i ]['content'] ] ) ) { + } elseif ( isset( self::$formattingFunctions[ $this->tokens[ $this->i ]['content'] ] ) ) { continue; } } @@ -180,7 +178,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { 'Use placeholders and $wpdb->prepare(); found %s', $this->i, 'NotPrepared', - array( $tokens[ $this->i ]['content'] ) + array( $this->tokens[ $this->i ]['content'] ) ); } diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index 19f0b72ce2..078c30a380 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -96,14 +96,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $this->blank_line_check = (bool) $this->blank_line_check; $this->blank_line_after_check = (bool) $this->blank_line_after_check; - $tokens = $phpcsFile->getTokens(); - $this->init( $phpcsFile ); - if ( isset( $tokens[ ( $stackPtr + 1 ) ] ) && T_WHITESPACE !== $tokens[ ( $stackPtr + 1 ) ]['code'] - && ! ( T_ELSE === $tokens[ $stackPtr ]['code'] && T_COLON === $tokens[ ( $stackPtr + 1 ) ]['code'] ) + if ( isset( $this->tokens[ ( $stackPtr + 1 ) ] ) && T_WHITESPACE !== $this->tokens[ ( $stackPtr + 1 ) ]['code'] + && ! ( T_ELSE === $this->tokens[ $stackPtr ]['code'] && T_COLON === $this->tokens[ ( $stackPtr + 1 ) ]['code'] ) && ! ( - T_CLOSURE === $tokens[ $stackPtr ]['code'] + T_CLOSURE === $this->tokens[ $stackPtr ]['code'] && ( 0 === (int) $this->spaces_before_closure_open_paren || -1 === (int) $this->spaces_before_closure_open_paren @@ -123,25 +121,25 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - if ( ! isset( $tokens[ $stackPtr ]['scope_closer'] ) ) { + if ( ! isset( $this->tokens[ $stackPtr ]['scope_closer'] ) ) { - if ( T_USE === $tokens[ $stackPtr ]['code'] && 'closure' === $this->get_use_type( $stackPtr ) ) { + if ( T_USE === $this->tokens[ $stackPtr ]['code'] && 'closure' === $this->get_use_type( $stackPtr ) ) { $scopeOpener = $phpcsFile->findNext( T_OPEN_CURLY_BRACKET, ( $stackPtr + 1 ) ); - $scopeCloser = $tokens[ $scopeOpener ]['scope_closer']; + $scopeCloser = $this->tokens[ $scopeOpener ]['scope_closer']; } else { return; } } else { - $scopeOpener = $tokens[ $stackPtr ]['scope_opener']; - $scopeCloser = $tokens[ $stackPtr ]['scope_closer']; + $scopeOpener = $this->tokens[ $stackPtr ]['scope_opener']; + $scopeCloser = $this->tokens[ $stackPtr ]['scope_closer']; } // Alternative syntax. - if ( T_COLON === $tokens[ $scopeOpener ]['code'] ) { + if ( T_COLON === $this->tokens[ $scopeOpener ]['code'] ) { if ( 'required' === $this->space_before_colon ) { - if ( T_WHITESPACE !== $tokens[ ( $scopeOpener - 1 ) ]['code'] ) { + if ( T_WHITESPACE !== $this->tokens[ ( $scopeOpener - 1 ) ]['code'] ) { $error = 'Space between opening control structure and T_COLON is required'; if ( isset( $phpcsFile->fixer ) ) { @@ -158,7 +156,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } elseif ( 'forbidden' === $this->space_before_colon ) { - if ( T_WHITESPACE === $tokens[ ( $scopeOpener - 1 ) ]['code'] ) { + if ( T_WHITESPACE === $this->tokens[ ( $scopeOpener - 1 ) ]['code'] ) { $error = 'Extra space between opening control structure and T_COLON found'; if ( isset( $phpcsFile->fixer ) ) { @@ -179,13 +177,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $parenthesisOpener = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); // If this is a function declaration. - if ( T_FUNCTION === $tokens[ $stackPtr ]['code'] ) { + if ( T_FUNCTION === $this->tokens[ $stackPtr ]['code'] ) { - if ( T_STRING === $tokens[ $parenthesisOpener ]['code'] ) { + if ( T_STRING === $this->tokens[ $parenthesisOpener ]['code'] ) { $function_name_ptr = $parenthesisOpener; - } elseif ( T_BITWISE_AND === $tokens[ $parenthesisOpener ]['code'] ) { + } elseif ( T_BITWISE_AND === $this->tokens[ $parenthesisOpener ]['code'] ) { // This function returns by reference (function &function_name() {}). $function_name_ptr = $parenthesisOpener = $phpcsFile->findNext( @@ -211,7 +209,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $error, $stackPtr, 'SpaceBeforeFunctionOpenParenthesis', - $tokens[ ( $function_name_ptr + 1 ) ]['content'] + $this->tokens[ ( $function_name_ptr + 1 ) ]['content'] ); if ( true === $fix ) { @@ -220,14 +218,14 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->fixer->endChangeset(); } } - } elseif ( T_CLOSURE === $tokens[ $stackPtr ]['code'] ) { + } elseif ( T_CLOSURE === $this->tokens[ $stackPtr ]['code'] ) { // Check if there is a use () statement. - if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { + if ( isset( $this->tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { $usePtr = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, - ( $tokens[ $parenthesisOpener ]['parenthesis_closer'] + 1 ), + ( $this->tokens[ $parenthesisOpener ]['parenthesis_closer'] + 1 ), null, true, null, @@ -235,19 +233,19 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { ); // If it is, we set that as the "scope opener". - if ( T_USE === $tokens[ $usePtr ]['code'] ) { + if ( T_USE === $this->tokens[ $usePtr ]['code'] ) { $scopeOpener = $usePtr; } } } if ( - T_COLON !== $tokens[ $parenthesisOpener ]['code'] - && T_FUNCTION !== $tokens[ $stackPtr ]['code'] + T_COLON !== $this->tokens[ $parenthesisOpener ]['code'] + && T_FUNCTION !== $this->tokens[ $stackPtr ]['code'] ) { if ( - T_CLOSURE === $tokens[ $stackPtr ]['code'] + T_CLOSURE === $this->tokens[ $stackPtr ]['code'] && 0 === (int) $this->spaces_before_closure_open_paren ) { @@ -263,7 +261,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } elseif ( ( - T_CLOSURE !== $tokens[ $stackPtr ]['code'] + T_CLOSURE !== $this->tokens[ $stackPtr ]['code'] || 1 === (int) $this->spaces_before_closure_open_paren ) && ( $stackPtr + 1 ) === $parenthesisOpener @@ -285,8 +283,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } if ( - T_WHITESPACE === $tokens[ ( $stackPtr + 1 ) ]['code'] - && ' ' !== $tokens[ ( $stackPtr + 1 ) ]['content'] + T_WHITESPACE === $this->tokens[ ( $stackPtr + 1 ) ]['code'] + && ' ' !== $this->tokens[ ( $stackPtr + 1 ) ]['content'] ) { // Checking this: if [*](...) {}. $error = 'Expected exactly one space before opening parenthesis; "%s" found.'; @@ -294,7 +292,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $error, $stackPtr, 'ExtraSpaceBeforeOpenParenthesis', - $tokens[ ( $stackPtr + 1 ) ]['content'] + $this->tokens[ ( $stackPtr + 1 ) ]['content'] ); if ( true === $fix ) { @@ -304,8 +302,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - if ( T_WHITESPACE !== $tokens[ ( $parenthesisOpener + 1) ]['code'] - && T_CLOSE_PARENTHESIS !== $tokens[ ( $parenthesisOpener + 1) ]['code'] + if ( T_WHITESPACE !== $this->tokens[ ( $parenthesisOpener + 1) ]['code'] + && T_CLOSE_PARENTHESIS !== $this->tokens[ ( $parenthesisOpener + 1) ]['code'] ) { // Checking this: $value = my_function([*]...). $error = 'No space after opening parenthesis is prohibited'; @@ -321,13 +319,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { + if ( isset( $this->tokens[ $parenthesisOpener ]['parenthesis_closer'] ) ) { - $parenthesisCloser = $tokens[ $parenthesisOpener ]['parenthesis_closer']; + $parenthesisCloser = $this->tokens[ $parenthesisOpener ]['parenthesis_closer']; - if ( T_CLOSE_PARENTHESIS !== $tokens[ ( $parenthesisOpener + 1 ) ]['code'] ) { + if ( T_CLOSE_PARENTHESIS !== $this->tokens[ ( $parenthesisOpener + 1 ) ]['code'] ) { - if ( T_WHITESPACE !== $tokens[ ( $parenthesisCloser - 1 ) ]['code'] ) { + if ( T_WHITESPACE !== $this->tokens[ ( $parenthesisCloser - 1 ) ]['code'] ) { $error = 'No space before closing parenthesis is prohibited'; if ( isset( $phpcsFile->fixer ) ) { $fix = $phpcsFile->addFixableError( $error, $parenthesisCloser, 'NoSpaceBeforeCloseParenthesis' ); @@ -342,8 +340,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } if ( - T_WHITESPACE !== $tokens[ ( $parenthesisCloser + 1 ) ]['code'] - && T_COLON !== $tokens[ $scopeOpener ]['code'] + T_WHITESPACE !== $this->tokens[ ( $parenthesisCloser + 1 ) ]['code'] + && T_COLON !== $this->tokens[ $scopeOpener ]['code'] ) { $error = 'Space between opening control structure and closing parenthesis is required'; @@ -361,8 +359,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - if ( isset( $tokens[ $parenthesisOpener ]['parenthesis_owner'] ) - && $tokens[ $parenthesisCloser ]['line'] !== $tokens[ $scopeOpener ]['line'] + if ( isset( $this->tokens[ $parenthesisOpener ]['parenthesis_owner'] ) + && $this->tokens[ $parenthesisCloser ]['line'] !== $this->tokens[ $scopeOpener ]['line'] ) { $error = 'Opening brace should be on the same line as the declaration'; if ( isset( $phpcsFile->fixer ) ) { @@ -383,8 +381,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; } elseif ( - T_WHITESPACE === $tokens[ ( $parenthesisCloser + 1 ) ]['code'] - && ' ' !== $tokens[ ( $parenthesisCloser + 1 ) ]['content'] + T_WHITESPACE === $this->tokens[ ( $parenthesisCloser + 1 ) ]['code'] + && ' ' !== $this->tokens[ ( $parenthesisCloser + 1 ) ]['content'] ) { // Checking this: if (...) [*]{}. @@ -393,7 +391,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $error, $stackPtr, 'ExtraSpaceAfterCloseParenthesis', - $tokens[ ( $parenthesisCloser + 1 ) ]['content'] + $this->tokens[ ( $parenthesisCloser + 1 ) ]['content'] ); if ( true === $fix ) { @@ -406,8 +404,8 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { if ( true === $this->blank_line_check ) { $firstContent = $phpcsFile->findNext( T_WHITESPACE, ( $scopeOpener + 1 ), null, true ); - if ( $tokens[ $firstContent ]['line'] > ( $tokens[ $scopeOpener ]['line'] + 1 ) - && false === in_array( $tokens[ $firstContent ]['code'], array( T_CLOSE_TAG, T_COMMENT ), true ) + if ( $this->tokens[ $firstContent ]['line'] > ( $this->tokens[ $scopeOpener ]['line'] + 1 ) + && false === in_array( $this->tokens[ $firstContent ]['code'], array( T_CLOSE_TAG, T_COMMENT ), true ) ) { $error = 'Blank line found at start of control structure'; if ( isset( $phpcsFile->fixer ) ) { @@ -428,11 +426,11 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } $lastContent = $phpcsFile->findPrevious( T_WHITESPACE, ( $scopeCloser - 1 ), null, true ); - if ( ( $tokens[ $scopeCloser ]['line'] - 1 ) !== $tokens[ $lastContent ]['line'] ) { + if ( ( $this->tokens[ $scopeCloser ]['line'] - 1 ) !== $this->tokens[ $lastContent ]['line'] ) { $errorToken = $scopeCloser; for ( $i = ( $scopeCloser - 1 ); $i > $lastContent; $i-- ) { - if ( $tokens[ $i ]['line'] < $tokens[ $scopeCloser ]['line'] - && T_OPEN_TAG !== $tokens[ $firstContent ]['code'] + if ( $this->tokens[ $i ]['line'] < $this->tokens[ $scopeCloser ]['line'] + && T_OPEN_TAG !== $this->tokens[ $firstContent ]['code'] ) { // TODO: Reporting error at empty line won't highlight it in IDE. $error = 'Blank line found at end of control structure'; @@ -458,16 +456,16 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end if $trailingContent = $phpcsFile->findNext( T_WHITESPACE, ( $scopeCloser + 1 ), null, true ); - if ( T_ELSE === $tokens[ $trailingContent ]['code'] ) { - if ( T_IF === $tokens[ $stackPtr ]['code'] ) { + if ( T_ELSE === $this->tokens[ $trailingContent ]['code'] ) { + if ( T_IF === $this->tokens[ $stackPtr ]['code'] ) { // IF with ELSE. return; } } - if ( T_COMMENT === $tokens[ $trailingContent ]['code'] ) { - if ( $tokens[ $trailingContent ]['line'] === $tokens[ $scopeCloser ]['line'] ) { - if ( '//end' === substr( $tokens[ $trailingContent ]['content'], 0, 5 ) ) { + if ( T_COMMENT === $this->tokens[ $trailingContent ]['code'] ) { + if ( $this->tokens[ $trailingContent ]['line'] === $this->tokens[ $scopeCloser ]['line'] ) { + if ( '//end' === substr( $this->tokens[ $trailingContent ]['content'], 0, 5 ) ) { // There is an end comment, so we have to get the next piece // of content. $trailingContent = $phpcsFile->findNext( T_WHITESPACE, ( $trailingContent + 1), null, true ); @@ -475,27 +473,27 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - if ( T_BREAK === $tokens[ $trailingContent ]['code'] ) { + if ( T_BREAK === $this->tokens[ $trailingContent ]['code'] ) { // If this BREAK is closing a CASE, we don't need the // blank line after this control structure. - if ( isset( $tokens[ $trailingContent ]['scope_condition'] ) ) { - $condition = $tokens[ $trailingContent ]['scope_condition']; - if ( T_CASE === $tokens[ $condition ]['code'] || T_DEFAULT === $tokens[ $condition ]['code'] ) { + if ( isset( $this->tokens[ $trailingContent ]['scope_condition'] ) ) { + $condition = $this->tokens[ $trailingContent ]['scope_condition']; + if ( T_CASE === $this->tokens[ $condition ]['code'] || T_DEFAULT === $this->tokens[ $condition ]['code'] ) { return; } } } - if ( T_CLOSE_TAG === $tokens[ $trailingContent ]['code'] ) { + if ( T_CLOSE_TAG === $this->tokens[ $trailingContent ]['code'] ) { // At the end of the script or embedded code. return; } - if ( T_CLOSE_CURLY_BRACKET === $tokens[ $trailingContent ]['code'] ) { + if ( T_CLOSE_CURLY_BRACKET === $this->tokens[ $trailingContent ]['code'] ) { // Another control structure's closing brace. - if ( isset( $tokens[ $trailingContent ]['scope_condition'] ) ) { - $owner = $tokens[ $trailingContent ]['scope_condition']; - if ( in_array( $tokens[ $owner ]['code'], array( T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT ), true ) ) { + if ( isset( $this->tokens[ $trailingContent ]['scope_condition'] ) ) { + $owner = $this->tokens[ $trailingContent ]['scope_condition']; + if ( in_array( $this->tokens[ $owner ]['code'], array( T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT ), true ) ) { // The next content is the closing brace of a function, class, interface or trait // so normal function/class rules apply and we can ignore it. return; @@ -503,7 +501,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } if ( true === $this->blank_line_after_check - && ( $tokens[ $scopeCloser ]['line'] + 1 ) !== $tokens[ $trailingContent ]['line'] + && ( $this->tokens[ $scopeCloser ]['line'] + 1 ) !== $this->tokens[ $trailingContent ]['line'] ) { // TODO: Won't cover following case: "} echo 'OK';". $error = 'Blank line found after control structure'; diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index d1999fdc29..41c749a8d0 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -116,12 +116,12 @@ public function register() { public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Merge any custom functions with the defaults, if we haven't already. if ( ! self::$addedCustomFunctions ) { - WordPress_Sniff::$escapingFunctions = array_merge( WordPress_Sniff::$escapingFunctions, array_flip( $this->customEscapingFunctions ) ); - WordPress_Sniff::$autoEscapedFunctions = array_merge( WordPress_Sniff::$autoEscapedFunctions, array_flip( $this->customAutoEscapedFunctions ) ); - WordPress_Sniff::$printingFunctions = array_merge( WordPress_Sniff::$printingFunctions, array_flip( $this->customPrintingFunctions ) ); + self::$escapingFunctions = array_merge( self::$escapingFunctions, array_flip( $this->customEscapingFunctions ) ); + self::$autoEscapedFunctions = array_merge( self::$autoEscapedFunctions, array_flip( $this->customAutoEscapedFunctions ) ); + self::$printingFunctions = array_merge( self::$printingFunctions, array_flip( $this->customPrintingFunctions ) ); if ( ! empty( $this->customSanitizingFunctions ) ) { - WordPress_Sniff::$escapingFunctions = array_merge( WordPress_Sniff::$escapingFunctions, array_flip( $this->customSanitizingFunctions ) ); + self::$escapingFunctions = array_merge( self::$escapingFunctions, array_flip( $this->customSanitizingFunctions ) ); $phpcsFile->addWarning( 'The customSanitizingFunctions property is deprecated in favor of customEscapingFunctions.', 0, 'DeprecatedCustomSanitizingFunctions' ); } @@ -129,22 +129,21 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } $this->init( $phpcsFile ); - $tokens = $phpcsFile->getTokens(); - $function = $tokens[ $stackPtr ]['content']; + $function = $this->tokens[ $stackPtr ]['content']; // Find the opening parenthesis (if present; T_ECHO might not have it). $open_paren = $phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); // If function, not T_ECHO nor T_PRINT. - if ( T_STRING === $tokens[ $stackPtr ]['code'] ) { + if ( T_STRING === $this->tokens[ $stackPtr ]['code'] ) { // Skip if it is a function but is not of the printing functions. - if ( ! isset( self::$printingFunctions[ $tokens[ $stackPtr ]['content'] ] ) ) { + if ( ! isset( self::$printingFunctions[ $this->tokens[ $stackPtr ]['content'] ] ) ) { return; } - if ( isset( $tokens[ $open_paren ]['parenthesis_closer'] ) ) { - $end_of_statement = $tokens[ $open_paren ]['parenthesis_closer']; + if ( isset( $this->tokens[ $open_paren ]['parenthesis_closer'] ) ) { + $end_of_statement = $this->tokens[ $open_paren ]['parenthesis_closer']; } // These functions only need to have the first argument escaped. @@ -177,13 +176,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Check for the ternary operator. We only need to do this here if this // echo is lacking parenthesis. Otherwise it will be handled below. - if ( T_OPEN_PARENTHESIS !== $tokens[ $open_paren ]['code'] || T_CLOSE_PARENTHESIS !== $tokens[ $last_token ]['code'] ) { + if ( T_OPEN_PARENTHESIS !== $this->tokens[ $open_paren ]['code'] || T_CLOSE_PARENTHESIS !== $this->tokens[ $last_token ]['code'] ) { $ternary = $phpcsFile->findNext( T_INLINE_THEN, $stackPtr, $end_of_statement ); // If there is a ternary skip over the part before the ?. However, if // the ternary is within parentheses, it will be handled in the loop. - if ( $ternary && empty( $tokens[ $ternary ]['nested_parenthesis'] ) ) { + if ( $ternary && empty( $this->tokens[ $ternary ]['nested_parenthesis'] ) ) { $stackPtr = $ternary; } } @@ -199,29 +198,29 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { for ( $i = $stackPtr; $i < $end_of_statement; $i++ ) { // Ignore whitespaces and comments. - if ( in_array( $tokens[ $i ]['code'], PHP_CodeSniffer_Tokens::$emptyTokens, true ) ) { + if ( in_array( $this->tokens[ $i ]['code'], PHP_CodeSniffer_Tokens::$emptyTokens, true ) ) { continue; } - if ( T_OPEN_PARENTHESIS === $tokens[ $i ]['code'] ) { + if ( T_OPEN_PARENTHESIS === $this->tokens[ $i ]['code'] ) { if ( $in_cast ) { // Skip to the end of a function call if it has been casted to a safe value. - $i = $tokens[ $i ]['parenthesis_closer']; + $i = $this->tokens[ $i ]['parenthesis_closer']; $in_cast = false; } else { // Skip over the condition part of a ternary (i.e., to after the ?). - $ternary = $phpcsFile->findNext( T_INLINE_THEN, $i, $tokens[ $i ]['parenthesis_closer'] ); + $ternary = $phpcsFile->findNext( T_INLINE_THEN, $i, $this->tokens[ $i ]['parenthesis_closer'] ); if ( $ternary ) { - $next_paren = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $i + 1 ), $tokens[ $i ]['parenthesis_closer'] ); + $next_paren = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ( $i + 1 ), $this->tokens[ $i ]['parenthesis_closer'] ); // We only do it if the ternary isn't within a subset of parentheses. - if ( ! $next_paren || $ternary > $tokens[ $next_paren ]['parenthesis_closer'] ) { + if ( ! $next_paren || $ternary > $this->tokens[ $next_paren ]['parenthesis_closer'] ) { $i = $ternary; } } @@ -231,34 +230,34 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // Handle arrays for those functions that accept them. - if ( T_ARRAY === $tokens[ $i ]['code'] ) { + if ( T_ARRAY === $this->tokens[ $i ]['code'] ) { $i++; // Skip the opening parenthesis. continue; } - if ( in_array( $tokens[ $i ]['code'], array( T_DOUBLE_ARROW, T_CLOSE_PARENTHESIS ), true ) ) { + if ( in_array( $this->tokens[ $i ]['code'], array( T_DOUBLE_ARROW, T_CLOSE_PARENTHESIS ), true ) ) { continue; } // Handle magic constants for debug functions. - if ( isset( $this->magic_constant_tokens[ $tokens[ $i ]['type'] ] ) ) { + if ( isset( $this->magic_constant_tokens[ $this->tokens[ $i ]['type'] ] ) ) { continue; } // Wake up on concatenation characters, another part to check. - if ( in_array( $tokens[ $i ]['code'], array( T_STRING_CONCAT ), true ) ) { + if ( in_array( $this->tokens[ $i ]['code'], array( T_STRING_CONCAT ), true ) ) { $watch = true; continue; } // Wake up after a ternary else (:). - if ( $ternary && in_array( $tokens[ $i ]['code'], array( T_INLINE_ELSE ), true ) ) { + if ( $ternary && in_array( $this->tokens[ $i ]['code'], array( T_INLINE_ELSE ), true ) ) { $watch = true; continue; } // Wake up for commas. - if ( T_COMMA === $tokens[ $i ]['code'] ) { + if ( T_COMMA === $this->tokens[ $i ]['code'] ) { $in_cast = false; $watch = true; continue; @@ -270,14 +269,14 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { // Allow T_CONSTANT_ENCAPSED_STRING eg: echo 'Some String'; // Also T_LNUMBER, e.g.: echo 45; exit -1; and booleans. - if ( in_array( $tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_MINUS, T_TRUE, T_FALSE, T_NULL ), true ) ) { + if ( in_array( $this->tokens[ $i ]['code'], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_MINUS, T_TRUE, T_FALSE, T_NULL ), true ) ) { continue; } $watch = false; // Allow int/double/bool casted variables. - if ( in_array( $tokens[ $i ]['code'], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { + if ( in_array( $this->tokens[ $i ]['code'], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { $in_cast = true; continue; } @@ -298,7 +297,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $mapped_function = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $function_opener + 1 ), - $tokens[ $function_opener ]['parenthesis_closer'], + $this->tokens[ $function_opener ]['parenthesis_closer'], true ); From f60bfe5c3aad100b191192ea1d06e515df3d8f27 Mon Sep 17 00:00:00 2001 From: Juliette Date: Thu, 18 Aug 2016 08:10:58 +0200 Subject: [PATCH 117/122] Streamline WPCS in file documentation. (#651) * Update the file and class @package tag and remove the @category tag. Follow the standard as described in https://www.phpdoc.org/docs/latest/references/phpdoc/tags/package.html The @category tag is considered deprecated. A hierarchical @package tag should be used instead. Ref: https://www.phpdoc.org/docs/latest/references/phpdoc/tags/category.html * Use correct version number for the newly deprecated classes. * Fix some - unintentional - parse errors in the test files. * Attempt to lead by example comment-wise in the unit tests. Capitalization, punctuation and some spelling. * Proper capitalization and punctuation for class end comments. * Remove `//end` comments for methods and conditionals < 35 lines. * Simplify the test file method doc blocks. * Various documentation fixes, largely based on PHPCS Docs output. * Make sure any function which will be passed the $phpcsFile has the right type hint. But only if it doesn't conflict with upstream function signatures. * Verify and update the docblocks for all files and classes. Based on Git file history: * Add @since tags to all classes. * Add @since tags to properties and methods if they weren't included from the start. * Verify/Fix a number of @author tags. * Remove old/copied over/incorrect PHPCS tags. * Where necessary improved/corrected the class description. Also: * Consistent tag order in class doc blocks. * Fix tag alignment. * Remove redundant explanation in unit test class doc blocks. * Sync the description line of the unit test class doc blocks. * Add handbook links to a number of sniffs. * Add reference to upstream sniff a sniff is based upon. Includes information on when the sniff was last synced with the upstream sniff if applicable and available. * Add @license tag and @link tag to the WPCS GH repo, to all file level doc blocks. License tag as per https://www.phpdoc.org/docs/latest/references/phpdoc/tags/license.html * Add the docs ruleset to the coding standard for WPCS itself. * Add @since class changelogs for PR #647. * Fix minor grammar error. * Updated `@since` tags for `2014-12-11` release to `0.3.0`. * Re-instate previously removed @since tags. * Updated based on feedback. * Adjusted the @package tags as per discussion in the PR thread * Removed the @link tag to the handbook at the file level doc block * Removed the @author tags --- ...stractArrayAssignmentRestrictionsSniff.php | 20 +- WordPress/AbstractClassRestrictionsSniff.php | 45 ++--- .../AbstractFunctionRestrictionsSniff.php | 18 +- .../AbstractVariableRestrictionsSniff.php | 32 ++-- WordPress/Sniff.php | 37 ++-- .../ArrayAssignmentRestrictionsSniff.php | 26 +-- .../Sniffs/Arrays/ArrayDeclarationSniff.php | 57 ++++-- .../ArrayKeySpacingRestrictionsSniff.php | 19 +- .../Sniffs/CSRF/NonceVerificationSniff.php | 19 +- .../Classes/ClassOpeningStatementSniff.php | 27 +-- .../Sniffs/Classes/ValidClassNameSniff.php | 35 ++-- .../Sniffs/DB/RestrictedClassesSniff.php | 16 +- .../Sniffs/DB/RestrictedFunctionsSniff.php | 16 +- WordPress/Sniffs/Files/FileNameSniff.php | 20 +- .../Sniffs/Functions/DontExtractSniff.php | 16 +- .../Functions/FunctionRestrictionsSniff.php | 24 +-- .../ValidFunctionNameSniff.php | 28 +-- .../NamingConventions/ValidHookNameSniff.php | 18 +- .../ValidVariableNameSniff.php | 39 ++-- .../PHP/DisallowAlternativePHPTagsSniff.php | 21 ++- .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 20 +- WordPress/Sniffs/PHP/POSIXFunctionsSniff.php | 19 +- .../Sniffs/PHP/StrictComparisonsSniff.php | 23 ++- WordPress/Sniffs/PHP/StrictInArraySniff.php | 20 +- WordPress/Sniffs/PHP/YodaConditionsSniff.php | 22 +-- WordPress/Sniffs/VIP/AdminBarRemovalSniff.php | 18 +- WordPress/Sniffs/VIP/CronIntervalSniff.php | 35 ++-- .../Sniffs/VIP/DirectDatabaseQuerySniff.php | 20 +- .../VIP/FileSystemWritesDisallowSniff.php | 20 +- WordPress/Sniffs/VIP/OrderByRandSniff.php | 17 +- WordPress/Sniffs/VIP/PluginMenuSlugSniff.php | 25 ++- WordPress/Sniffs/VIP/PostsPerPageSniff.php | 18 +- .../Sniffs/VIP/RestrictedFunctionsSniff.php | 35 +++- .../Sniffs/VIP/RestrictedVariablesSniff.php | 21 ++- .../Sniffs/VIP/SessionFunctionsUsageSniff.php | 34 ++-- .../Sniffs/VIP/SessionVariableUsageSniff.php | 24 +-- WordPress/Sniffs/VIP/SlowDBQuerySniff.php | 24 ++- .../Sniffs/VIP/SuperGlobalInputUsageSniff.php | 23 +-- WordPress/Sniffs/VIP/TimezoneChangeSniff.php | 35 ++-- .../VIP/ValidatedSanitizedInputSniff.php | 22 +-- .../Sniffs/Variables/GlobalVariablesSniff.php | 20 +- .../Variables/VariableRestrictionsSniff.php | 26 +-- .../Sniffs/WP/EnqueuedResourcesSniff.php | 20 +- WordPress/Sniffs/WP/I18nSniff.php | 52 ++++-- WordPress/Sniffs/WP/PreparedSQLSniff.php | 19 +- .../WhiteSpace/CastStructureSpacingSniff.php | 34 ++-- .../ControlStructureSpacingSniff.php | 32 ++-- .../WhiteSpace/OperatorSpacingSniff.php | 42 +++-- WordPress/Sniffs/XSS/EscapeOutputSniff.php | 26 +-- .../ArrayAssignmentRestrictionsUnitTest.inc | 6 +- .../ArrayAssignmentRestrictionsUnitTest.php | 33 ++-- .../Tests/Arrays/ArrayDeclarationUnitTest.inc | 84 ++++----- .../Arrays/ArrayDeclarationUnitTest.inc.fixed | 84 ++++----- .../Tests/Arrays/ArrayDeclarationUnitTest.php | 35 +--- .../ArrayKeySpacingRestrictionsUnitTest.inc | 48 ++--- ...ayKeySpacingRestrictionsUnitTest.inc.fixed | 48 ++--- .../ArrayKeySpacingRestrictionsUnitTest.php | 30 ++- .../Tests/CSRF/NonceVerificationUnitTest.inc | 32 ++-- .../Tests/CSRF/NonceVerificationUnitTest.php | 30 ++- .../Classes/ClassOpeningStatementUnitTest.php | 30 +-- .../Tests/Classes/ValidClassNameUnitTest.inc | 6 +- .../Tests/Classes/ValidClassNameUnitTest.php | 35 +--- .../Tests/DB/RestrictedClassesUnitTest.1.inc | 2 +- .../Tests/DB/RestrictedClassesUnitTest.2.inc | 40 ++-- .../Tests/DB/RestrictedClassesUnitTest.3.inc | 64 +++---- .../Tests/DB/RestrictedClassesUnitTest.php | 34 +--- .../Tests/DB/RestrictedFunctionsUnitTest.inc | 20 +- .../Tests/DB/RestrictedFunctionsUnitTest.php | 35 +--- WordPress/Tests/Files/FileNameUnitTest.php | 35 +--- .../Tests/Functions/DontExtractUnitTest.inc | 2 +- .../Tests/Functions/DontExtractUnitTest.php | 35 ++-- .../ValidFunctionNameUnitTest.inc | 28 +-- .../ValidFunctionNameUnitTest.php | 35 +--- .../ValidHookNameUnitTest.php | 32 +--- .../ValidVariableNameUnitTest.inc | 94 +++++----- .../ValidVariableNameUnitTest.php | 36 +--- .../DisallowAlternativePHPTagsUnitTest.php | 24 +-- .../PHP/DiscouragedFunctionsUnitTest.inc | 16 +- .../PHP/DiscouragedFunctionsUnitTest.php | 37 ++-- .../Tests/PHP/POSIXFunctionsUnitTest.inc | 12 +- .../Tests/PHP/POSIXFunctionsUnitTest.php | 37 ++-- .../Tests/PHP/StrictComparisonsUnitTest.inc | 18 +- .../Tests/PHP/StrictComparisonsUnitTest.php | 33 +--- WordPress/Tests/PHP/StrictInArrayUnitTest.inc | 20 +- WordPress/Tests/PHP/StrictInArrayUnitTest.php | 29 +-- .../Tests/PHP/YodaConditionsUnitTest.inc | 80 ++++---- .../Tests/PHP/YodaConditionsUnitTest.php | 35 ++-- .../Tests/VIP/AdminBarRemovalUnitTest.php | 30 ++- WordPress/Tests/VIP/CronIntervalUnitTest.inc | 2 +- WordPress/Tests/VIP/CronIntervalUnitTest.php | 30 ++- .../Tests/VIP/DirectDatabaseQueryUnitTest.inc | 46 ++--- .../Tests/VIP/DirectDatabaseQueryUnitTest.php | 30 ++- .../VIP/FileSystemWritesDisallowUnitTest.php | 30 ++- WordPress/Tests/VIP/OrderByRandUnitTest.inc | 12 +- WordPress/Tests/VIP/OrderByRandUnitTest.php | 29 ++- .../Tests/VIP/PluginMenuSlugUnitTest.inc | 6 +- .../Tests/VIP/PluginMenuSlugUnitTest.php | 30 ++- WordPress/Tests/VIP/PostsPerPageUnitTest.inc | 22 +-- WordPress/Tests/VIP/PostsPerPageUnitTest.php | 30 ++- .../Tests/VIP/RestrictedFunctionsUnitTest.inc | 142 +++++++------- .../Tests/VIP/RestrictedFunctionsUnitTest.php | 33 +--- .../Tests/VIP/RestrictedVariablesUnitTest.inc | 18 +- .../Tests/VIP/RestrictedVariablesUnitTest.php | 35 ++-- .../VIP/SessionFunctionsUsageUnitTest.php | 30 ++- .../VIP/SessionVariableUsageUnitTest.php | 30 ++- WordPress/Tests/VIP/SlowDBQueryUnitTest.php | 30 ++- .../VIP/SuperGlobalInputUsageUnitTest.inc | 10 +- .../VIP/SuperGlobalInputUsageUnitTest.php | 30 ++- .../Tests/VIP/TimezoneChangeUnitTest.inc | 2 +- .../Tests/VIP/TimezoneChangeUnitTest.php | 30 ++- .../VIP/ValidatedSanitizedInputUnitTest.inc | 86 ++++----- .../VIP/ValidatedSanitizedInputUnitTest.php | 30 ++- .../Variables/GlobalVariablesUnitTest.inc | 2 +- .../Variables/GlobalVariablesUnitTest.php | 30 ++- .../VariableRestrictionsUnitTest.inc | 22 +-- .../VariableRestrictionsUnitTest.php | 33 ++-- .../Tests/WP/EnqueuedResourcesUnitTest.php | 27 +-- WordPress/Tests/WP/I18nUnitTest.inc | 50 ++--- WordPress/Tests/WP/I18nUnitTest.inc.fixed | 50 ++--- WordPress/Tests/WP/I18nUnitTest.php | 30 ++- WordPress/Tests/WP/PreparedSQLUnitTest.inc | 34 ++-- WordPress/Tests/WP/PreparedSQLUnitTest.php | 24 ++- .../CastStructureSpacingUnitTest.inc | 2 +- .../CastStructureSpacingUnitTest.php | 33 +--- .../ControlStructureSpacingUnitTest.inc | 62 +++---- .../ControlStructureSpacingUnitTest.inc.fixed | 62 +++---- .../ControlStructureSpacingUnitTest.php | 36 ++-- .../WhiteSpace/OperatorSpacingUnitTest.inc | 14 +- .../OperatorSpacingUnitTest.inc.fixed | 14 +- .../WhiteSpace/OperatorSpacingUnitTest.php | 35 +--- WordPress/Tests/XSS/EscapeOutputUnitTest.inc | 174 +++++++++--------- WordPress/Tests/XSS/EscapeOutputUnitTest.php | 33 +--- bin/phpcs.xml | 4 +- 133 files changed, 1950 insertions(+), 2237 deletions(-) diff --git a/WordPress/AbstractArrayAssignmentRestrictionsSniff.php b/WordPress/AbstractArrayAssignmentRestrictionsSniff.php index f875bc9d7c..3329826316 100644 --- a/WordPress/AbstractArrayAssignmentRestrictionsSniff.php +++ b/WordPress/AbstractArrayAssignmentRestrictionsSniff.php @@ -2,17 +2,21 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts array assignment of certain keys. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.10.0 Class became a proper abstract class. This was already the behaviour. + * Moved the file and renamed the class from + * `WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff` to + * `WordPress_AbstractArrayAssignmentRestrictionsSniff`. */ abstract class WordPress_AbstractArrayAssignmentRestrictionsSniff extends WordPress_Sniff { @@ -47,7 +51,7 @@ public function register() { T_DOUBLE_QUOTED_STRING, ); - } // end register() + } /** * Groups of variables to restrict. @@ -195,4 +199,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { */ abstract public function callback( $key, $val, $line, $group ); -} // end class +} // End class. diff --git a/WordPress/AbstractClassRestrictionsSniff.php b/WordPress/AbstractClassRestrictionsSniff.php index bcb2164958..a9a4e82426 100644 --- a/WordPress/AbstractClassRestrictionsSniff.php +++ b/WordPress/AbstractClassRestrictionsSniff.php @@ -2,17 +2,17 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some classes. * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 */ abstract class WordPress_AbstractClassRestrictionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -51,8 +51,9 @@ abstract class WordPress_AbstractClassRestrictionsSniff extends WordPress_Abstra * Documented here for clarity. Not (re)defined as it is already defined in the parent class. * * @return array + * + abstract public function getGroups(); */ - // abstract public function getGroups(); /** * Returns an array of tokens this test wants to listen for. @@ -72,7 +73,7 @@ public function register() { T_IMPLEMENTS, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -178,13 +179,13 @@ protected function prepare_name_for_regex( $classname ) { /** * See if the classname was found in a namespaced file and if so, add the namespace to the classname. * - * @param string $classname The full classname as found. - * @param object $phpcsFile Instance of phpcsFile. - * @param array $tokens The token stack for this file. - * @param int $search_from The token position to search up from. + * @param string $classname The full classname as found. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tokens The token stack for this file. + * @param int $search_from The token position to search up from. * @return string Classname, potentially prefixed with the namespace. */ - protected function get_namespaced_classname( $classname, $phpcsFile, $tokens, $search_from ) { + protected function get_namespaced_classname( $classname, PHP_CodeSniffer_File $phpcsFile, $tokens, $search_from ) { // Don't do anything if this is already a fully qualified classname. if ( empty( $classname ) || '\\' === $classname[0] ) { return $classname; @@ -216,12 +217,12 @@ protected function get_namespaced_classname( $classname, $phpcsFile, $tokens, $s /** * Determine the namespace name based on whether this is a scoped namespace or a file namespace. * - * @param object $phpcsFile Instance of phpcsFile. - * @param array $tokens The token stack for this file. - * @param int $search_from The token position to search up from. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tokens The token stack for this file. + * @param int $search_from The token position to search up from. * @return string Namespace name or empty string if it couldn't be determined or no namespace applied. */ - protected function determine_namespace( $phpcsFile, $tokens, $search_from ) { + protected function determine_namespace( PHP_CodeSniffer_File $phpcsFile, $tokens, $search_from ) { $namespace = ''; if ( ! empty( $tokens[ $search_from ]['conditions'] ) ) { @@ -247,12 +248,12 @@ protected function determine_namespace( $phpcsFile, $tokens, $search_from ) { /** * Get the namespace name based on the position of the namespace scope opener. * - * @param object $phpcsFile Instance of phpcsFile. - * @param array $tokens The token stack for this file. - * @param int $t_namespace_token The token position to search from. + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param array $tokens The token stack for this file. + * @param int $t_namespace_token The token position to search from. * @return string Namespace name. */ - protected function get_namespace_name( $phpcsFile, $tokens, $t_namespace_token ) { + protected function get_namespace_name( PHP_CodeSniffer_File $phpcsFile, $tokens, $t_namespace_token ) { $nameEnd = ( $phpcsFile->findNext( array( T_OPEN_CURLY_BRACKET, T_WHITESPACE, T_SEMICOLON ), ( $t_namespace_token + 2 ) ) - 1 ); $length = ( $nameEnd - ( $t_namespace_token + 1 ) ); $namespace = $phpcsFile->getTokensAsString( ( $t_namespace_token + 2 ), $length ); @@ -260,4 +261,4 @@ protected function get_namespace_name( $phpcsFile, $tokens, $t_namespace_token ) return $namespace; } -} // end class +} // End class. diff --git a/WordPress/AbstractFunctionRestrictionsSniff.php b/WordPress/AbstractFunctionRestrictionsSniff.php index 4598c1a742..e21341fd75 100644 --- a/WordPress/AbstractFunctionRestrictionsSniff.php +++ b/WordPress/AbstractFunctionRestrictionsSniff.php @@ -2,17 +2,21 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some functions. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.10.0 Class became a proper abstract class. This was already the behaviour. + * Moved the file and renamed the class from + * `WordPress_Sniffs_Functions_FunctionRestrictionsSniff` to + * `WordPress_AbstractFunctionRestrictionsSniff`. */ abstract class WordPress_AbstractFunctionRestrictionsSniff implements PHP_CodeSniffer_Sniff { @@ -209,4 +213,4 @@ protected function prepare_name_for_regex( $function ) { return $function; } -} // end class +} // End class. diff --git a/WordPress/AbstractVariableRestrictionsSniff.php b/WordPress/AbstractVariableRestrictionsSniff.php index 530f809313..5cd5bdbfc4 100644 --- a/WordPress/AbstractVariableRestrictionsSniff.php +++ b/WordPress/AbstractVariableRestrictionsSniff.php @@ -2,17 +2,21 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some variables. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.10.0 Class became a proper abstract class. This was already the behaviour. + * Moved the file and renamed the class from + * `WordPress_Sniffs_Variables_VariableRestrictionsSniff` to + * `WordPress_AbstractVariableRestrictionsSniff`. */ abstract class WordPress_AbstractVariableRestrictionsSniff implements PHP_CodeSniffer_Sniff { @@ -48,7 +52,7 @@ public function register() { T_DOUBLE_QUOTED_STRING, ); - } // end register() + } /** * Groups of variables to restrict. @@ -76,7 +80,7 @@ abstract public function getGroups(); * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * - * @return void + * @return int|void If no groups are found, a stack pointer to indicate to skip the current one is passed. */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); @@ -111,7 +115,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $var = $token['content']; } elseif ( in_array( $token['code'], array( T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_DOUBLE_QUOTED_STRING ), true ) && ! empty( $group['object_vars'] ) ) { - // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar + // Object var, ex: $foo->bar / $foo::bar / Foo::bar / Foo::$bar . $patterns = array_merge( $patterns, $group['object_vars'] ); $owner = $phpcsFile->findPrevious( array( T_VARIABLE, T_STRING ), $stackPtr ); @@ -165,6 +169,12 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() + /** + * Transform a wildcard pattern to a usable regex pattern. + * + * @param string $pattern Pattern. + * @return string + */ private function test_patterns( $pattern ) { $pattern = preg_quote( $pattern, '#' ); $pattern = preg_replace( @@ -173,6 +183,6 @@ private function test_patterns( $pattern ) { $pattern ); return $pattern; - } // end test_patterns() + } -} // end class +} // End class. diff --git a/WordPress/Sniff.php b/WordPress/Sniff.php index ee010cd4f8..9e7f8bd8b0 100644 --- a/WordPress/Sniff.php +++ b/WordPress/Sniff.php @@ -2,8 +2,9 @@ /** * Represents a PHP_CodeSniffer sniff for sniffing WordPress coding standards. * - * @category PHP - * @package PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -11,10 +12,8 @@ * * Provides a bootstrap for the sniffs, to reduce code duplication. * - * @category PHP - * @package PHP_CodeSniffer - * @version 0.4.0 - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.4.0 */ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { @@ -461,7 +460,7 @@ abstract class WordPress_Sniff implements PHP_CodeSniffer_Sniff { /** * A list of superglobals that incorporate user input. * - * @since 0.4.0 + * @since 0.5.0 * * @var string[] */ @@ -578,7 +577,7 @@ protected function has_whitelist_comment( $comment, $stackPtr ) { * * $array['key'][ $foo ][ something() ] = $bar; * - * @since 0.4.0 + * @since 0.5.0 * * @param int $stackPtr The index of the token in the stack. This must points to * either a T_VARIABLE or T_CLOSE_SQUARE_BRACKET token. @@ -613,7 +612,7 @@ protected function is_assignment( $stackPtr ) { return true; } - // Check if this is an array assignment, e.g., $var['key'] = 'val'; + // Check if this is an array assignment, e.g., `$var['key'] = 'val';` . if ( T_OPEN_SQUARE_BRACKET === $tokens[ $next_non_empty ]['code'] ) { return $this->is_assignment( $tokens[ $next_non_empty ]['bracket_closer'] ); } @@ -633,14 +632,14 @@ protected function is_assignment( $stackPtr ) { protected function has_nonce_check( $stackPtr ) { /** - * @var array { - * A cache of the scope that we last checked for nonce verification in. + * A cache of the scope that we last checked for nonce verification in. * - * @var string $file The name of the file. - * @var int $start The index of the token where the scope started. - * @var int $end The index of the token where the scope ended. - * @var bool|int $nonce_check The index of the token where an nonce - * check was found, or false if none was found. + * @var array { + * @var string $file The name of the file. + * @var int $start The index of the token where the scope started. + * @var int $end The index of the token where the scope ended. + * @var bool|int $nonce_check The index of the token where an nonce check + * was found, or false if none was found. * } */ static $last; @@ -973,7 +972,6 @@ protected function get_array_access_key( $stackPtr ) { protected function is_validated( $stackPtr, $array_key = null, $in_condition_only = false ) { if ( $in_condition_only ) { - /* This is a stricter check, requiring the variable to be used only within the validation condition. @@ -1004,7 +1002,6 @@ protected function is_validated( $stackPtr, $array_key = null, $in_condition_onl $scope_end = $condition['parenthesis_closer']; } else { - /* We are are more loose, requiring only that the variable be validated in the same function/file scope as it is used. @@ -1130,6 +1127,8 @@ protected function is_comparison( $stackPtr ) { * This function will check the token and return 'closure', 'trait', or 'class', * based on which of these uses the use is being used for. * + * @since 0.7.0 + * * @param int $stackPtr The position of the token to check. * * @return string The type of use. @@ -1157,6 +1156,8 @@ protected function get_use_type( $stackPtr ) { * * Check if '$' is followed by a valid variable name, and that it is not preceded by an escape sequence. * + * @since 0.9.0 + * * @param string $string A T_DOUBLE_QUOTED_STRING token. * * @return array Variable names (without '$' sigil). diff --git a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php index 0fb0f044b9..309303d785 100644 --- a/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayAssignmentRestrictionsSniff.php @@ -2,24 +2,24 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts array assignment of certain keys. * - * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to - * the WordPress_AbstractArrayAssignmentRestrictionsSniff class. - * This class is left here to prevent backward-compatibility breaks for - * custom sniffs extending the old class and references to this - * sniff from custom phpcs.xml files. - * This file is also still used to unit test the abstract class. + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 + * @deprecated 0.10.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractArrayAssignmentRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * This file is also still used to unit test the abstract class. + * @see WordPress_AbstractArrayAssignmentRestrictionsSniff */ class WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { @@ -56,4 +56,4 @@ public function callback( $key, $val, $line, $group ) { return true; } // end callback() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php index 49c4675033..7e0d6ccad4 100644 --- a/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -1,12 +1,10 @@ - * @author Greg Sherwood - * @author Marc McIntyre + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'Squiz_Sniffs_Arrays_ArrayDeclarationSniff', true ) ) { @@ -14,18 +12,40 @@ } /** - * Enforces WordPress array format. + * Enforces WordPress array format, based upon Squiz code. + * + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#indentation + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.1.0 + * @since 0.5.0 Now extends `Squiz_Sniffs_Arrays_ArrayDeclarationSniff`. + * + * @todo Check whether the upstream PRs have been merged and released and if possible, + * remove duplicate logic. + * Ref: commit 3ea49d2b56f248d83bed890f9f5246d67c775d54 + * "The upstream version is similar, except that we exclude a few errors. + * Unfortunately we have to actually comment out the code rather than just + * using the upstream sniff and `` in our ruleset, due to a bug + * (squizlabs/PHP_CodeSniffer#582). (I've also included a fix for another + * bug, squizlabs/PHP_CodeSniffer#584.) Because of this, we cannot yet + * eliminate duplicated logic from this child sniff." * - * @category PHP - * @package PHP_CodeSniffer - * @author John Godley - * @author Greg Sherwood - * @author Marc McIntyre + * Last synced with parent class ?[unknown date]? at commit ?[unknown commit]?. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php */ class WordPress_Sniffs_Arrays_ArrayDeclarationSniff extends Squiz_Sniffs_Arrays_ArrayDeclarationSniff { /** + * Process a single line array. + * * @since 0.5.0 + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart Position of the array opener in the token stack. + * @param int $arrayEnd Position of the array closer in the token stack. */ public function processSingleLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $arrayStart, $arrayEnd ) { @@ -85,7 +105,15 @@ public function processSingleLineArray( PHP_CodeSniffer_File $phpcsFile, $stackP } /** + * Process a multi-line array. + * * @since 0.5.0 + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart Position of the array opener in the token stack. + * @param int $arrayEnd Position of the array closer in the token stack. */ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $arrayStart, $arrayEnd ) { $tokens = $phpcsFile->getTokens(); @@ -458,9 +486,8 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt $nextComma = $i; break; } - } // end for + } // End for. - //if ( $nextComma === false || ( $tokens[ $nextComma ]['line'] !== $valueLine ) ) { if ( false === $nextComma ) { $error = 'Each line in an array declaration must end in a comma'; $fix = $phpcsFile->addFixableError( $error, $index['value'], 'NoComma' ); @@ -496,4 +523,4 @@ public function processMultiLineArray( PHP_CodeSniffer_File $phpcsFile, $stackPt } // end processMultiLineArray() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php index 1950547ed6..c02272f13a 100644 --- a/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php +++ b/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php @@ -2,19 +2,20 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Check for proper spacing in array key references. * - * @link http://make.wordpress.org/core/handbook/coding-standards/php/#space-usage + * @link http://make.wordpress.org/core/handbook/coding-standards/php/#space-usage * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.7.0 This sniff now has the ability to fix a number of the issues it flags. */ class WordPress_Sniffs_Arrays_ArrayKeySpacingRestrictionsSniff implements PHP_CodeSniffer_Sniff { @@ -28,7 +29,7 @@ public function register() { T_OPEN_SQUARE_BRACKET, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -85,4 +86,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php index 7bc92b3a3b..2ba0a2d7a9 100644 --- a/WordPress/Sniffs/CSRF/NonceVerificationSniff.php +++ b/WordPress/Sniffs/CSRF/NonceVerificationSniff.php @@ -1,23 +1,20 @@ + * @since 0.5.0 */ class WordPress_Sniffs_CSRF_NonceVerificationSniff extends WordPress_Sniff { @@ -134,4 +131,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php index 23d432836b..c4b9a4b571 100644 --- a/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php +++ b/WordPress/Sniffs/Classes/ClassOpeningStatementSniff.php @@ -2,24 +2,27 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Classes_ClassOpeningStatementSniff. - * * Checks that the opening brace of a class or interface is on the same line * as the class declaration. * * Also checks that the brace is the last thing on that line and has precisely one space before it. * - * Loosely based on Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff. + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#brace-style + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * {@internal Upstream PR https://github.com/squizlabs/PHP_CodeSniffer/pull/1070 has been merged. + * If and when the WPCS minimum PHPCS version would be upped to the version + * that PR is contained in - probably v 2.7.0 -, this sniff and associated unit tests + * can be replaced by the upstream sniff Generic.Classes.OpeningBraceSameLine.}} */ class WordPress_Sniffs_Classes_ClassOpeningStatementSniff implements PHP_CodeSniffer_Sniff { @@ -35,7 +38,7 @@ public function register() { T_TRAIT, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -129,6 +132,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } - } // end process() + } // End process(). -} // end class +} // End class. diff --git a/WordPress/Sniffs/Classes/ValidClassNameSniff.php b/WordPress/Sniffs/Classes/ValidClassNameSniff.php index c5c2bd31f2..90f3dd2094 100644 --- a/WordPress/Sniffs/Classes/ValidClassNameSniff.php +++ b/WordPress/Sniffs/Classes/ValidClassNameSniff.php @@ -1,30 +1,23 @@ - * @author Marc McIntyre - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version CVS: $Id: ValidClassNameSniff.php,v 1.6 2008/05/19 05:59:25 squiz Exp $ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Squiz_Sniffs_Classes_ValidClassNameSniff. + * Ensures classes are in camel caps, and the first letter is capitalised. * - * Ensures classes are in camel caps, and the first letter is capitalised + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) - * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence - * @version Release: 1.2.0RC1 - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * + * @since 0.1.0 + * + * Last synced with base class ?[unknown date]? at commit ?[unknown commit]?. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php */ class WordPress_Sniffs_Classes_ValidClassNameSniff implements PHP_CodeSniffer_Sniff { @@ -39,7 +32,7 @@ public function register() { T_INTERFACE, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -79,4 +72,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/DB/RestrictedClassesSniff.php b/WordPress/Sniffs/DB/RestrictedClassesSniff.php index f036014a2c..e9bdbc762a 100644 --- a/WordPress/Sniffs/DB/RestrictedClassesSniff.php +++ b/WordPress/Sniffs/DB/RestrictedClassesSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -15,11 +15,11 @@ * helps keep your code forward-compatible and, in cases where results are cached in memory, * it can be many times faster." * - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#database-queries + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#database-queries * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 */ class WordPress_Sniffs_DB_RestrictedClassesSniff extends WordPress_AbstractClassRestrictionsSniff { @@ -52,4 +52,4 @@ public function getGroups() { ); } -} // end class +} // End class. diff --git a/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php index 8fb9735aa2..17a65ea723 100644 --- a/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -15,11 +15,11 @@ * helps keep your code forward-compatible and, in cases where results are cached in memory, * it can be many times faster." * - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#database-queries + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#database-queries * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 */ class WordPress_Sniffs_DB_RestrictedFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -59,4 +59,4 @@ public function getGroups() { ); } -} // end class +} // End class. diff --git a/WordPress/Sniffs/Files/FileNameSniff.php b/WordPress/Sniffs/Files/FileNameSniff.php index 4e24b72b8a..8c7887df97 100644 --- a/WordPress/Sniffs/Files/FileNameSniff.php +++ b/WordPress/Sniffs/Files/FileNameSniff.php @@ -2,19 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Sniffs_Files_FileNameSniff. - * * Ensures filenames do not contain underscores. * - * @category PHP - * @package PHP_CodeSniffer - * @author John Godley + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.1.0 */ class WordPress_Sniffs_Files_FileNameSniff implements PHP_CodeSniffer_Sniff { @@ -26,7 +26,7 @@ class WordPress_Sniffs_Files_FileNameSniff implements PHP_CodeSniffer_Sniff { public function register() { return array( T_OPEN_TAG ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -51,4 +51,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Functions/DontExtractSniff.php b/WordPress/Sniffs/Functions/DontExtractSniff.php index 86bdd044ad..0c91e4587a 100644 --- a/WordPress/Sniffs/Functions/DontExtractSniff.php +++ b/WordPress/Sniffs/Functions/DontExtractSniff.php @@ -2,19 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts the usage of extract(). * - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#dont-extract + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#dont-extract * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 Previously this check was contained within WordPress_Sniffs_VIP_RestrictedFunctionsSniff. */ class WordPress_Sniffs_Functions_DontExtractSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -45,4 +45,4 @@ public function getGroups() { ); } // end getGroups() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php index eeae1eddb0..f32bfe9234 100644 --- a/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php +++ b/WordPress/Sniffs/Functions/FunctionRestrictionsSniff.php @@ -2,23 +2,23 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some functions. * - * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to - * the WordPress_AbstractFunctionRestrictionsSniff class. - * This class is left here to prevent backward-compatibility breaks for - * custom sniffs extending the old class and references to this - * sniff from custom phpcs.xml files. + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 + * @deprecated 0.10.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractFunctionRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * @see WordPress_AbstractFunctionRestrictionsSniff */ class WordPress_Sniffs_Functions_FunctionRestrictionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -39,4 +39,4 @@ public function getGroups() { return array(); } -} // end class +} // End class. diff --git a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php index ee98295cab..f339ffc183 100644 --- a/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -1,10 +1,10 @@ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff', true ) ) { @@ -14,14 +14,14 @@ /** * Enforces WordPress function name and method name format, based upon Squiz code. * - * @link https://make.wordpress.org/core/handbook/coding-standards/php/#naming-conventions + * @link https://make.wordpress.org/core/handbook/coding-standards/php/#naming-conventions * - * Last synced with parent class July 2016 at commit 916b09a. - * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author John Godley + * @since 0.1.0 + * + * Last synced with parent class July 2016 up to commit 4fea2e651109e41066a81e22e004d851fb1287f6. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/PEAR/Sniffs/NamingConventions/ValidFunctionNameSniff.php */ class WordPress_Sniffs_NamingConventions_ValidFunctionNameSniff extends PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff { @@ -173,9 +173,11 @@ protected function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $st } // end processTokenWithinScope() /** - * Returns the name of the class that the specified class implements. + * Returns the name of the interface that the specified class implements. + * + * Returns FALSE on error or if there is no implemented interface name. * - * Returns FALSE on error or if there is no implemented class name. + * @since 0.5.0 * * @param int $stackPtr The stack position of the class. * @param PHP_CodeSniffer_File $phpcsFile The stack position of the class. @@ -218,4 +220,4 @@ public function findImplementedInterfaceName( $stackPtr, $phpcsFile ) { return $name; } // end findExtendedClassName() -} // end class +} // End class. diff --git a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php index c322c3dabe..af90f1c95d 100644 --- a/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -15,11 +15,11 @@ * * Hook names invoked with `do_action_deprecated()` and `apply_filters_deprecated()` are ignored. * - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 */ class WordPress_Sniffs_NamingConventions_ValidHookNameSniff implements PHP_CodeSniffer_Sniff { @@ -69,7 +69,7 @@ public function register() { T_STRING, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -281,4 +281,4 @@ protected function transform_complex_string( $string, $regex, $transform_type = return implode( '', $output ); } // end transform_complex_string() -} // end class +} // End class. diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 655fbd8bee..7dae7edcfb 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -1,18 +1,10 @@ - * @author Marc McIntyre - * @author Weston Ruter - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'PHP_CodeSniffer_Standards_AbstractVariableSniff', true ) ) { @@ -20,19 +12,16 @@ } /** - * WordPress_Sniffs_NamingConventions_ValidVariableNameSniff. - * * Checks the naming of variables and member variables. * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @author Weston Ruter - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.9.0 + * + * Last synced with base class July 2014 at commit ed257ca0e56ad86cd2a4d6fa38ce0b95141c824f. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/NamingConventions/ValidVariableNameSniff.php */ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_CodeSniffer_Standards_AbstractVariableSniff { @@ -241,6 +230,6 @@ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $s */ static function isSnakeCase( $var_name ) { return (bool) preg_match( '/^[a-z0-9_]+$/', $var_name ); - } // end isSnakeCase() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php index e2690c16b6..b73e7d31ef 100644 --- a/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php +++ b/WordPress/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP\CodeSniffer\WordPress-Coding-Standards - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -12,11 +12,16 @@ * * If alternative PHP open tags are found, this sniff can fix both the open and close tags. * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/580 + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/580 * - * @category PHP - * @package PHP\CodeSniffer\WordPress-Coding-Standards - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 + * + * {@internal If and when the upstream PR https://github.com/squizlabs/PHP_CodeSniffer/pull/1084 + * would be merged and the WPCS minimum PHPCS version would be upped to the version + * that PR is contained in, this sniff and associated unit tests can be replaced by + * the upstream sniff Generic.PHP.DisallowAlternativePHPTags.}} */ class WordPress_Sniffs_PHP_DisallowAlternativePHPTagsSniff implements PHP_CodeSniffer_Sniff { @@ -200,7 +205,7 @@ private function find_closing_tag( PHP_CodeSniffer_File $phpcsFile, $tokens, $st * @param int $close_tag_pointer Stack pointer to the PHP close tag. * @param bool $echo Whether to add 'echo' or not. */ - private function add_changeset( $phpcsFile, $tokens, $open_tag_pointer, $close_tag_pointer, $echo = false ) { + private function add_changeset( PHP_CodeSniffer_File $phpcsFile, $tokens, $open_tag_pointer, $close_tag_pointer, $echo = false ) { // Build up the open tag replacement and make sure there's always whitespace behind it. $open_replacement = ' + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { @@ -12,13 +12,13 @@ } /** - * WordPress_Sniffs_PHP_DiscouragedFunctionsSniff. + * Discourages the use of various functions and suggests (WordPress) alternatives. * - * Discourages the use of debug functions and suggests deprecated WordPress alternatives + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author John Godley + * @since 0.1.0 + * @since 0.10.0 The checks for the POSIX functions have been replaced by the stand-alone + * sniff WordPress_Sniffs_PHP_POSIXFunctionsSniff. */ class WordPress_Sniffs_PHP_DiscouragedFunctionsSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { @@ -88,4 +88,4 @@ public function register() { return $register; } -} // end class +} // End class. diff --git a/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php b/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php index 2ab56a9a99..8a78541c70 100644 --- a/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php +++ b/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php @@ -2,21 +2,22 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Perl compatible regular expressions (PCRE, preg_ functions) should be used in preference * to their POSIX counterparts. * - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#regular-expressions - * @link http://php.net/manual/en/ref.regex.php + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#regular-expressions + * @link http://php.net/manual/en/ref.regex.php * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 Previously this check was contained within WordPress_Sniffs_VIP_RestrictedFunctionsSniff + * and the WordPress_Sniffs_PHP_DiscouragedFunctionsSniff. */ class WordPress_Sniffs_PHP_POSIXFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -66,4 +67,4 @@ public function getGroups() { ); } // end getGroups() -} // end class +} // End class. diff --git a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php index 1f42761541..0386e801f0 100644 --- a/WordPress/Sniffs/PHP/StrictComparisonsSniff.php +++ b/WordPress/Sniffs/PHP/StrictComparisonsSniff.php @@ -2,17 +2,22 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Enforces Strict Comparison checks, based upon Squiz code. * - * @category PHP - * @package PHP_CodeSniffer - * @author Matt Robinson + * @package WPCS\WordPressCodingStandards + * + * @since 0.4.0 + * + * Last synced with base class ?[unknown date]? at commit ?[unknown commit]?. + * It is currently unclear whether this sniff is actually based on Squiz code on whether the above + * reference to it is a copy/paste oversight. + * @link Possibly: https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff.php */ class WordPress_Sniffs_PHP_StrictComparisonsSniff extends WordPress_Sniff { @@ -27,7 +32,7 @@ public function register() { T_IS_NOT_EQUAL, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -46,6 +51,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addWarning( $error, $stackPtr, 'LooseComparison' ); } - } // end process() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/PHP/StrictInArraySniff.php b/WordPress/Sniffs/PHP/StrictInArraySniff.php index bda11b7932..2ef72fb9ad 100644 --- a/WordPress/Sniffs/PHP/StrictInArraySniff.php +++ b/WordPress/Sniffs/PHP/StrictInArraySniff.php @@ -2,18 +2,22 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Flag calling in_array(), array_search() and array_keys() without true as the third parameter. * - * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#using-in_array-without-strict-parameter + * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#using-in_array-without-strict-parameter * - * @category PHP - * @package PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * + * @since 0.9.0 + * @since 0.10.0 This sniff not only checks for `in_array()`, but also `array_search()` and `array_keys()`. + * The sniff no longer needlessly extends the WordPress_Sniffs_Arrays_ArrayAssignmentRestrictionsSniff + * which it didn't use. */ class WordPress_Sniffs_PHP_StrictInArraySniff implements PHP_CodeSniffer_Sniff { @@ -29,6 +33,8 @@ class WordPress_Sniffs_PHP_StrictInArraySniff implements PHP_CodeSniffer_Sniff { * @link http://php.net/array-search * @link http://php.net/array-keys * + * @since 0.10.0 + * * @var array => */ protected $array_functions = array( @@ -123,4 +129,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/PHP/YodaConditionsSniff.php b/WordPress/Sniffs/PHP/YodaConditionsSniff.php index 02e2bc0f70..f7ba541aad 100644 --- a/WordPress/Sniffs/PHP/YodaConditionsSniff.php +++ b/WordPress/Sniffs/PHP/YodaConditionsSniff.php @@ -1,20 +1,20 @@ - * @author Greg Sherwood - * @author Marc McIntyre + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_PHP_YodaConditionsSniff implements PHP_CodeSniffer_Sniff { @@ -31,7 +31,7 @@ public function register() { T_IS_NOT_IDENTICAL, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -102,4 +102,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php index a9b1fbd4bd..f2a7083983 100644 --- a/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php +++ b/WordPress/Sniffs/VIP/AdminBarRemovalSniff.php @@ -2,17 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Discourages removal of the admin bar. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#removing-the-admin-bar + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_AdminBarRemovalSniff implements PHP_CodeSniffer_Sniff { @@ -28,7 +30,7 @@ public function register() { T_DOUBLE_QUOTED_STRING, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -47,4 +49,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/CronIntervalSniff.php b/WordPress/Sniffs/VIP/CronIntervalSniff.php index 036ef5b0a7..6cec70acf7 100644 --- a/WordPress/Sniffs/VIP/CronIntervalSniff.php +++ b/WordPress/Sniffs/VIP/CronIntervalSniff.php @@ -2,17 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Flag cron schedules less than 15 minutes. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#cron-schedules-less-than-15-minutes-or-expensive-events + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_CronIntervalSniff implements PHP_CodeSniffer_Sniff { @@ -27,7 +29,7 @@ public function register() { T_DOUBLE_QUOTED_STRING, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -129,8 +131,19 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() - public function confused( $phpcsFile, $stackPtr ) { - $phpcsFile->addWarning( 'Detected changing of cron_schedules, but could not detect the interval value.', $stackPtr, 'ChangeDetected' ); - } // end confused() + /** + * Add warning about unclear cron schedule change. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + */ + public function confused( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { + $phpcsFile->addWarning( + 'Detected changing of cron_schedules, but could not detect the interval value.', + $stackPtr, + 'ChangeDetected' + ); + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php index bd19a84368..73a4c0d860 100644 --- a/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php +++ b/WordPress/Sniffs/VIP/DirectDatabaseQuerySniff.php @@ -2,19 +2,21 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Flag Database direct queries. * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#direct-database-queries + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#database-alteration * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.6.0 Removed the add_unique_message() function as it is no longer needed. */ class WordPress_Sniffs_VIP_DirectDatabaseQuerySniff implements PHP_CodeSniffer_Sniff { @@ -78,7 +80,7 @@ public function register() { T_VARIABLE, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -210,4 +212,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php index ba53a7429d..674a077793 100644 --- a/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php +++ b/WordPress/Sniffs/VIP/FileSystemWritesDisallowSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { @@ -14,11 +14,11 @@ /** * Disallow Filesystem writes. * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#filesystem-writes * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { @@ -68,6 +68,8 @@ class WordPress_Sniffs_VIP_FileSystemWritesDisallowSniff extends Generic_Sniffs_ /** * Generates the error or warning for this sniff. * + * Overloads parent addError method. + * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the forbidden function * in the token array. @@ -86,6 +88,6 @@ protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) $phpcsFile->addWarning( $error, $stackPtr, 'FileWriteDetected', $data ); } - } // end addError() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/OrderByRandSniff.php b/WordPress/Sniffs/VIP/OrderByRandSniff.php index 9e05d9aae1..158a11312c 100644 --- a/WordPress/Sniffs/VIP/OrderByRandSniff.php +++ b/WordPress/Sniffs/VIP/OrderByRandSniff.php @@ -2,18 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Flag using orderby => rand. * - * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#order-by-rand + * @link https://vip.wordpress.com/documentation/code-review-what-we-look-for/#order-by-rand * - * @category PHP - * @package PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * + * @since 0.9.0 */ class WordPress_Sniffs_VIP_OrderByRandSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { @@ -49,6 +50,6 @@ public function callback( $key, $val, $line, $group ) { } else { return false; } - } // end callback() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php index 4a6ea1ba27..807cf2c24b 100644 --- a/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php +++ b/WordPress/Sniffs/VIP/PluginMenuSlugSniff.php @@ -2,20 +2,27 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Warn about __FILE__ for page registration. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#using-__file__-for-page-registration + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_PluginMenuSlugSniff implements PHP_CodeSniffer_Sniff { + /** + * Functions which can be used to add pages to the WP Admin menu. + * + * @var array + */ public $add_menu_functions = array( 'add_menu_page', 'add_object_page', @@ -44,7 +51,7 @@ public function register() { T_STRING, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -72,6 +79,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addError( 'Using __FILE__ for menu slugs risks exposing filesystem structure.', $stackPtr, 'Using__FILE__' ); } - } // end process() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/PostsPerPageSniff.php b/WordPress/Sniffs/VIP/PostsPerPageSniff.php index 23d456cb6a..fbc22a5a36 100644 --- a/WordPress/Sniffs/VIP/PostsPerPageSniff.php +++ b/WordPress/Sniffs/VIP/PostsPerPageSniff.php @@ -2,17 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Flag returning high or infinite posts_per_page. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#no-limit-queries + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_PostsPerPageSniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { @@ -72,6 +74,6 @@ public function callback( $key, $val, $line, $group ) { return 'Detected high pagination limit, `%s` is set to `%s`'; } } - } // end callback() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php index 50ccb710ec..9cbfd3c4a7 100644 --- a/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedFunctionsSniff.php @@ -2,17 +2,20 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some functions in VIP context. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.10.0 The checks for `extract()` and the POSIX functions have been replaced by + * the stand-alone sniffs WordPress_Sniffs_Functions_DontExtractSniff and + * WordPress_Sniffs_PHP_POSIXFunctionsSniff respectively. */ class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_AbstractFunctionRestrictionsSniff { @@ -31,13 +34,14 @@ class WordPress_Sniffs_VIP_RestrictedFunctionsSniff extends WordPress_AbstractFu */ public function getGroups() { return array( - + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#switch_to_blog 'switch_to_blog' => array( 'type' => 'error', 'message' => '%s is not something you should ever need to do in a VIP theme context. Instead use an API (XML-RPC, REST) to interact with other sites if needed.', 'functions' => array( 'switch_to_blog' ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#eval-and-create_function 'create_function' => array( 'type' => 'warning', 'message' => '%s is discouraged, please use Anonymous functions instead.', @@ -46,6 +50,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#eval-and-create_function 'eval' => array( 'type' => 'error', 'message' => '%s is prohibited, please use Anonymous functions instead.', @@ -123,6 +128,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#remote-calls 'wp_remote_get' => array( 'type' => 'warning', 'message' => '%s is highly discouraged, please use vip_safe_wp_remote_get() instead.', @@ -131,6 +137,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#remote-calls 'curl' => array( 'type' => 'warning', 'message' => 'Using cURL functions is highly discouraged within VIP context. Check (Fetching Remote Data) on VIP Documentation.', @@ -139,6 +146,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#custom-roles 'custom_role' => array( 'type' => 'error', 'message' => 'Use wpcom_vip_add_role() instead of add_role()', @@ -147,6 +155,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#caching-constraints 'cookies' => array( 'type' => 'warning', 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', @@ -155,6 +164,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#working-with-wp_users-and-user_meta 'user_meta' => array( 'type' => 'error', 'message' => '%s() usage is highly discouraged, check VIP documentation on "Working with wp_users"', @@ -224,6 +234,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#use-wp_parse_url-instead-of-parse_url 'parse_url' => array( 'type' => 'warning', 'message' => '%s is discouraged due to a lack for backwards-compatibility in PHP versions; please use wp_parse_url() instead.', @@ -240,6 +251,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#serializing-data 'serialize' => array( 'type' => 'warning', 'message' => '%s Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data.', @@ -249,6 +261,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#commented-out-code-debug-code-or-output 'error_log' => array( 'type' => 'error', 'message' => '%s Debug code is not allowed on VIP Production', @@ -261,6 +274,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#use-wp_safe_redirect-instead-of-wp_redirect 'wp_redirect' => array( 'type' => 'warning', 'message' => '%s Using wp_safe_redirect(), along with the allowed_redirect_hosts filter, can help avoid any chances of malicious redirects within code. It’s also important to remember to call exit() after a redirect so that no other unwanted code is executed.', @@ -269,6 +283,7 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#mobile-detection 'wp_is_mobile' => array( 'type' => 'error', 'message' => '%s When targeting mobile visitors, jetpack_is_mobile() should be used instead of wp_is_mobile. It is more robust and works better with full page caching.', @@ -277,14 +292,16 @@ public function getGroups() { ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#encoding-values-used-when-creating-a-url-or-passed-to-add_query_arg 'urlencode' => array( 'type' => 'warning', - 'message' => '%s urlencode should only be used when dealing with legacy applications rawurlencode should now de used instead. See http://php.net/manual/en/function.rawurlencode.php and http://www.faqs.org/rfcs/rfc3986.html', + 'message' => '%s urlencode should only be used when dealing with legacy applications rawurlencode should now be used instead. See http://php.net/manual/en/function.rawurlencode.php and http://www.faqs.org/rfcs/rfc3986.html', 'functions' => array( 'rawurlencode', ), ), + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#settings-alteration 'runtime_configuration' => array( 'type' => 'error', 'message' => '%s is prohibited, changing configuration at runtime is not allowed on VIP Production.', @@ -315,4 +332,4 @@ public function getGroups() { ); } // end getGroups() -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php index cd3a48c059..51822b4d17 100644 --- a/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php +++ b/WordPress/Sniffs/VIP/RestrictedVariablesSniff.php @@ -2,17 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some variables in VIP context. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/ + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_AbstractVariableRestrictionsSniff { @@ -33,6 +35,7 @@ class WordPress_Sniffs_VIP_RestrictedVariablesSniff extends WordPress_AbstractVa */ public function getGroups() { return array( + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#working-with-wp_users-and-user_meta 'user_meta' => array( 'type' => 'error', 'message' => 'Usage of users/usermeta tables is highly discouraged in VIP context, For storing user additional user metadata, you should look at User Attributes.', @@ -41,6 +44,8 @@ public function getGroups() { '$wpdb->usermeta', ), ), + + // @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#caching-constraints 'cache_constraints' => array( 'type' => 'warning', 'message' => 'Due to using Batcache, server side based client related logic will not work, use JS instead.', @@ -53,6 +58,6 @@ public function getGroups() { ), ), ); - } // end getGroups() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php index 7901677144..b3d9510aaf 100644 --- a/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionFunctionsUsageSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { @@ -12,15 +12,13 @@ } /** - * WordPress_Sniffs_VIP_SessionFunctionsUsageSniff. - * * Discourages the use of session functions. * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#session_start-and-other-session-related-functions + * + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 */ class WordPress_Sniffs_VIP_SessionFunctionsUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { @@ -57,12 +55,24 @@ class WordPress_Sniffs_VIP_SessionFunctionsUsageSniff extends Generic_Sniffs_PHP 'session_write_close' => null, ); + /** + * Generates the error or warning for this sniff. + * + * Overloads parent addError method. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the forbidden function + * in the token array. + * @param string $function The name of the forbidden function. + * @param string $pattern The pattern used for the match. + * + * @return void + */ protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) { $data = array( $function ); $error = 'The use of PHP session function %s() is prohibited.'; $phpcsFile->addError( $error, $stackPtr, $function, $data ); + } - } // end addError() - -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php index 30e968d2b8..1db40d9d69 100644 --- a/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php +++ b/WordPress/Sniffs/VIP/SessionVariableUsageSniff.php @@ -2,22 +2,22 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Sniffs_VIP_SessionVariableUsageSniff - * * Discourages the use of the session variable. * Creating a session writes a file to the server and is unreliable in a multi-server environment. * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#session_start-and-other-session-related-functions + * + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 + * @since 0.10.0 The sniff no longer needlessly extends the Generic_Sniffs_PHP_ForbiddenFunctionsSniff + * which it didn't use. */ class WordPress_Sniffs_VIP_SessionVariableUsageSniff implements PHP_CodeSniffer_Sniff { @@ -31,7 +31,7 @@ public function register() { T_VARIABLE, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -51,6 +51,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addError( 'Usage of $_SESSION variable is prohibited.', $stackPtr, 'SessionVarsProhibited' ); } - } // end process() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php index 1d7dd024d8..843b2891a2 100644 --- a/WordPress/Sniffs/VIP/SlowDBQuerySniff.php +++ b/WordPress/Sniffs/VIP/SlowDBQuerySniff.php @@ -2,17 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Flag slow queries. + * Flag potentially slow queries. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip/code-review-what-we-look-for/#uncached-pageload + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_VIP_SlowDBQuerySniff extends WordPress_AbstractArrayAssignmentRestrictionsSniff { @@ -50,6 +52,8 @@ public function getGroups() { /** * Processes this test, when one of its tokens is encountered. * + * @since 0.10.0 + * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token * in the stack passed in $tokens. @@ -65,7 +69,7 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } parent::process( $phpcsFile, $stackPtr ); - } // end process() + } /** * Callback to process each confirmed key, to check value. @@ -80,6 +84,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { */ public function callback( $key, $val, $line, $group ) { return true; - } // end callback() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php index d7b8c76798..b0c75fb045 100644 --- a/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php +++ b/WordPress/Sniffs/VIP/SuperGlobalInputUsageSniff.php @@ -2,19 +2,20 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Flag any usage of super global input var ( _GET / _POST / etc. ) + * Flag any usage of super global input var ( _GET / _POST / etc. ). * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/79 + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/79 * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.4.0 This class now extends WordPress_Sniff. */ class WordPress_Sniffs_VIP_SuperGlobalInputUsageSniff extends WordPress_Sniff { @@ -28,7 +29,7 @@ public function register() { T_VARIABLE, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -59,6 +60,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addWarning( 'Detected access of super global var %s, probably needs manual inspection.', $stackPtr, 'AccessDetected', array( $varName ) ); } - } // end process() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php index 6e650b52ca..76e486a0e3 100644 --- a/WordPress/Sniffs/VIP/TimezoneChangeSniff.php +++ b/WordPress/Sniffs/VIP/TimezoneChangeSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ if ( ! class_exists( 'Generic_Sniffs_PHP_ForbiddenFunctionsSniff', true ) ) { @@ -12,15 +12,13 @@ } /** - * WordPress_Sniffs_VIP_TimezoneChangeSniff. + * Disallow the changing of timezone. * - * Disallow the changing of timezone + * @link http://vip.wordpress.com/documentation/use-current_time-not-date_default_timezone_set/ * - * @link http://vip.wordpress.com/documentation/use-current_time-not-date_default_timezone_set/ + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 */ class WordPress_Sniffs_VIP_TimezoneChangeSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { @@ -36,10 +34,23 @@ class WordPress_Sniffs_VIP_TimezoneChangeSniff extends Generic_Sniffs_PHP_Forbid 'date_default_timezone_set' => null, ); + /** + * Generates the error or warning for this sniff. + * + * Overloads parent addError method. + * + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the forbidden function + * in the token array. + * @param string $function The name of the forbidden function. + * @param string $pattern The pattern used for the match. + * + * @return void + */ protected function addError( $phpcsFile, $stackPtr, $function, $pattern = null ) { - $error = 'Using date_default_timezone_set() and similar isn’t allowed, instead use WP internal timezone support.'; + $error = 'Using date_default_timezone_set() and similar isn\'t allowed, instead use WP internal timezone support.'; $phpcsFile->addError( $error, $stackPtr, $function ); - } // end addError() + } -} // end class +} // End class. diff --git a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php index bc62c72459..f6c0853475 100644 --- a/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php +++ b/WordPress/Sniffs/VIP/ValidatedSanitizedInputSniff.php @@ -2,19 +2,21 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Flag any non-validated/sanitized input ( _GET / _POST / etc. ) + * Flag any non-validated/sanitized input ( _GET / _POST / etc. ). * - * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/69 * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.4.0 This class now extends WordPress_Sniff. + * @since 0.5.0 Method getArrayIndexKey() has been moved to WordPress_Sniff. */ class WordPress_Sniffs_VIP_ValidatedSanitizedInputSniff extends WordPress_Sniff { @@ -150,8 +152,6 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $phpcsFile->addError( 'Detected usage of a non-sanitized input variable: %s', $stackPtr, 'InputNotSanitized', $error_data ); } - return; - } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php index 16f8a51e2a..c243b7e0d8 100644 --- a/WordPress/Sniffs/Variables/GlobalVariablesSniff.php +++ b/WordPress/Sniffs/Variables/GlobalVariablesSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -12,12 +12,18 @@ * * Warns about usage of global variables used by WordPress * - * @category PHP - * @package WordPress_Coding_Standards - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * @since 0.4.0 This class now extends WordPress_Sniff. */ class WordPress_Sniffs_Variables_GlobalVariablesSniff extends WordPress_Sniff { + /** + * List of global WP variables. + * + * @var array + */ public $globals = array( 'comment', 'comment_alt', @@ -345,4 +351,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php index 6a2e86950e..7e6b96262b 100644 --- a/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php +++ b/WordPress/Sniffs/Variables/VariableRestrictionsSniff.php @@ -2,24 +2,24 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Restricts usage of some variables. * - * @deprecated 0.1.0 The functionality which used to be contained in this class has been moved to - * the WordPress_AbstractVariableRestrictionsSniff class. - * This class is left here to prevent backward-compatibility breaks for - * custom sniffs extending the old class and references to this - * sniff from custom phpcs.xml files. - * This file is also still used to unit test the abstract class. + * @package WPCS\WordPressCodingStandards * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @since 0.3.0 + * @deprecated 0.10.0 The functionality which used to be contained in this class has been moved to + * the WordPress_AbstractVariableRestrictionsSniff class. + * This class is left here to prevent backward-compatibility breaks for + * custom sniffs extending the old class and references to this + * sniff from custom phpcs.xml files. + * This file is also still used to unit test the abstract class. + * @see WordPress_AbstractVariableRestrictionsSniff */ class WordPress_Sniffs_Variables_VariableRestrictionsSniff extends WordPress_AbstractVariableRestrictionsSniff { @@ -42,4 +42,4 @@ public function getGroups() { return parent::$groups; } -} // end class +} // End class. diff --git a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php index 849693c557..65d5db07fb 100644 --- a/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php +++ b/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php @@ -2,19 +2,19 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Sniffs_WP_Enqueued_Resources_Sniff - * * Makes sure scripts and styles are enqueued and not explicitly echo'd. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @link https://vip.wordpress.com/documentation/vip-go/code-review-blockers-warnings-notices/#inline-resources + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 */ class WordPress_Sniffs_WP_EnqueuedResourcesSniff implements PHP_CodeSniffer_Sniff { @@ -30,7 +30,7 @@ public function register() { T_INLINE_HTML, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -55,4 +55,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/WP/I18nSniff.php b/WordPress/Sniffs/WP/I18nSniff.php index 1b7ea37c4e..815edb95cd 100644 --- a/WordPress/Sniffs/WP/I18nSniff.php +++ b/WordPress/Sniffs/WP/I18nSniff.php @@ -2,19 +2,20 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Sniffs_WP_I18nSniff + * Makes sure WP internationalization functions are used properly. * - * Makes sure internationalization functions are used properly. + * @link https://make.wordpress.org/core/handbook/best-practices/internationalization/ + * @link https://developer.wordpress.org/plugins/internationalization/ * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * + * @since 0.10.0 */ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { @@ -37,6 +38,11 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { */ static $text_domain_override; + /** + * The I18N functions in use in WP. + * + * @var array => + */ public $i18n_functions = array( 'translate' => 'simple', '__' => 'simple', @@ -58,13 +64,17 @@ class WordPress_Sniffs_WP_I18nSniff extends WordPress_Sniff { /** * These Regexes copied from http://php.net/manual/en/function.sprintf.php#93552 + * + * @var string */ - static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; + public static $sprintf_placeholder_regex = '/(?:%%|(%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFos]))/'; /** * "Unordered" means there's no position specifier: '%s', not '%2$s'. + * + * @var string */ - static $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; + public static $unordered_sprintf_placeholder_regex = '/(?:%%|(?:%[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX]))/'; /** * Returns an array of tokens this test wants to listen for. @@ -82,7 +92,7 @@ public function register() { * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. * @param int $stack_ptr The position of the current token - * in the stack passed in $tokens. + * in the stack passed in $tokens. * * @return void */ @@ -211,7 +221,7 @@ public function process( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { * Check if supplied tokens represent a translation text string literal. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $context + * @param array $context Context (@todo needs better description). * @return bool */ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $context ) { @@ -274,8 +284,10 @@ protected function check_argument_tokens( PHP_CodeSniffer_File $phpcs_file, $con * Check for inconsistencies between single and plural arguments. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $single_context - * @param array $plural_context + * @param int $stack_ptr The position of the current token + * in the stack passed in $tokens. + * @param array $single_context Single context (@todo needs better description). + * @param array $plural_context Plural context (@todo needs better description). * @return void */ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $phpcs_file, $stack_ptr, $single_context, $plural_context ) { @@ -289,7 +301,7 @@ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $ph $plural_placeholders = $plural_placeholders[0]; // English conflates "singular" with "only one", described in the codex: - // https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals + // https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals . if ( count( $single_placeholders ) < count( $plural_placeholders ) ) { $error_string = 'Missing singular placeholder, needed for some languages. See https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals'; $single_index = $single_context['tokens'][0]['token_index']; @@ -310,7 +322,7 @@ protected function compare_single_and_plural_arguments( PHP_CodeSniffer_File $ph * Check the string itself for problems. * * @param PHP_CodeSniffer_File $phpcs_file The file being scanned. - * @param array $context + * @param array $context Context (@todo needs better description). * @return void */ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { @@ -348,9 +360,11 @@ protected function check_text( PHP_CodeSniffer_File $phpcs_file, $context ) { } } - // NoEmptyStrings. - - // Strip placeholders and surrounding quotes. + /* + * NoEmptyStrings. + * + * Strip placeholders and surrounding quotes. + */ $non_placeholder_content = trim( $content, "'" ); $non_placeholder_content = preg_replace( self::$sprintf_placeholder_regex, '', $non_placeholder_content ); diff --git a/WordPress/Sniffs/WP/PreparedSQLSniff.php b/WordPress/Sniffs/WP/PreparedSQLSniff.php index 1bfcf9793a..3759a93b48 100644 --- a/WordPress/Sniffs/WP/PreparedSQLSniff.php +++ b/WordPress/Sniffs/WP/PreparedSQLSniff.php @@ -2,9 +2,9 @@ /** * WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** @@ -12,8 +12,11 @@ * * Makes sure that variables aren't directly interpolated into SQL statements. * - * @package WordPress-Coding-Standards - * @since 0.8.0 + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#formatting-sql-statements + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.8.0 */ class WordPress_Sniffs_WP_PreparedSQLSniff extends WordPress_Sniff { @@ -91,12 +94,12 @@ public function register() { /** * Processes this test, when one of its tokens is encountered. * - * @since 0.8.0 - * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * + * @since 0.8.0 + * * @return int|void */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { @@ -240,4 +243,4 @@ protected function is_wpdb_method_call( $stackPtr ) { return true; } // is_wpdb_method_call() -} // end class. +} // End class. diff --git a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php index 5d623a971c..ab2f91cae9 100755 --- a/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php @@ -1,29 +1,23 @@ - * @author Marc McIntyre - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Squiz_Sniffs_WhiteSpace_CastSpacingSniff. + * Ensure cast statements don't contain whitespace, but *are* surrounded by whitespace, based upon Squiz code. * - * Ensure cast statements don't contain whitespace. + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#space-usage * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * + * @since 0.3.0 + * + * Last synced with base class ?[unknown date]? at commit ?[unknown commit]?. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/WhiteSpace/CastSpacingSniff.php */ class WordPress_Sniffs_WhiteSpace_CastStructureSpacingSniff implements PHP_CodeSniffer_Sniff { @@ -35,7 +29,7 @@ class WordPress_Sniffs_WhiteSpace_CastStructureSpacingSniff implements PHP_CodeS public function register() { return PHP_CodeSniffer_Tokens::$castTokens; - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -80,4 +74,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { */ public $error = false; -} // end class +} // End class. diff --git a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php index 078c30a380..af6cbc56f2 100644 --- a/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -1,24 +1,24 @@ - * @author Greg Sherwood - * @author Marc McIntyre + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Squiz_Sniffs_WhiteSpace_ControlStructureSpacingSniff. + * Enforces spacing around logical operators and assignments, based upon Squiz code. + * + * @package WPCS\WordPressCodingStandards * - * Checks that any array declarations are lower case. + * @since 0.1.0 + * @since 2013-06-11 This sniff no longer supports JS. + * @since 0.3.0 This sniff now has the ability to fix most errors it flags. + * @since 0.7.0 This class now extends WordPress_Sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author John Godley - * @author Greg Sherwood - * @author Marc McIntyre + * Last synced with base class ?[unknown date]? at commit ?[unknown commit]?. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php */ class WordPress_Sniffs_WhiteSpace_ControlStructureSpacingSniff extends WordPress_Sniff { @@ -53,7 +53,7 @@ class WordPress_Sniffs_WhiteSpace_ControlStructureSpacingSniff extends WordPress /** * How many spaces should be between a T_CLOSURE and T_OPEN_PARENTHESIS. * - * function[*]() {...} + * `function[*]() {...}` * * @since 0.7.0 * @@ -81,7 +81,7 @@ public function register() { T_USE, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -526,4 +526,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php index 89941a5c76..18e3abe038 100644 --- a/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php +++ b/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -1,20 +1,26 @@ - * @author Marc McIntyre + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Modified version of Squiz operator white spacing. + * Verify operator spacing, based upon Squiz code. * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre + * "Always put spaces after commas, and on both sides of logical, comparison, string and assignment operators." + * + * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#space-usage + * + * @package WPCS\WordPressCodingStandards + * + * @since 0.1.0 + * @since 0.3.0 This sniff now has the ability to fix the issues it flags. + * + * Last synced with base class December 2008 at commit f01746fd1c89e98174b16c76efd325825eb58bf1. + * @link https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php */ class WordPress_Sniffs_WhiteSpace_OperatorSpacingSniff implements PHP_CodeSniffer_Sniff { @@ -43,7 +49,7 @@ public function register() { return $tokens; - } // end register() + } /** * Processes this sniff, when one of its tokens is encountered. @@ -76,13 +82,13 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } if ( T_BITWISE_AND === $tokens[ $stackPtr ]['code'] ) { - // If its not a reference, then we expect one space either side of the + /* + // If it's not a reference, then we expect one space either side of the // bitwise operator. - // if ( false === $phpcsFile->isReference( $stackPtr ) ) { - // @todo Implement or remove ? - - // } // end if - + if ( false === $phpcsFile->isReference( $stackPtr ) ) { + // @todo Implement or remove ? + } + */ return; } else { @@ -205,4 +211,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Sniffs/XSS/EscapeOutputSniff.php b/WordPress/Sniffs/XSS/EscapeOutputSniff.php index 41c749a8d0..237a9291a8 100644 --- a/WordPress/Sniffs/XSS/EscapeOutputSniff.php +++ b/WordPress/Sniffs/XSS/EscapeOutputSniff.php @@ -1,20 +1,23 @@ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Verifies that all outputted strings are escaped. * - * @link http://codex.wordpress.org/Data_Validation Data Validation on WordPress Codex + * @link http://codex.wordpress.org/Data_Validation Data Validation on WordPress Codex * - * @category PHP - * @package PHP_CodeSniffer - * @author Weston Ruter + * @package WPCS\WordPressCodingStandards + * + * @since 2013-06-11 + * @since 0.4.0 This class now extends WordPress_Sniff. + * @since 0.5.0 The various function list properties which used to be contained in this class + * have been moved to the WordPress_Sniff parent class. */ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { @@ -39,8 +42,9 @@ class WordPress_Sniffs_XSS_EscapeOutputSniff extends WordPress_Sniff { /** * Custom list of functions which escape values for output. * - * @since 0.3.0 + * @since 0.3.0 * @deprecated 0.5.0 Use $customEscapingFunctions instead. + * @see WordPress_Sniffs_XSS_EscapeOutputSniff::$customEscapingFunctions * * @var string[] */ @@ -102,7 +106,7 @@ public function register() { T_STRING, ); - } // end register() + } /** * Processes this test, when one of its tokens is encountered. @@ -347,4 +351,4 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { } // end process() -} // end class +} // End class. diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.inc b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.inc index e592293211..7f5d00841e 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.inc +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.inc @@ -1,7 +1,7 @@ 1 ); // Bad +$foo = array( 'bar' => 1 ); // Bad. -$foo['bar'] = 1; // Bad +$foo['bar'] = 1; // Bad. -$foo = 'test' . 'bar=1&taz=5&bar=2'; // Bad +$foo = 'test' . 'bar=1&taz=5&bar=2'; // Bad. diff --git a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php index bdebed3728..952516ac0f 100644 --- a/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayAssignmentRestrictionsUnitTest.php @@ -2,21 +2,22 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the ArrayAssignmentRestrictions sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_Arrays_ArrayAssignmentRestrictionsUnitTest extends AbstractSniffUnitTest { + /** + * Fill in the $groups property to test the abstract class. + */ protected function setUp() { parent::setUp(); @@ -35,10 +36,7 @@ protected function setUp() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -47,19 +45,16 @@ public function getErrorList() { 7 => 2, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc index b8357583f3..12831f7841 100644 --- a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc +++ b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc @@ -1,48 +1,48 @@ 'food'), // Bad, no spaces after opening and befoer closing paranthesis + array('post_type' => 'food'), // Bad, no spaces after opening and before closing paranthesis. // ... array( 'post_status' => 'private', - 'orderby' => 'title' // Bad, no comma at the ending + 'orderby' => 'title' // Bad, no comma at the ending. ) ); $query = new WP_Query( $query_vars ); $query_vars = array_merge( - array( 'post_type' => 'food' ), // Good + array( 'post_type' => 'food' ), // Good. // ... array( 'post_status' => 'private', - 'orderby' => 'title', // Good + 'orderby' => 'title', // Good. ), array( - 'closure' => function () { // Good, Closures allowed + 'closure' => function () { // Good, closures allowed. return array(); }, ), - bar( // Good, Functions allowed + bar( // Good, functions allowed. 1, 2 ) ); $query = new WP_Query( $query_vars ); -$defaults = array( 'type'=>'post' ); // Bad, no spaces before and after double arrow +$defaults = array( 'type'=>'post' ); // Bad, no spaces before and after double arrow. wp_parse_args( $args, $defaults ); class Foo { function to_markdown( $params = array() ) { - // Parse sections + // Parse sections. $section_formatters = array( 'Description' => function ( $body ) use ( $params ) { if ( isset( $params['travis_ci_url'] ) ) { @@ -69,15 +69,15 @@ class Foo { } $primary_order = array( - 'n', // null - 'b', // boolean - 'i', // integer - 'f', // float - 's', // string - 'a', // array - 'o', // object - 'r', // resource - 'p', // SPL_Types object + 'n', // Null. + 'b', // Boolean. + 'i', // Integer. + 'f', // Float. + 's', // String. + 'a', // Array. + 'o', // Object. + 'r', // Resource. + 'p', // SPL_Types object. ); $var = array( @@ -89,7 +89,7 @@ $var = array( ', ); -// This should all be good: +// This should all be good. $section_args = array( 'title' => sprintf( __( 'Sidebar: %s', 'widget-customizer' ), @@ -125,67 +125,67 @@ $actions = array( ); $custom_fields = array( - 'videoembed', // Press75 Simple Video Embedder - '_videoembed_manual', // Press75 Simple Video Embedder - '_videoembed', // Press75 Simple Video Embedder - '_premise_settings', // Premise + 'videoembed', // Press75 Simple Video Embedder. + '_videoembed_manual', // Press75 Simple Video Embedder. + '_videoembed', // Press75 Simple Video Embedder. + '_premise_settings', // Premise. ); $item_block_comment = array( 'item', - /* Some comment */ + /* Some comment. */ ); $item_multiple_line_block_comment = array( 'item', /* Some comment - over multiple lines */ + over multiple lines. */ ); $block_comment = array( - /* Just a comment */ + /* Just a comment. */ ); $comment = array( - // Just a single comment + // Just a single comment. ); $multidimensional_comments = array( 'item_block_comment' => array( 'item', - /* comment */ + /* Comment. */ ), 'block_comment' => array( - /* comment */ + /* Comment. */ ), 'item_comment' => array( 'item', - // comment + // Comment. ), 'comment' => array( - // comment + // Comment. ), - // comment + // Comment. array( 'item', - /* comment */ + /* Comment. */ ), array( - /* comment */ + /* Comment. */ ), array( 'item', - // comment + // Comment. ), array( - // comment + // Comment. ), - // comment + // Comment. ); $q = new WP_Query( array( 'meta_query' => array( - 'relation' => 'and', // OK + 'relation' => 'and', // Ok. array( 'key' => 'asdsa', 'value' => 'asds', @@ -198,7 +198,7 @@ array( /** * Doc comment. */ -// 'core' +// 'core'. ); // Multiple values in an array on a single line is allowed. diff --git a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc.fixed b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc.fixed index 23b2a7d8e7..cbe7ae78a6 100644 --- a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc.fixed +++ b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.inc.fixed @@ -1,48 +1,48 @@ 'food' ), // Bad, no spaces after opening and befoer closing paranthesis + array( 'post_type' => 'food' ), // Bad, no spaces after opening and before closing paranthesis. // ... array( 'post_status' => 'private', - 'orderby' => 'title',// Bad, no comma at the ending + 'orderby' => 'title',// Bad, no comma at the ending. ) ); $query = new WP_Query( $query_vars ); $query_vars = array_merge( - array( 'post_type' => 'food' ), // Good + array( 'post_type' => 'food' ), // Good. // ... array( 'post_status' => 'private', - 'orderby' => 'title', // Good + 'orderby' => 'title', // Good. ), array( - 'closure' => function () { // Good, Closures allowed + 'closure' => function () { // Good, closures allowed. return array(); }, ), - bar( // Good, Functions allowed + bar( // Good, functions allowed. 1, 2 ) ); $query = new WP_Query( $query_vars ); -$defaults = array( 'type' => 'post' ); // Bad, no spaces before and after double arrow +$defaults = array( 'type' => 'post' ); // Bad, no spaces before and after double arrow. wp_parse_args( $args, $defaults ); class Foo { function to_markdown( $params = array() ) { - // Parse sections + // Parse sections. $section_formatters = array( 'Description' => function ( $body ) use ( $params ) { if ( isset( $params['travis_ci_url'] ) ) { @@ -69,15 +69,15 @@ class Foo { } $primary_order = array( - 'n', // null - 'b', // boolean - 'i', // integer - 'f', // float - 's', // string - 'a', // array - 'o', // object - 'r', // resource - 'p', // SPL_Types object + 'n', // Null. + 'b', // Boolean. + 'i', // Integer. + 'f', // Float. + 's', // String. + 'a', // Array. + 'o', // Object. + 'r', // Resource. + 'p', // SPL_Types object. ); $var = array( @@ -89,7 +89,7 @@ $var = array( ', ); -// This should all be good: +// This should all be good. $section_args = array( 'title' => sprintf( __( 'Sidebar: %s', 'widget-customizer' ), @@ -125,67 +125,67 @@ $actions = array( ); $custom_fields = array( - 'videoembed', // Press75 Simple Video Embedder - '_videoembed_manual', // Press75 Simple Video Embedder - '_videoembed', // Press75 Simple Video Embedder - '_premise_settings', // Premise + 'videoembed', // Press75 Simple Video Embedder. + '_videoembed_manual', // Press75 Simple Video Embedder. + '_videoembed', // Press75 Simple Video Embedder. + '_premise_settings', // Premise. ); $item_block_comment = array( 'item', - /* Some comment */ + /* Some comment. */ ); $item_multiple_line_block_comment = array( 'item', /* Some comment - over multiple lines */ + over multiple lines. */ ); $block_comment = array( - /* Just a comment */ + /* Just a comment. */ ); $comment = array( - // Just a single comment + // Just a single comment. ); $multidimensional_comments = array( 'item_block_comment' => array( 'item', - /* comment */ + /* Comment. */ ), 'block_comment' => array( - /* comment */ + /* Comment. */ ), 'item_comment' => array( 'item', - // comment + // Comment. ), 'comment' => array( - // comment + // Comment. ), - // comment + // Comment. array( 'item', - /* comment */ + /* Comment. */ ), array( - /* comment */ + /* Comment. */ ), array( 'item', - // comment + // Comment. ), array( - // comment + // Comment. ), - // comment + // Comment. ); $q = new WP_Query( array( 'meta_query' => array( - 'relation' => 'and', // OK + 'relation' => 'and', // Ok. array( 'key' => 'asdsa', 'value' => 'asds', @@ -198,7 +198,7 @@ array( /** * Doc comment. */ -// 'core' +// 'core'. ); // Multiple values in an array on a single line is allowed. diff --git a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php index 0beec37b9f..c206bab99e 100644 --- a/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php +++ b/WordPress/Tests/Arrays/ArrayDeclarationUnitTest.php @@ -2,35 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the ArrayDeclaration sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_Arrays_ArrayDeclarationUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -43,19 +31,16 @@ public function getErrorList() { 208 => 2, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.inc b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.inc index a149f21b77..ab7fae7162 100644 --- a/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.inc +++ b/WordPress/Tests/Arrays/ArrayKeySpacingRestrictionsUnitTest.inc @@ -1,31 +1,31 @@ + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_Arrays_ArrayKeySpacingRestrictionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -41,19 +36,16 @@ public function getErrorList() { 29 => 1, 31 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/CSRF/NonceVerificationUnitTest.inc b/WordPress/Tests/CSRF/NonceVerificationUnitTest.inc index e6b612f5c8..c6eb4e9c9c 100644 --- a/WordPress/Tests/CSRF/NonceVerificationUnitTest.inc +++ b/WordPress/Tests/CSRF/NonceVerificationUnitTest.inc @@ -2,11 +2,11 @@ // Bad, needs nonce check. function bar() { - if ( ! isset( $_POST['test'] ) ) { // Bad + if ( ! isset( $_POST['test'] ) ) { // Bad. return; } - do_something( $_POST['test'] ); // Bad + do_something( $_POST['test'] ); // Bad. } // Good, has an nonce check. @@ -28,7 +28,7 @@ function foo() { // Doing other things with the request params before the nonce check is prohibited. function process() { - do_something( $_POST['foo'] ); // Bad + do_something( $_POST['foo'] ); // Bad. if ( ! isset( $_POST['test'] ) || ! wp_verify_nonce( 'some_action' ) ) { exit; @@ -41,11 +41,11 @@ class Some_Class { // Bad, needs nonce check. function bar() { - if ( ! isset( $_POST['test'] ) ) { // Bad + if ( ! isset( $_POST['test'] ) ) { // Bad. return; } - do_something( $_POST['test'] ); // Bad + do_something( $_POST['test'] ); // Bad. } // Good, has an nonce check. @@ -66,7 +66,7 @@ class Some_Class { // Doing other things with the request params before the nonce check is prohibited. function process() { - do_something( $_POST['foo'] ); // Bad + do_something( $_POST['foo'] ); // Bad. if ( ! isset( $_POST['test'] ) || ! wp_verify_nonce( 'some_action' ) ) { exit; @@ -78,20 +78,20 @@ class Some_Class { // Assignments are allowed. function foo_2() { - $_POST = array( 'a' => 'b' ); // OK - $_POST['test'] = somethin(); // OK - $_POST['settings'][ $setting ] = 'bb'; // OK + $_POST = array( 'a' => 'b' ); // OK. + $_POST['test'] = somethin(); // OK. + $_POST['settings'][ $setting ] = 'bb'; // OK. } // Particular cases can be whitelisted with a comment. function foo_3() { - bar( $_POST['var'] ); // WPCS: CSRF OK - bar( $_POST['var'] ); // Bad + bar( $_POST['var'] ); // WPCS: CSRF OK. + bar( $_POST['var'] ); // Bad. } // We need to account for when there are multiple vars in a single isset(). function foo_4() { - if ( ! isset( $_POST['foo'], $_POST['bar'], $_POST['_wpnonce'] ) ) { // OK + if ( ! isset( $_POST['foo'], $_POST['bar'], $_POST['_wpnonce'] ) ) { // OK. return; } @@ -101,8 +101,8 @@ function foo_4() { // Sanitization before the nonce check is permitted. function sanitization_allowed() { - $foo = (int) $_POST['foo']; // OK - $bar = sanitize_key( $_POST['bar'] ); // OK + $foo = (int) $_POST['foo']; // OK. + $bar = sanitize_key( $_POST['bar'] ); // OK. check_ajax_referer( "something-{$foo}-{$bar}" ); } @@ -110,8 +110,8 @@ function sanitization_allowed() { // The value must only be sanitized though. function foo_5() { - do_something( (int) $_POST['foo'] ); // Bad - do_something( sanitize_key( $_POST['bar'] ) ); // Bad + do_something( (int) $_POST['foo'] ); // Bad. + do_something( sanitize_key( $_POST['bar'] ) ); // Bad. check_ajax_referer( 'something' ); } diff --git a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php index fbc366048f..66979da9f9 100644 --- a/WordPress/Tests/CSRF/NonceVerificationUnitTest.php +++ b/WordPress/Tests/CSRF/NonceVerificationUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the NonceVerification Sniff. + * Unit test class for the NonceVerification sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author J.D. Grimes - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.5.0 */ class WordPress_Tests_CSRF_NonceVerificationUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { @@ -38,19 +33,16 @@ public function getErrorList() { 113 => 1, 114 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php index 7bbbd9ebf5..0de7389e44 100644 --- a/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php +++ b/WordPress/Tests/Classes/ClassOpeningStatementUnitTest.php @@ -2,30 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the ClassOpeningStatement sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_Classes_ClassOpeningStatementUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array + * @return array => */ public function getErrorList() { @@ -43,21 +36,18 @@ public function getErrorList() { 79 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array + * @return array => */ public function getWarningList() { return array( 51 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Classes/ValidClassNameUnitTest.inc b/WordPress/Tests/Classes/ValidClassNameUnitTest.inc index 485ad2705f..f4914ededd 100644 --- a/WordPress/Tests/Classes/ValidClassNameUnitTest.inc +++ b/WordPress/Tests/Classes/ValidClassNameUnitTest.inc @@ -1,7 +1,7 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_Classes_ValidClassNameUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( 7 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc index 03af35213e..594c0ae8b7 100644 --- a/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.1.inc @@ -34,7 +34,7 @@ class TheirMysqli implements \mysqli {} $db5 = new PDO(); $db6 - new PDO->exec(); -PDO::getAvailableDrivers() +PDO::getAvailableDrivers(); $db7 = new PDOStatement; $db8 = new \PDOStatement(); diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc index b4fad2d8e1..9536046e7a 100644 --- a/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.2.inc @@ -13,35 +13,35 @@ class DBlayer { } } -class DBextended extends DBlayer { // Bad +class DBextended extends DBlayer { // Bad. } -class DBextender implements PDO { // Ok -> resolves to \My\PDO +class DBextender implements PDO { // Ok -> resolves to \My\PDO. } -class DBextendes implements \PDO { // Bad -> fully qualified as \PDO +class DBextendes implements \PDO { // Bad -> fully qualified as \PDO. } -$db0 = new \DBlayer; // Ok - fully qualified as \DBlayer -$db1 = new DBlayer; // Bad - resolves to \My\DBlayer -$db2 = new DBlayer(); // Bad - resolves to \My\DBlayer +$db0 = new \DBlayer; // Ok - fully qualified as \DBlayer. +$db1 = new DBlayer; // Bad - resolves to \My\DBlayer. +$db2 = new DBlayer(); // Bad - resolves to \My\DBlayer. -echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer -echo DBlayer::$property; // Bad - resolves to \My\DBlayer -echo DBlayer::connect(); // Bad - resolves to \My\DBlayer +echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer. +echo DBlayer::$property; // Bad - resolves to \My\DBlayer. +echo DBlayer::connect(); // Bad - resolves to \My\DBlayer. -$db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer +$db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer. -echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer -echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer -echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer +echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer. +echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer. +echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer. -$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer +$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer. -echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer -echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer -echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer. +echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer. +echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer. -echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer -echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer -echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer +echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer. +echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer. +echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer. diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc b/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc index fd1ddf14a8..3100d1c2f7 100644 --- a/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.3.inc @@ -13,42 +13,42 @@ namespace My { } } - class DBextended extends DBlayer { // Bad + class DBextended extends DBlayer { // Bad. } - class DBextender implements PDO { // Ok -> resolves to \My\PDO + class DBextender implements PDO { // Ok -> resolves to \My\PDO. } - class DBextendes implements \PDO { // Bad -> fully qualified as \PDO + class DBextendes implements \PDO { // Bad -> fully qualified as \PDO. } - $db0 = new \DBlayer; // Ok - fully qualified as \DBlayer - $db1 = new DBlayer; // Bad - resolves to \My\DBlayer - $db2 = new DBlayer(); // Bad - resolves to \My\DBlayer + $db0 = new \DBlayer; // Ok - fully qualified as \DBlayer. + $db1 = new DBlayer; // Bad - resolves to \My\DBlayer. + $db2 = new DBlayer(); // Bad - resolves to \My\DBlayer. - echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer - echo DBlayer::$property; // Bad - resolves to \My\DBlayer - echo DBlayer::connect(); // Bad - resolves to \My\DBlayer + echo DBlayer::VERSION; // Bad - resolves to \My\DBlayer. + echo DBlayer::$property; // Bad - resolves to \My\DBlayer. + echo DBlayer::connect(); // Bad - resolves to \My\DBlayer. - $db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer + $db3 = new Yours\DBlayer; // Ok - resolves to \My\Yours\DBlayer. - echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer - echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer - echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer + echo Yours\DBlayer::VERSION; // Ok - resolves to \My\Yours\DBlayer. + echo Yours\DBlayer::$property; // Ok - resolves to \My\Yours\DBlayer. + echo Yours\DBlayer::connect(); // Ok - resolves to \My\Yours\DBlayer. - $db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer + $db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer. - echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer - echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer - echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer + echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer. + echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer. + echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer. - echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer - echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer - echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer + echo namespace\DBlayer::VERSION; // Bad - resolves to \My\DBlayer. + echo namespace\DBlayer::$property; // Bad - resolves to \My\DBlayer. + echo namespace\DBlayer::connect(); // Bad - resolves to \My\DBlayer. } -// Now we're outside the namespace, so things should work differently +// Now we're outside the namespace, so things should work differently. $db0 = new \DBlayer; // Ok. $db1 = new DBlayer; // Ok. $db2 = new DBlayer(); // Ok. @@ -57,17 +57,17 @@ echo DBlayer::VERSION; // Ok. echo DBlayer::$property; // Ok. echo DBlayer::connect(); // Ok. -$db3 = new Yours\DBlayer; // Ok - resolves to \Yours\DBlayer +$db3 = new Yours\DBlayer; // Ok - resolves to \Yours\DBlayer. -echo Yours\DBlayer::VERSION; // Ok - resolves to \Yours\DBlayer -echo Yours\DBlayer::$property; // Ok - resolves to \Yours\DBlayer -echo Yours\DBlayer::connect(); // Ok - resolves to \Yours\DBlayer +echo Yours\DBlayer::VERSION; // Ok - resolves to \Yours\DBlayer. +echo Yours\DBlayer::$property; // Ok - resolves to \Yours\DBlayer. +echo Yours\DBlayer::connect(); // Ok - resolves to \Yours\DBlayer. -$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer +$db4 = new \My\DBlayer; // Bad - fully qualified as \My\DBlayer. -echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer -echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer -echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer +echo \My\DBlayer::VERSION; // Bad - fully qualified as \My\DBlayer. +echo \My\DBlayer::$property; // Bad - fully qualified as \My\DBlayer. +echo \My\DBlayer::connect(); // Bad - fully qualified as \My\DBlayer. echo namespace\DBlayer::VERSION; // Ok. echo namespace\DBlayer::$property; // Ok. @@ -85,8 +85,8 @@ namespace AdoDb { class TestYetAgain extends Tester {} // Bad. - $db5 = new Test; // Bad - $db6 = new Tester(); // Bad + $db5 = new Test; // Bad. + $db6 = new Tester(); // Bad. } -$db7 = new Test; // Ok +$db7 = new Test; // Ok. diff --git a/WordPress/Tests/DB/RestrictedClassesUnitTest.php b/WordPress/Tests/DB/RestrictedClassesUnitTest.php index 2c8eef383f..c174c84fc4 100644 --- a/WordPress/Tests/DB/RestrictedClassesUnitTest.php +++ b/WordPress/Tests/DB/RestrictedClassesUnitTest.php @@ -2,25 +2,16 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Tests_DB_RestrictedFunctionsUnitTest + * Unit test class for the DB_RestrictedClasses sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_DB_RestrictedClassesUnitTest extends AbstractSniffUnitTest { @@ -58,12 +49,8 @@ protected function shouldSkipTest() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * * @param string $testFile The name of the file being tested. - * - * @return array(int => int) + * @return array => */ public function getErrorList( $testFile = '' ) { switch ( $testFile ) { @@ -144,14 +131,11 @@ public function getErrorList( $testFile = '' ) { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); } -} // end class +} // End class. diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc index 821abf7c38..ab973dcf17 100644 --- a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.inc @@ -1,20 +1,20 @@ mysql_info(); // ok -$y = Bar::mysql_info(); // ok -prefix_mysql_info(); // ok +$x->mysql_info(); // Ok. +$y = Bar::mysql_info(); // Ok. +prefix_mysql_info(); // Ok. /** @@ -68,11 +68,11 @@ maxdb_close(); maxdb_connect(); maxdb_errno(); maxdb_escape_string(); -maxdb_fetch_assoc +maxdb_fetch_assoc(); maxdb_init(); maxdb_num_fields(); maxdb_prepare(); -maxdb_real_query +maxdb_real_query(); maxdb_stat(); diff --git a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php index 1e70d1a433..335e2bdce2 100644 --- a/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/DB/RestrictedFunctionsUnitTest.php @@ -2,35 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Tests_DB_RestrictedFunctionsUnitTest + * Unit test class for the DB_RestrictedFunctions sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_DB_RestrictedFunctionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -87,14 +75,11 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Files/FileNameUnitTest.php b/WordPress/Tests/Files/FileNameUnitTest.php index 7770770826..20b7e51110 100644 --- a/WordPress/Tests/Files/FileNameUnitTest.php +++ b/WordPress/Tests/Files/FileNameUnitTest.php @@ -2,52 +2,37 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the FileName sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_Files_FileNameUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Functions/DontExtractUnitTest.inc b/WordPress/Tests/Functions/DontExtractUnitTest.inc index f6a12ec66f..9ed5c3d2b2 100644 --- a/WordPress/Tests/Functions/DontExtractUnitTest.inc +++ b/WordPress/Tests/Functions/DontExtractUnitTest.inc @@ -1,6 +1,6 @@ 1 ) ); // bad +extract( array( 'a' => 1 ) ); // Bad. // Similarly named functions or methods however are fine. my_extract(); // Ok. diff --git a/WordPress/Tests/Functions/DontExtractUnitTest.php b/WordPress/Tests/Functions/DontExtractUnitTest.php index de482870a2..fa06e359d8 100644 --- a/WordPress/Tests/Functions/DontExtractUnitTest.php +++ b/WordPress/Tests/Functions/DontExtractUnitTest.php @@ -2,52 +2,39 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the DontExtract sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_Functions_DontExtractUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( 3 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc index 176bcaeea3..82aaef04e5 100644 --- a/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidFunctionNameUnitTest.inc @@ -1,24 +1,24 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_NamingConventions_ValidFunctionNameUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -51,19 +39,16 @@ public function getErrorList() { 89 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php index 4afc403505..f571579194 100644 --- a/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidHookNameUnitTest.php @@ -2,32 +2,24 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the ValidHookName sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_NamingConventions_ValidHookNameUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * * @param string $testFile The name of the file being tested. - * - * @return array + * @return array => */ public function getErrorList( $testFile = 'ValidHookNameUnitTest.inc' ) { @@ -84,12 +76,8 @@ public function getErrorList( $testFile = 'ValidHookNameUnitTest.inc' ) { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * * @param string $testFile The name of the file being tested. - * - * @return array + * @return array => */ public function getWarningList( $testFile = 'ValidHookNameUnitTest.inc' ) { @@ -117,8 +105,8 @@ public function getWarningList( $testFile = 'ValidHookNameUnitTest.inc' ) { default: return array(); - } // end switch + } - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc index 3dc603c39c..80a2477d51 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -1,46 +1,46 @@ varName2; // Bad +echo $this->varName2; // Bad. echo $this->var_name2; echo $this->varname2; -echo $this->_varName2; // Bad -echo $object->varName2; // Bad +echo $this->_varName2; // Bad. +echo $object->varName2; // Bad. echo $object->var_name2; echo $object_name->varname2; -echo $object_name->_varName2; // Bad -echo $object_name->VAR_name; // Bad +echo $object_name->_varName2; // Bad. +echo $object_name->VAR_name; // Bad. echo $this->myFunction($one, $two); echo $object->myFunction($one_two); -$error = "format is \$GLOBALS['$varName']"; // Bad +$error = "format is \$GLOBALS['$varName']"; // Bad. echo $_SESSION['var_name']; echo $_FILES['var_name']; echo $_ENV['var_name']; echo $_COOKIE['var_name']; -$XML = 'hello'; // Bad -$myXML = 'hello'; // Bad -$XMLParser = 'hello'; // Bad -$xmlParser = 'hello'; // Bad +$XML = 'hello'; // Bad. +$myXML = 'hello'; // Bad. +$XMLParser = 'hello'; // Bad. +$xmlParser = 'hello'; // Bad. -$ID = 1; // Bad +$ID = 1; // Bad. $post = get_post( $x ); echo $post->ID; -echo $comment_ID; // Bad -echo $comment_post_ID; // Bad -echo $comment_author_IP; // Bad +echo $comment_ID; // Bad. +echo $comment_post_ID; // Bad. +echo $comment_author_IP; // Bad. $comment = get_comment( 1 ); echo $comment->comment_ID; @@ -96,22 +96,22 @@ class Foo { public $_public_leading_underscore; private $private_no_underscore_loading; - function Bar( $VARname ) { // Bad - $localVariable = false; // Bad - echo Some_Class::$VarName; // Bad - echo $this->VAR_name; // Bad - $_localVariable = false; // Bad - echo Some_Class::$_VarName; // Bad - echo $this->_VAR_name; // Bad + function Bar( $VARname ) { // Bad. + $localVariable = false; // Bad. + echo Some_Class::$VarName; // Bad. + echo $this->VAR_name; // Bad. + $_localVariable = false; // Bad. + echo Some_Class::$_VarName; // Bad. + echo $this->_VAR_name; // Bad. } - function Baz( $var_name ) { // Ok - $local_variable = false; // Ok - echo Some_Class::$var_name; // Ok - echo $this->var_name; // Ok - $_local_variable = false; // Ok - echo Some_Class::$_var_name; // Ok - echo $this->_var_name; // Ok + function Baz( $var_name ) { // Ok. + $local_variable = false; // Ok. + echo Some_Class::$var_name; // Ok. + echo $this->var_name; // Ok. + $_local_variable = false; // Ok. + echo Some_Class::$_var_name; // Ok. + echo $this->_var_name; // Ok. } } diff --git a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php index fbbb92876c..33cf777902 100644 --- a/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php +++ b/WordPress/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -2,36 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for WordPress_Sniffs_NamingConventions_ValidVariableNameSniff. + * Unit test class for the ValidVariableName sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Greg Sherwood - * @author Marc McIntyre - * @author Weston Ruter - * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.9.0 */ class WordPress_Tests_NamingConventions_ValidVariableNameUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array + * @return array => */ public function getErrorList() { $errors = array( @@ -85,14 +72,11 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php index f68c4a94de..e661908ef9 100644 --- a/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php +++ b/WordPress/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php @@ -2,20 +2,16 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP\CodeSniffer\WordPress-Coding-Standards - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the DisallowAlternativePHPTags sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP\CodeSniffer\WordPress-Coding-Standards - * @author Juliette Reinders Folmer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_PHP_DisallowAlternativePHPTagsUnitTest extends AbstractSniffUnitTest { @@ -49,10 +45,7 @@ protected function shouldSkipTest() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array + * @return array => */ public function getErrorList() { $errors = array( @@ -75,10 +68,7 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array + * @return array => */ public function getWarningList() { $warnings = array(); diff --git a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc index 0c1733e3b7..b86c3f0377 100644 --- a/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc +++ b/WordPress/Tests/PHP/DiscouragedFunctionsUnitTest.inc @@ -1,15 +1,15 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_PHP_DiscouragedFunctionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -68,6 +53,6 @@ public function getWarningList() { 54 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc b/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc index bad1dd5372..785779e02b 100644 --- a/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc +++ b/WordPress/Tests/PHP/POSIXFunctionsUnitTest.inc @@ -1,12 +1,12 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_PHP_POSIXFunctionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -43,19 +31,16 @@ public function getErrorList() { 26 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/PHP/StrictComparisonsUnitTest.inc b/WordPress/Tests/PHP/StrictComparisonsUnitTest.inc index 73030baf36..1cb1fe41b7 100644 --- a/WordPress/Tests/PHP/StrictComparisonsUnitTest.inc +++ b/WordPress/Tests/PHP/StrictComparisonsUnitTest.inc @@ -1,21 +1,21 @@ $true ) { // Bad +} elseif ( true <> $true ) { // Bad. echo 'False'; -} elseif ( false !== $true ) { // OK +} elseif ( false !== $true ) { // Ok. echo 'False'; } -// test for whitelisting -if ( true == $true ) { // loose comparison, OK +// Test for whitelisting. +if ( true == $true ) { // Loose comparison, OK. echo 'True'; } \ No newline at end of file diff --git a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php index 0c2e6c1888..1de1ad161e 100644 --- a/WordPress/Tests/PHP/StrictComparisonsUnitTest.php +++ b/WordPress/Tests/PHP/StrictComparisonsUnitTest.php @@ -2,46 +2,33 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the StrictComparisons sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Matt Robinson - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.4.0 */ class WordPress_Tests_PHP_StrictComparisonsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -50,6 +37,6 @@ public function getWarningList() { 12 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/PHP/StrictInArrayUnitTest.inc b/WordPress/Tests/PHP/StrictInArrayUnitTest.inc index a23ab1f3fb..4832b9d50c 100644 --- a/WordPress/Tests/PHP/StrictInArrayUnitTest.inc +++ b/WordPress/Tests/PHP/StrictInArrayUnitTest.inc @@ -1,23 +1,23 @@ in_array( 1, array( '1', 1, true ) ); // OK +$bar->in_array( 1, array( '1', 1, true ) ); // Ok. $bar-> - in_array( 1, array( '1', 1, true ) ); // OK + in_array( 1, array( '1', 1, true ) ); // Ok. -in_array(); // Error +in_array(); // Error. array_search( 1, $array, true ); // Ok. diff --git a/WordPress/Tests/PHP/StrictInArrayUnitTest.php b/WordPress/Tests/PHP/StrictInArrayUnitTest.php index 9966470356..25738ba2b8 100644 --- a/WordPress/Tests/PHP/StrictInArrayUnitTest.php +++ b/WordPress/Tests/PHP/StrictInArrayUnitTest.php @@ -2,44 +2,35 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the StrictInArray sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.9.0 */ class WordPress_Tests_PHP_StrictInArrayUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( 7 => 1, 20 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -55,6 +46,6 @@ public function getWarningList() { 39 => 1, 40 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/PHP/YodaConditionsUnitTest.inc b/WordPress/Tests/PHP/YodaConditionsUnitTest.inc index 308649e663..5b2cf5e43a 100644 --- a/WordPress/Tests/PHP/YodaConditionsUnitTest.inc +++ b/WordPress/Tests/PHP/YodaConditionsUnitTest.inc @@ -1,92 +1,92 @@ num_rows === 0 ) {} // Bad +if ( $GLOBALS['wpdb']->num_rows === 0 ) {} // Bad. -if ( $true == strtolower( $check ) ) {} // Bad +if ( $true == strtolower( $check ) ) {} // Bad. -$update = 'yes' === strtolower( $this->from_post( 'update' ) ); // OK +$update = 'yes' === strtolower( $this->from_post( 'update' ) ); // Ok. diff --git a/WordPress/Tests/PHP/YodaConditionsUnitTest.php b/WordPress/Tests/PHP/YodaConditionsUnitTest.php index f63b3a535e..bdf509621c 100644 --- a/WordPress/Tests/PHP/YodaConditionsUnitTest.php +++ b/WordPress/Tests/PHP/YodaConditionsUnitTest.php @@ -2,33 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the YodeConditions sniff. + * Unit test class for the YodaConditions sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Matt Robinson - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_PHP_YodaConditionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -47,19 +37,16 @@ public function getErrorList() { 90 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php index f894ac7fa4..0634f529bf 100644 --- a/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php +++ b/WordPress/Tests/VIP/AdminBarRemovalUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the AdminBarRemoval sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_AdminBarRemovalUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -31,19 +26,16 @@ public function getErrorList() { 5 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/CronIntervalUnitTest.inc b/WordPress/Tests/VIP/CronIntervalUnitTest.inc index 183c4eaea4..d4bc9dbd37 100644 --- a/WordPress/Tests/VIP/CronIntervalUnitTest.inc +++ b/WordPress/Tests/VIP/CronIntervalUnitTest.inc @@ -25,7 +25,7 @@ class Foo { static function my_add_quicklier( $schedules ) { $schedules['every_5_mins'] = array( - 'interval' => 20 * 60 - 15 * 60, // sneaky 5 minute interval + 'interval' => 20 * 60 - 15 * 60, // Sneaky 5 minute interval. 'display' => __( 'Once every 5 minutes' ) ); return $schedules; diff --git a/WordPress/Tests/VIP/CronIntervalUnitTest.php b/WordPress/Tests/VIP/CronIntervalUnitTest.php index f4253e37c8..bbeca06dff 100644 --- a/WordPress/Tests/VIP/CronIntervalUnitTest.php +++ b/WordPress/Tests/VIP/CronIntervalUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the CronInterval sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_CronIntervalUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -33,21 +28,18 @@ public function getErrorList() { 39 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( 37 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.inc b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.inc index 1cfe139e86..e44b14358c 100644 --- a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.inc +++ b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.inc @@ -3,9 +3,9 @@ function foo() { global $wpdb; - $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Error + Warning + $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Error + Warning. - $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); //db call okay ( No Warning, but Error for not caching! ) + $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // DB call okay ( No Warning, but Error for not caching! ). return $listofthings; } @@ -14,7 +14,7 @@ function bar() { global $wpdb; if ( ! ( $listofthings = wp_cache_get( $foo ) ) ) { - $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Warning + $listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Warning. wp_cache_set( 'foo', $listofthings ); } @@ -29,11 +29,11 @@ function baz() { $baz = wp_cache_get( 'baz' ); if ( false !== $baz ) { - $wpdb->query( 'ALTER TABLE TO ADD SOME FIELDS' ); // db call okay (but not really because ALTER TABLE!) + $wpdb->query( 'ALTER TABLE TO ADD SOME FIELDS' ); // DB call okay (but not really because ALTER TABLE!). - $wpdb->query( $wpdb->prepare( 'CREATE TABLE ' ) ); // db call okay (but not really because CREATE TABLE!) + $wpdb->query( $wpdb->prepare( 'CREATE TABLE ' ) ); // DB call okay (but not really because CREATE TABLE!). - $wpdb->query( 'SELECT QUERY' ); // db call okay + $wpdb->query( 'SELECT QUERY' ); // DB call okay. $baz = $wpdb->get_results( $wpdb->prepare( 'SELECT X FROM Y ' ) ); @@ -47,20 +47,20 @@ function quux() { global $wpdb; $quux = wp_cache_get( 'quux' ); if ( false !== $quux ) { - $quux = $wpdb->get_results( $wpdb->prepare( 'SELECT X FROM Y ' ) ); // Bad, no wp_cache_set, results in Error + Warning + $quux = $wpdb->get_results( $wpdb->prepare( 'SELECT X FROM Y ' ) ); // Bad, no wp_cache_set, results in Error + Warning. } } function barzd() { global $wpdb; - $autoload = $wpdb->get_var( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option_name ) ); // db call ok; no-cache ok + $autoload = $wpdb->get_var( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option_name ) ); // DB call ok; no-cache ok. } function taz() { /* @var wpdb $wpdb */ global $wpdb; - echo $wpdb->insert_id; // Good, no actual call, and doesn't need any caching + echo $wpdb->insert_id; // Good, no actual call, and doesn't need any caching. } // Some $wpdb methods can pass with only deleting the cache. @@ -70,14 +70,14 @@ function cache_delete_only() { $data = $where = array(); // These methods are allowed to be used with just wp_cache_delete(). - $wpdb->update( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->replace( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->delete( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->query( 'SELECT X FROM Y' ); // db call ok; OK + $wpdb->update( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->replace( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->delete( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->query( 'SELECT X FROM Y' ); // DB call ok; OK. - $wpdb->get_results( 'SELECT X FROM Y' ); // db call ok; Bad - $wpdb->get_row( 'SELECT X FROM Y' ); // db call ok; Bad - $wpdb->get_col( 'SELECT X FROM Y' ); // db call ok; Bad + $wpdb->get_results( 'SELECT X FROM Y' ); // DB call ok; Bad. + $wpdb->get_row( 'SELECT X FROM Y' ); // DB call ok; Bad. + $wpdb->get_col( 'SELECT X FROM Y' ); // DB call ok; Bad. wp_cache_delete( 'key', 'group' ); } @@ -92,13 +92,13 @@ function cache_add_instead_of_set() { $data = $where = array(); - $wpdb->update( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->replace( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->delete( $wpdb->users, $data, $where ); // db call ok; OK - $wpdb->query( 'SELECT X FROM Y' ); // db call ok; OK - $wpdb->get_row( 'SELECT X FROM Y' ); // db call ok; OK - $wpdb->get_col( 'SELECT X FROM Y' ); // db call ok; OK - $baz = $wpdb->get_results( $wpdb->prepare( 'SELECT X FROM Y ' ) ); // db call ok; OK + $wpdb->update( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->replace( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->delete( $wpdb->users, $data, $where ); // DB call ok; OK. + $wpdb->query( 'SELECT X FROM Y' ); // DB call ok; OK. + $wpdb->get_row( 'SELECT X FROM Y' ); // DB call ok; OK. + $wpdb->get_col( 'SELECT X FROM Y' ); // DB call ok; OK. + $baz = $wpdb->get_results( $wpdb->prepare( 'SELECT X FROM Y ' ) ); // DB call ok; OK. wp_cache_add( 'baz', $baz ); } diff --git a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php index aaee817c9e..4b8da25df5 100644 --- a/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php +++ b/WordPress/Tests/VIP/DirectDatabaseQueryUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the Direct Database Query. + * Unit test class for the DirectDatabaseQuery sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_DirectDatabaseQueryUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -37,15 +32,12 @@ public function getErrorList() { 80 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -55,6 +47,6 @@ public function getWarningList() { 50 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php index 575fc68a3b..0b13aa5da7 100644 --- a/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php +++ b/WordPress/Tests/VIP/FileSystemWritesDisallowUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the Filesystem writes sniff. + * Unit test class for the FileSystemWritesDisallow sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_FileSystemWritesDisallowUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -33,19 +28,16 @@ public function getErrorList() { 12 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/OrderByRandUnitTest.inc b/WordPress/Tests/VIP/OrderByRandUnitTest.inc index 289228d057..c680a98a8b 100644 --- a/WordPress/Tests/VIP/OrderByRandUnitTest.inc +++ b/WordPress/Tests/VIP/OrderByRandUnitTest.inc @@ -1,13 +1,13 @@ 'rand', // Bad - "orderby" => "rand", // Bad - "orderby" => "RAND", // Bad + 'orderby' => 'rand', // Bad. + "orderby" => "rand", // Bad. + "orderby" => "RAND", // Bad. ); -_query_posts( 'orderby=rand' ); // Bad +_query_posts( 'orderby=rand' ); // Bad. -$query_args['orderby'] = 'rand'; // Bad +$query_args['orderby'] = 'rand'; // Bad. -$query_args['orderby'] = 'date'; // OK +$query_args['orderby'] = 'date'; // Ok. diff --git a/WordPress/Tests/VIP/OrderByRandUnitTest.php b/WordPress/Tests/VIP/OrderByRandUnitTest.php index 3faadd2216..5074d859c1 100644 --- a/WordPress/Tests/VIP/OrderByRandUnitTest.php +++ b/WordPress/Tests/VIP/OrderByRandUnitTest.php @@ -2,27 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the OrderByRand sniff. * - * @category PHP - * @package PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.9.0 */ class WordPress_Tests_VIP_OrderByRandUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -33,19 +29,16 @@ public function getErrorList() { 11 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.inc b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.inc index e6669fe953..e4414e80e9 100644 --- a/WordPress/Tests/VIP/PluginMenuSlugUnitTest.inc +++ b/WordPress/Tests/VIP/PluginMenuSlugUnitTest.inc @@ -1,7 +1,7 @@ + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_PluginMenuSlugUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -31,19 +26,16 @@ public function getErrorList() { 5 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/PostsPerPageUnitTest.inc b/WordPress/Tests/VIP/PostsPerPageUnitTest.inc index 7be7fc8a39..9fd7d8aa7f 100644 --- a/WordPress/Tests/VIP/PostsPerPageUnitTest.inc +++ b/WordPress/Tests/VIP/PostsPerPageUnitTest.inc @@ -1,18 +1,18 @@ true, // Bad - 'posts_per_page' => 999, // Bad - 'posts_per_page' => -1, // Bad - 'posts_per_page' => 1, // OK - 'posts_per_page' => '1', // OK + 'nopaging' => true, // Bad. + 'posts_per_page' => 999, // Bad. + 'posts_per_page' => -1, // Bad. + 'posts_per_page' => 1, // Ok. + 'posts_per_page' => '1', // Ok. ); -_query_posts( 'nopaging=true&posts_per_page=999' ); // Bad +_query_posts( 'nopaging=true&posts_per_page=999' ); // Bad. -$query_args['posts_per_page'] = -1; // Bad -$query_args['posts_per_page'] = 1; // OK -$query_args['posts_per_page'] = '1'; // OK -$query_args['posts_per_page'] = '-1'; // Bad +$query_args['posts_per_page'] = -1; // Bad. +$query_args['posts_per_page'] = 1; // Ok. +$query_args['posts_per_page'] = '1'; // Ok. +$query_args['posts_per_page'] = '-1'; // Bad. -$query_args['my_posts_per_page'] = -1; // OK +$query_args['my_posts_per_page'] = -1; // Ok. diff --git a/WordPress/Tests/VIP/PostsPerPageUnitTest.php b/WordPress/Tests/VIP/PostsPerPageUnitTest.php index 6e991e78a8..5dfb472a00 100644 --- a/WordPress/Tests/VIP/PostsPerPageUnitTest.php +++ b/WordPress/Tests/VIP/PostsPerPageUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the PostsPerPage sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_PostsPerPageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -35,19 +30,16 @@ public function getErrorList() { 16 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc index 58926e4fa0..3cf6d6a47c 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.inc @@ -1,90 +1,90 @@ add_role(); // ok -$y = Bar::add_role(); // ok -\SomeNamespace\add_role(); // ok - -\add_role(); // bad - -get_term_link( $term ); // bad - -get_page_by_path( $path ); // bad - -get_page_by_title( $page_title ); // bad - -get_term_by( $field, $value, $taxonomy ); // bad - -get_category_by_slug( $slug ); // bad - -url_to_postid( $url ); // bad - -attachment_url_to_postid( $url ); // bad -wpcom_vip_attachment_url_to_postid( $url ); // ok - -get_tag_link(); // error -get_category_link(); // error -get_cat_ID(); // error -url_to_post_id(); // error -attachment_url_to_postid(); // error -get_posts(); // warning -wp_get_recent_posts(); // warning - -get_children(); // warning -wp_get_post_terms(); // error -wp_get_post_categories(); // error -wp_get_post_tags(); // error -wp_get_object_terms(); // error -term_exists(); // error -count_user_posts(); // error -wp_old_slug_redirect(); // error -get_adjacent_post(); // error -get_previous_post(); // error -get_next_post(); // error -parse_url( 'http://example.com/' ); // warning - -dl(); // error -error_reporting(); // error -ini_alter(); // error -ini_restore(); // error -ini_set(); // error -magic_quotes_runtime(); // error -set_magic_quotes_runtime(); // error -apache_setenv(); // error -putenv(); // error -set_include_path(); // error -restore_include_path(); // error -phpinfo(); // error - -PHPINFO(); // error -CURL_getinfo(); // error - -curlyhair(); // ok +$x->add_role(); // Ok. +$y = Bar::add_role(); // Ok. +\SomeNamespace\add_role(); // Ok. + +\add_role(); // Bad. + +get_term_link( $term ); // Bad. + +get_page_by_path( $path ); // Bad. + +get_page_by_title( $page_title ); // Bad. + +get_term_by( $field, $value, $taxonomy ); // Bad. + +get_category_by_slug( $slug ); // Bad. + +url_to_postid( $url ); // Bad. + +attachment_url_to_postid( $url ); // Bad. +wpcom_vip_attachment_url_to_postid( $url ); // Ok. + +get_tag_link(); // Error. +get_category_link(); // Error. +get_cat_ID(); // Error. +url_to_post_id(); // Error. +attachment_url_to_postid(); // Error. +get_posts(); // Warning. +wp_get_recent_posts(); // Warning. + +get_children(); // Warning. +wp_get_post_terms(); // Error. +wp_get_post_categories(); // Error. +wp_get_post_tags(); // Error. +wp_get_object_terms(); // Error. +term_exists(); // Error. +count_user_posts(); // Error. +wp_old_slug_redirect(); // Error. +get_adjacent_post(); // Error. +get_previous_post(); // Error. +get_next_post(); // Error. +parse_url( 'http://example.com/' ); // Warning. + +dl(); // Error. +error_reporting(); // Error. +ini_alter(); // Error. +ini_restore(); // Error. +ini_set(); // Error. +magic_quotes_runtime(); // Error. +set_magic_quotes_runtime(); // Error. +apache_setenv(); // Error. +putenv(); // Error. +set_include_path(); // Error. +restore_include_path(); // Error. +phpinfo(); // Error. + +PHPINFO(); // Error. +CURL_getinfo(); // Error. + +curlyhair(); // Ok. diff --git a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php index 88791f35b9..9adb6c76c4 100644 --- a/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedFunctionsUnitTest.php @@ -2,33 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the VIP_RestrictedFunctions sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_RestrictedFunctionsUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -79,10 +69,7 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -99,6 +86,6 @@ public function getWarningList() { 88 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.inc b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.inc index 4c6d513f2a..61e919117e 100644 --- a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.inc +++ b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.inc @@ -1,19 +1,19 @@ users"; // bad +$query = "SELECT * FROM $wpdb->users"; // Bad. -$wp_db->update( $wpdb->users, array( 'displayname' => 'Kanobe!' ), array( 'ID' => 1 ) ); // bad +$wp_db->update( $wpdb->users, array( 'displayname' => 'Kanobe!' ), array( 'ID' => 1 ) ); // Bad. -$query = "SELECT * FROM $wpdb->usermeta"; // bad +$query = "SELECT * FROM $wpdb->usermeta"; // Bad. -$wp_db->update( $wpdb->usermeta, array( 'meta_value' => 'bar!' ), array( 'user_id' => 1, 'meta_key' => 'foo' ) ); // bad +$wp_db->update( $wpdb->usermeta, array( 'meta_value' => 'bar!' ), array( 'user_id' => 1, 'meta_key' => 'foo' ) ); // Bad. -$query = "SELECT * FROM $wpdb->posts"; // ok +$query = "SELECT * FROM $wpdb->posts"; // Ok. -if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // bad - foo( $_SERVER['HTTP_USER_AGENT'] ); // bad +if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // Bad. + foo( $_SERVER['HTTP_USER_AGENT'] ); // Bad. } -$x = $_COOKIE['bar']; // bad +$x = $_COOKIE['bar']; // Bad. -$y = $_SERVER['REQUEST_URI']; // ok +$y = $_SERVER['REQUEST_URI']; // Ok. diff --git a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php index 20b8fb0143..b7d0e0b6b2 100644 --- a/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php +++ b/WordPress/Tests/VIP/RestrictedVariablesUnitTest.php @@ -2,33 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the VIP_RestrictedVariables sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_RestrictedVariablesUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -38,15 +28,12 @@ public function getErrorList() { 9 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -55,6 +42,6 @@ public function getWarningList() { 17 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php index 8516abd709..0f2c70fd07 100644 --- a/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionFunctionsUsageUnitTest.php @@ -2,47 +2,39 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the PHP Session functions usage + * Unit test class for the SessionFunctionsUsage sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_SessionFunctionsUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( 3 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php index c6cc975887..102afe5a54 100644 --- a/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php +++ b/WordPress/Tests/VIP/SessionVariableUsageUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Tests_VIP_SessionVariableUsageUnitTest + * Unit test class for the SessionVariableUsage sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_SessionVariableUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -31,19 +26,16 @@ public function getErrorList() { 4 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php index 07b3b00a9b..57a0c4b5e8 100644 --- a/WordPress/Tests/VIP/SlowDBQueryUnitTest.php +++ b/WordPress/Tests/VIP/SlowDBQueryUnitTest.php @@ -2,41 +2,33 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the SlowDBQuery sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_SlowDBQueryUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -48,6 +40,6 @@ public function getWarningList() { 30 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc index 19150dd26c..ecb1315625 100644 --- a/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc +++ b/WordPress/Tests/VIP/SuperGlobalInputUsageUnitTest.inc @@ -2,7 +2,7 @@ foo( $_GET['bar'] ); -foo( $_GET['whitelisted'] ); // input var okay +foo( $_GET['whitelisted'] ); // Input var okay. foo( $_POST['whitelisted_with_prefix'] ); // WPCS: input var okay. @@ -10,13 +10,11 @@ if ( $_GET['test'] && foo() && $bar ) { // input var okay taz(); } -bar( $_POST['foo'] ); // warning +bar( $_POST['foo'] ); // Warning. -quux( $_REQUEST['quux'] ); // warning +quux( $_REQUEST['quux'] ); // Warning. -$_REQUEST['wp_customize'] = 'on'; // ok +$_REQUEST['wp_customize'] = 'on'; // Ok. // Issue: https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/542 if ( isset( $_GET['updated'] ) ) { // input var okay ?> - - - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_SuperGlobalInputUsageUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -44,6 +36,6 @@ public function getWarningList() { 13 => 1, 15 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/TimezoneChangeUnitTest.inc b/WordPress/Tests/VIP/TimezoneChangeUnitTest.inc index f0de5d8c4f..4e38791f9b 100644 --- a/WordPress/Tests/VIP/TimezoneChangeUnitTest.inc +++ b/WordPress/Tests/VIP/TimezoneChangeUnitTest.inc @@ -1,6 +1,6 @@ setTimezone( new DateTimeZone( 'America/Toronto' ) ); // Yay! diff --git a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php index 48247224a6..a88b4923b4 100644 --- a/WordPress/Tests/VIP/TimezoneChangeUnitTest.php +++ b/WordPress/Tests/VIP/TimezoneChangeUnitTest.php @@ -2,47 +2,39 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * WordPress_Tests_VIP_TimezoneChangeUnitTest + * Unit test class for the TimezoneChange sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_TimezoneChangeUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( 3 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.inc b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.inc index 4659c0e39c..0249040471 100644 --- a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.inc +++ b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.inc @@ -1,13 +1,13 @@ $value ) { // .. } -unset( $_GET['test'] ); // ok +unset( $_GET['test'] ); // Ok. -output( "some string {$_POST['some_var']}" ); // Bad +output( "some string {$_POST['some_var']}" ); // Bad. -echo (int) $_GET['test']; // ok -some_func( $some_arg, (int) $_GET['test'] ); // ok +echo (int) $_GET['test']; // Ok. +some_func( $some_arg, (int) $_GET['test'] ); // Ok. function zebra() { if ( isset( $_GET['foo'], $_POST['bar'] ) ) { - echo sanitize_text_field( wp_unslash( $_POST['bar'] ) ); // ok + echo sanitize_text_field( wp_unslash( $_POST['bar'] ) ); // Ok. } } echo $_GET['test']; // WPCS: sanitization OK. -echo array_map( 'sanitize_text_field', wp_unslash( $_GET['test'] ) ); // OK -echo array_map( 'foo', wp_unslash( $_GET['test'] ) ); // Bad -echo array_map( $something, wp_unslash( $_GET['test'] ) ); // Bad -echo array_map( array( $obj, 'func' ), wp_unslash( $_GET['test'] ) ); // Bad -echo array_map( array( $obj, 'sanitize_text_field' ), wp_unslash( $_GET['test'] ) ); // Bad +echo array_map( 'sanitize_text_field', wp_unslash( $_GET['test'] ) ); // Ok. +echo array_map( 'foo', wp_unslash( $_GET['test'] ) ); // Bad. +echo array_map( $something, wp_unslash( $_GET['test'] ) ); // Bad. +echo array_map( array( $obj, 'func' ), wp_unslash( $_GET['test'] ) ); // Bad. +echo array_map( array( $obj, 'sanitize_text_field' ), wp_unslash( $_GET['test'] ) ); // Bad. // Sanitized but not validated. -$foo = (int) $_POST['foo6']; // Bad +$foo = (int) $_POST['foo6']; // Bad. // Non-assignment checks are OK. -if ( 'bar' === $_POST['foo'] ) {} // OK -if ( $_GET['test'] != 'a' ) {} // OK -if ( 'bar' === do_something( wp_unslash( $_POST['foo'] ) ) ) {} // Bad +if ( 'bar' === $_POST['foo'] ) {} // Ok. +if ( $_GET['test'] != 'a' ) {} // Ok. +if ( 'bar' === do_something( wp_unslash( $_POST['foo'] ) ) ) {} // Bad. -switch ( $_POST['foo'] ) {} // OK -switch ( do_something( wp_unslash( $_POST['foo'] ) ) ) {} // Bad +switch ( $_POST['foo'] ) {} // Ok. +switch ( do_something( wp_unslash( $_POST['foo'] ) ) ) {} // Bad. // Sanitization is required even when the value is being escaped. -echo esc_html( wp_unslash( $_POST['foo'] ) ); // Bad -echo esc_html( sanitize_text_field( wp_unslash( $_POST['foo'] ) ) ); // OK +echo esc_html( wp_unslash( $_POST['foo'] ) ); // Bad. +echo esc_html( sanitize_text_field( wp_unslash( $_POST['foo'] ) ) ); // Ok. -$current_tax_slug = isset( $_GET['a'] ) ? sanitize_key( $_GET['a'] ) : false; // OK +$current_tax_slug = isset( $_GET['a'] ) ? sanitize_key( $_GET['a'] ) : false; // Ok. $current_tax_slug = isset( $_GET['a'] ) ? $_GET['a'] : false; // Bad x 2 -$current_tax_slug = isset( $_GET['a'] ) ? wp_unslash( $_GET['a'] ) : false; // Bad -$current_tax_slug = isset( $_GET['a'] ) ? sanitize_text_field( wp_unslash( $_GET['a'] ) ) : false; // OK +$current_tax_slug = isset( $_GET['a'] ) ? wp_unslash( $_GET['a'] ) : false; // Bad. +$current_tax_slug = isset( $_GET['a'] ) ? sanitize_text_field( wp_unslash( $_GET['a'] ) ) : false; // Ok. -echo sanitize_text_field( $_POST['foo545'] ); // Error for no validation, unslashing -echo array_map( 'sanitize_text_field', $_GET['test'] ); // Bad, no unslashing -echo array_map( 'sanitize_key', $_GET['test'] ); // OK +echo sanitize_text_field( $_POST['foo545'] ); // Error for no validation, unslashing. +echo array_map( 'sanitize_text_field', $_GET['test'] ); // Bad, no unslashing. +echo array_map( 'sanitize_key', $_GET['test'] ); // Ok. -foo( absint( $_GET['foo'] ) ); // OK -$ids = array_map( 'absint', $_GET['test'] ); // OK +foo( absint( $_GET['foo'] ) ); // Ok. +$ids = array_map( 'absint', $_GET['test'] ); // Ok. -if ( is_array( $_GET['test'] ) ) {} // OK +if ( is_array( $_GET['test'] ) ) {} // Ok. -output( "some string \$_POST[some_var]" ); // Ok -output( "some string \\$_POST[some_var] $_GET[evil]" ); // Bad 2 +output( "some string \$_POST[some_var]" ); // Ok. +output( "some string \\$_POST[some_var] $_GET[evil]" ); // Bad x2. diff --git a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php index 1313dcd1f9..9b9cc8f113 100644 --- a/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php +++ b/WordPress/Tests/VIP/ValidatedSanitizedInputUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * Unit test class for the ValidatedSanitizedInputSniff + * Unit test class for the ValidatedSanitizedInput sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_VIP_ValidatedSanitizedInputUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -48,19 +43,16 @@ public function getErrorList() { 114 => 2, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Variables/GlobalVariablesUnitTest.inc b/WordPress/Tests/Variables/GlobalVariablesUnitTest.inc index 30e3cd8310..4535a7bcc1 100644 --- a/WordPress/Tests/Variables/GlobalVariablesUnitTest.inc +++ b/WordPress/Tests/Variables/GlobalVariablesUnitTest.inc @@ -6,4 +6,4 @@ global $wpdb; $wpdb = 'test'; global $post; -$post = get_post( 1 ); // override ok \ No newline at end of file +$post = get_post( 1 ); // Override ok. \ No newline at end of file diff --git a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php index 2881082b4a..dee8ca0fcf 100644 --- a/WordPress/Tests/Variables/GlobalVariablesUnitTest.php +++ b/WordPress/Tests/Variables/GlobalVariablesUnitTest.php @@ -2,28 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the GlobalVariables sniff. * - * @category PHP - * @package WordPress_Coding_Standards - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_Variables_GlobalVariablesUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -31,19 +26,16 @@ public function getErrorList() { 6 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.inc b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.inc index 1e171ec302..0038124db3 100644 --- a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.inc +++ b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.inc @@ -1,25 +1,25 @@ bar ); // Matches: '$foo->bar' +test( $foo->bar ); // Matches: '$foo->bar'. -$foo->bar(); // Ignored, this is a function not a variable +$foo->bar(); // Ignored, this is a function not a variable. -$foo->bar_method(); // Ignored +$foo->bar_method(); // Ignored. -FOO::var; // Matches: 'FOO::var' +FOO::var; // Matches: 'FOO::var'. FOO::var_test; -FOO::reg; // Matches: 'FOO::reg*' +FOO::reg; // Matches: 'FOO::reg*'. -FOO::regex; // Matches: 'FOO::reg*' +FOO::regex; // Matches: 'FOO::reg*'. -FOO::var(); // Ignored +FOO::var(); // Ignored. -FOO::$static; // Matches: 'FOO::$static' +FOO::$static; // Matches: 'FOO::$static'. -$foo['test']; // Matches: '$foo['test']' +$foo['test']; // Matches: '$foo['test']'. -$foo["test"]; // Matches: '$foo['test']' AND $foo['test'] +$foo["test"]; // Matches: '$foo['test']' AND $foo['test']. diff --git a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php index 930a003bdb..9684a9a819 100644 --- a/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php +++ b/WordPress/Tests/Variables/VariableRestrictionsUnitTest.php @@ -2,21 +2,22 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. + * Unit test class for the VariableRestrictions sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_Variables_VariableRestrictionsUnitTest extends AbstractSniffUnitTest { + /** + * Fill in the $groups property to test the abstract class. + */ protected function setUp() { parent::setUp(); @@ -43,10 +44,7 @@ protected function setUp() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -59,19 +57,16 @@ public function getErrorList() { 23 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php index 24dfec7f35..31255edea5 100644 --- a/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php +++ b/WordPress/Tests/WP/EnqueuedResourcesUnitTest.php @@ -2,17 +2,16 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the EnqueuedResources sniff. * - * @category PHP - * @package PHP_CodeSniffer - * @author Shady Sharaf + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_WP_EnqueuedResourcesUnitTest extends AbstractSniffUnitTest { @@ -30,10 +29,7 @@ protected function shouldSkipTest() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -45,19 +41,16 @@ public function getErrorList() { 11 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/WP/I18nUnitTest.inc b/WordPress/Tests/WP/I18nUnitTest.inc index 2a881d88f6..9743060a06 100644 --- a/WordPress/Tests/WP/I18nUnitTest.inc +++ b/WordPress/Tests/WP/I18nUnitTest.inc @@ -1,46 +1,46 @@ + * @package WPCS\WordPressCodingStandards + * @since 0.10.0 */ class WordPress_Tests_WP_I18nUnitTest extends AbstractSniffUnitTest { + /** + * Fill in the $text_domain_override property to test domain check functionality. + */ protected function setUp() { // @todo Should be possible via self::$phpcs->setSniffProperty( 'WordPress_Sniffs_WP_I18nSniff', 'text_domain', 'my-slug' ); WordPress_Sniffs_WP_I18nSniff::$text_domain_override = 'my-slug'; @@ -25,10 +27,7 @@ protected function setUp() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -87,10 +86,7 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -101,6 +97,6 @@ public function getWarningList() { 102 => 1, 103 => 1, ); - } // end getWarningList() + } -} // end class. +} // End class. diff --git a/WordPress/Tests/WP/PreparedSQLUnitTest.inc b/WordPress/Tests/WP/PreparedSQLUnitTest.inc index db3d5289ea..ff20f58be8 100644 --- a/WordPress/Tests/WP/PreparedSQLUnitTest.inc +++ b/WordPress/Tests/WP/PreparedSQLUnitTest.inc @@ -1,26 +1,26 @@ query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . $_GET['title'] . "';" ); // Bad -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '{$_GET['title']}';" ); // Bad -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '$var';" ); // Bad -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE 'Hello World!';" ); // OK -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '{$_GET['title']}';" ) ); // Bad -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '$var';" ) ); // Bad -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE %s;", $_GET['title'] ) ); // OK +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . $_GET['title'] . "';" ); // Bad. +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '{$_GET['title']}';" ); // Bad. +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '$var';" ); // Bad. +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE 'Hello World!';" ); // Ok. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '{$_GET['title']}';" ) ); // Bad. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '$var';" ) ); // Bad. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE %s;", $_GET['title'] ) ); // Ok. $wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . $escaped_var . "';" ); // WPCS: unprepared SQL OK. $wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '{$escaped_var}';" ); // WPCS: unprepared SQL OK. -$wpdb->query( $wpdb->prepare( "SELECT SUBSTRING( post_name, %d + 1 ) REGEXP '^[0-9]+$'", array( 123 ) ) ); // OK -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \$_GET var can be evil.' AND ID = %s", array( 123 ) ) ); // OK -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The $_GET[foo] var is evil.' AND ID = %s", array( 123 ) ) ); // Bad -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \\$_GET[foo]// var is evil again.' AND ID = %s", array( 123 ) ) ); // Bad -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \$_GET var can be evil, but $_GET[foo] var is evil.' AND ID = %s", array( 123 ) ) ); // Bad +$wpdb->query( $wpdb->prepare( "SELECT SUBSTRING( post_name, %d + 1 ) REGEXP '^[0-9]+$'", array( 123 ) ) ); // Ok. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \$_GET var can be evil.' AND ID = %s", array( 123 ) ) ); // Ok. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The $_GET[foo] var is evil.' AND ID = %s", array( 123 ) ) ); // Bad. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \\$_GET[foo]// var is evil again.' AND ID = %s", array( 123 ) ) ); // Bad. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = 'The \$_GET var can be evil, but $_GET[foo] var is evil.' AND ID = %s", array( 123 ) ) ); // Bad. -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ); // Bad -$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ) ); // Bad +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ); // Bad. +$wpdb->query( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ) ); // Bad. -$wpdb->query( "SELECT * FROM " . $wpdb->posts . " WHERE post_title LIKE 'foo';" ); // OK +$wpdb->query( "SELECT * FROM " . $wpdb->posts . " WHERE post_title LIKE 'foo';" ); // Ok. // All OK. $all_post_meta = $wpdb->get_results( $wpdb->prepare( sprintf( @@ -29,5 +29,5 @@ $all_post_meta = $wpdb->get_results( $wpdb->prepare( sprintf( implode( ',', array_fill( 0, count( $post_ids ), '%d' ) ) ), $post_ids ) ); -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . esc_sql( $foo ) . "';" ); // OK -$wpdb->query( "SELECT * FROM $wpdb->posts WHERE ID = " . absint( $foo ) . ";" ); // OK +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . esc_sql( $foo ) . "';" ); // Ok. +$wpdb->query( "SELECT * FROM $wpdb->posts WHERE ID = " . absint( $foo ) . ";" ); // Ok. diff --git a/WordPress/Tests/WP/PreparedSQLUnitTest.php b/WordPress/Tests/WP/PreparedSQLUnitTest.php index 74aa6e6eb8..6058ae70d0 100644 --- a/WordPress/Tests/WP/PreparedSQLUnitTest.php +++ b/WordPress/Tests/WP/PreparedSQLUnitTest.php @@ -2,20 +2,25 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the PreparedSQL sniff. * - * @since 0.8.0 + * @package WPCS\WordPressCodingStandards + * @since 0.8.0 */ class WordPress_Tests_WP_PreparedSQLUnitTest extends AbstractSniffUnitTest { /** + * Returns the lines where errors should occur. + * * @since 0.8.0 + * + * @return array => */ public function getErrorList() { return array( @@ -30,13 +35,18 @@ public function getErrorList() { 20 => 1, 21 => 1, ); - } // end getErrorList() + } /** + * Returns the lines where warnings should occur. + * * @since 0.8.0 + * + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() -} // end class. + } + +} // End class. diff --git a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.inc b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.inc index 2601356fa2..f718db10e5 100644 --- a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.inc +++ b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.inc @@ -7,7 +7,7 @@ $bool1 = (bool)$bool; $bool2 = (bool) $bool; $int1 = (int)$int; -$int2 = (int) $int +$int2 = (int) $int; $obj1 = ( object )$object; $obj2 = (object) $object; diff --git a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php index a78556f889..28bf974b43 100644 --- a/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php +++ b/WordPress/Tests/WhiteSpace/CastStructureSpacingUnitTest.php @@ -2,46 +2,33 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the CastStructureSpacing sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Matt Robinson - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 0.3.0 */ class WordPress_Tests_WhiteSpace_CastStructureSpacingUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array(); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array( @@ -54,6 +41,6 @@ public function getWarningList() { 21 => 1, ); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc index 076a4d744b..e5216cb8c8 100644 --- a/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc +++ b/WordPress/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc @@ -1,31 +1,31 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_WhiteSpace_ControlStructureSpacingUnitTest extends AbstractSniffUnitTest { @@ -38,10 +29,7 @@ protected function shouldSkipTest() { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { $ret = array( @@ -69,8 +57,9 @@ public function getErrorList() { 98 => 1, ); - // Uncomment when "$blank_line_check" parameter will be "true" by default. /* + Uncomment when "$blank_line_check" parameter will be "true" by default. + $ret[29] += 1; $ret[33] = 1; $ret[36] = 1; @@ -84,14 +73,11 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.inc b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.inc index 82162e874c..bee440f694 100644 --- a/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.inc +++ b/WordPress/Tests/WhiteSpace/OperatorSpacingUnitTest.inc @@ -1,20 +1,20 @@ - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_WhiteSpace_OperatorSpacingUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -40,19 +28,16 @@ public function getErrorList() { 49 => 1, ); - } // end getErrorList() + } /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.inc b/WordPress/Tests/XSS/EscapeOutputUnitTest.inc index 0adf1ebf8b..c009fe2349 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.inc +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.inc @@ -1,25 +1,25 @@ -

-

-

+

+

+

'; -echo ent2ncr( $text ); // Bad +echo ent2ncr( $text ); // Bad. echo number_format( 1024 ); echo ent2ncr( esc_html( $_data ) ); -echo $foo ? $foo : 'no foo'; // Bad -echo empty( $foo ) ? 'no foo' : $foo; // Bad -echo $foo ? esc_html( $foo ) : 'no foo'; // OK +echo $foo ? $foo : 'no foo'; // Bad. +echo empty( $foo ) ? 'no foo' : $foo; // Bad. +echo $foo ? esc_html( $foo ) : 'no foo'; // Ok. -echo 4; // OK +echo 4; // Ok. -exit( $foo ); // Bad -exit( esc_html( $foo ) ); // OK +exit( $foo ); // Bad. +exit( esc_html( $foo ) ); // Ok. -die( $foo ); // Bad -die( esc_html( $foo ) ); // OK +die( $foo ); // Bad. +die( esc_html( $foo ) ); // Ok. -printf( 'Hello %s', $foo ); // Bad -printf( 'Hello %s', esc_html( $foo ) ); // OK -printf( 'Hello %s! Hi %s!', esc_html( $foo ), $bar ); // Bad +printf( 'Hello %s', $foo ); // Bad. +printf( 'Hello %s', esc_html( $foo ) ); // Ok. +printf( 'Hello %s! Hi %s!', esc_html( $foo ), $bar ); // Bad. -vprintf( 'Hello %s', array( $foo ) ); // Bad -vprintf( 'Hello %s', array( esc_html( $foo ) ) ); // OK +vprintf( 'Hello %s', array( $foo ) ); // Bad. +vprintf( 'Hello %s', array( esc_html( $foo ) ) ); // Ok. // The below checks that functions which are marked as needed further sanitization // don't spill over into later arguments when nested in a function call. There was @@ -81,12 +81,12 @@ vprintf( 'Hello %s', array( esc_html( $foo ) ) ); // OK // is marked as needing sanitization. do_something( _x( 'Some string', 'context', 'domain' ) - , array( $foo ) // OK + , array( $foo ) // Ok. ); // There was a bug where an empty exit followed by other code would give an error. if ( ! defined( 'ABSPATH' ) ) { - exit; // OK + exit; // Ok. } else { other(); } @@ -98,85 +98,85 @@ printf( // There were other long arguments down here "in real life", which is why this was multi-line. ); -wp_die( $message ); // Bad -wp_die( esc_html( $message ) ); // OK -wp_die( esc_html( $message ), $title ); // Bad -wp_die( esc_html( $message ), esc_html( $title ) ); // OK -wp_die( esc_html( $message ), '', array( 'back_link' => true ) ); // OK -wp_die( esc_html( $message ), '', array( 'back_link' => false ) ); // OK -wp_die( esc_html( $message ), '', array( 'response' => 200 ) ); // OK +wp_die( $message ); // Bad. +wp_die( esc_html( $message ) ); // Ok. +wp_die( esc_html( $message ), $title ); // Bad. +wp_die( esc_html( $message ), esc_html( $title ) ); // Ok. +wp_die( esc_html( $message ), '', array( 'back_link' => true ) ); // Ok. +wp_die( esc_html( $message ), '', array( 'back_link' => false ) ); // Ok. +wp_die( esc_html( $message ), '', array( 'response' => 200 ) ); // Ok. -echo '

', esc_html( $foo ), '

'; // OK -echo 'a', 'b'; // OK -echo 'Hello, ', $foo; // Bad -echo esc_html( $foo ), $bar; // Bad -echo (int) $foo, $bar; // Bad -echo (int) get_post_meta( $post_id, SOME_NUMBER, true ), do_something( $else ); // Bad +echo '

', esc_html( $foo ), '

'; // Ok. +echo 'a', 'b'; // Ok. +echo 'Hello, ', $foo; // Bad. +echo esc_html( $foo ), $bar; // Bad. +echo (int) $foo, $bar; // Bad. +echo (int) get_post_meta( $post_id, SOME_NUMBER, true ), do_something( $else ); // Bad. -wp_die( -1 ); // OK +wp_die( -1 ); // Ok. ?> -

- - +

+ + ' . sprintf( esc_html__( 'Some text -> %sLink text%s', 'textdomain' ), '', '' ). '

'; // OK +echo '

' . sprintf( esc_html__( 'Some text -> %sLink text%s', 'textdomain' ), '', '' ). '

'; // Ok. -echo '
' . sprintf( esc_html__( 'Found %d results', 'textdomain' ), (int) $result_count ) . '

'; // OK +echo '
' . sprintf( esc_html__( 'Found %d results', 'textdomain' ), (int) $result_count ) . '

'; // Ok. -echo sprintf( 'Hello %s', $foo ); // Bad -echo sprintf( 'Hello %s', esc_html( $foo ) ); // OK -echo sprintf( 'Hello %s! Hi %s!', esc_html( $foo ), $bar ); // Bad +echo sprintf( 'Hello %s', $foo ); // Bad. +echo sprintf( 'Hello %s', esc_html( $foo ) ); // Ok. +echo sprintf( 'Hello %s! Hi %s!', esc_html( $foo ), $bar ); // Bad. -echo vsprintf( 'Hello %s', array( $foo ) ); // Bad -echo vsprintf( 'Hello %s', array( esc_html( $foo ) ) ); // OK +echo vsprintf( 'Hello %s', array( $foo ) ); // Bad. +echo vsprintf( 'Hello %s', array( esc_html( $foo ) ) ); // Ok. -echo sprintf( __( 'Welcome to Genesis %s', 'genesis' ), PARENT_THEME_BRANCH ); // Bad x 2 -echo sprintf( esc_html__( 'Welcome to Genesis %s', 'genesis' ), esc_html( PARENT_THEME_BRANCH ) ); // OK +echo sprintf( __( 'Welcome to Genesis %s', 'genesis' ), PARENT_THEME_BRANCH ); // Bad x 2. +echo sprintf( esc_html__( 'Welcome to Genesis %s', 'genesis' ), esc_html( PARENT_THEME_BRANCH ) ); // Ok. -echo esc_html( strval( $_var ) ? $_var : gettype( $_var ) ); // OK -echo ( $is_hidden ) ? ' style="display:none;"' : ''; // OK -echo sprintf( 'Howdy, %s', esc_html( $name ? $name : __( 'Partner' ) ) ); // OK +echo esc_html( strval( $_var ) ? $_var : gettype( $_var ) ); // Ok. +echo ( $is_hidden ) ? ' style="display:none;"' : ''; // Ok. +echo sprintf( 'Howdy, %s', esc_html( $name ? $name : __( 'Partner' ) ) ); // Ok. -_e( 'Something' ); // Bad -esc_html_e( 'Something' ); // OK +_e( 'Something' ); // Bad. +esc_html_e( 'Something' ); // Ok. -echo $something // Bad - . esc_attr( 'baz-' // Rest is OK +echo $something // Bad. + . esc_attr( 'baz-' // Rest is OK. . $r . ( $r === $active_round ? ' foo' : '' ) . ( $r < $active_round ? ' bar' : '' ) ) . 'something'; -echo implode( '
', $items ); // Bad -echo implode( '
', urlencode_deep( $items ) ); // OK -echo implode( '
', array_map( 'esc_html', $items ) ); // OK -echo implode( '
', array_map( 'foo', $items ) ); // Bad -echo join( '
', $items ); // Bad -echo join( '
', array_map( 'esc_html', $items ) ); // OK +echo implode( '
', $items ); // Bad. +echo implode( '
', urlencode_deep( $items ) ); // Ok. +echo implode( '
', array_map( 'esc_html', $items ) ); // Ok. +echo implode( '
', array_map( 'foo', $items ) ); // Bad. +echo join( '
', $items ); // Bad. +echo join( '
', array_map( 'esc_html', $items ) ); // Ok. echo ''; -_deprecated_hook( 'some_filter', '1.3.0', esc_html__( 'The $arg is deprecated.' ), 'some_other_filter' ); // OK -_deprecated_hook( "filter_{$context}", '1.3.0', __( 'The $arg is deprecated.' ), sprintf( __( 'Some parsed message %s', $variable ) ) ); // Bad +_deprecated_hook( 'some_filter', '1.3.0', esc_html__( 'The $arg is deprecated.' ), 'some_other_filter' ); // Ok. +_deprecated_hook( "filter_{$context}", '1.3.0', __( 'The $arg is deprecated.' ), sprintf( __( 'Some parsed message %s', $variable ) ) ); // Bad. diff --git a/WordPress/Tests/XSS/EscapeOutputUnitTest.php b/WordPress/Tests/XSS/EscapeOutputUnitTest.php index 3d6bae14b8..31ddd3e57a 100644 --- a/WordPress/Tests/XSS/EscapeOutputUnitTest.php +++ b/WordPress/Tests/XSS/EscapeOutputUnitTest.php @@ -2,35 +2,23 @@ /** * Unit test class for WordPress Coding Standard. * - * @category PHP - * @package PHP_CodeSniffer - * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/ + * @package WPCS\WordPressCodingStandards + * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards + * @license https://opensource.org/licenses/MIT MIT */ /** * Unit test class for the EscapeOutput sniff. * - * A sniff unit test checks a .inc file for expected violations of a single - * coding standard. Expected errors and warnings are stored in this class. - * - * @category PHP - * @package PHP_CodeSniffer - * @author Akeda Bagus - * @author Greg Sherwood - * @author Marc McIntyre - * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence - * @version Release: @package_version@ - * @link http://pear.php.net/package/PHP_CodeSniffer + * @package WPCS\WordPressCodingStandards + * @since 2013-06-11 */ class WordPress_Tests_XSS_EscapeOutputUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * - * The key of the array should represent the line number and the value - * should represent the number of errors that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getErrorList() { return array( @@ -77,14 +65,11 @@ public function getErrorList() { /** * Returns the lines where warnings should occur. * - * The key of the array should represent the line number and the value - * should represent the number of warnings that should occur on that line. - * - * @return array(int => int) + * @return array => */ public function getWarningList() { return array(); - } // end getWarningList() + } -} // end class +} // End class. diff --git a/bin/phpcs.xml b/bin/phpcs.xml index aa8ec9d7fc..f6a7e6e234 100644 --- a/bin/phpcs.xml +++ b/bin/phpcs.xml @@ -2,11 +2,11 @@ The Coding standard for the WordPress Coding Standards itself. - + - + From 43d69498d93be35a1f3824feeac830a618c7a727 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 25 Aug 2016 16:37:25 +0200 Subject: [PATCH 118/122] Add some additional relevant information about running the PHPCompatibility sniffs. --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index a8c4dae3cc..8d629dcef4 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,11 @@ The [PHPCompatibility](https://github.com/wimg/PHPCompatibility) ruleset comes h The [PHPCompatibility](https://github.com/wimg/PHPCompatibility) sniffs are designed to analyse your code for cross-PHP version compatibility. Install it as a separate ruleset and either run it separately against your code or add it to your custom ruleset. +Whichever way you run it, do make sure you set the `testVersion` to run the sniffs against. The `testVersion` determines for which PHP versions you will received compatibility information. The recommended setting for this at this moment is `5.2-7.1` to support the same PHP versions as WordPress Core supports. + +For more information about setting the `testVersion`, see: +* [PHPCompatibility: Using the compatibility sniffs](https://github.com/wimg/PHPCompatibility#using-the-compatibility-sniffs) +* [PHPCompatibility: Using a custom ruleset](https://github.com/wimg/PHPCompatibility#using-a-custom-ruleset) ## Fixing errors or whitelisting them From 9a635779990c9ccdf510433e9dbf15823f313d6b Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 26 Aug 2016 16:08:33 +0200 Subject: [PATCH 119/122] Improve VariableName whitelisting for the `ValidVariableName` sniff. Depending on how the tokenized file is build up, any of the methods in the sniff might be called first, so the whitelist should be also be merged (if not done so already) in the other method which uses the whitelist. --- .../ValidVariableNameSniff.php | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php index 7dae7edcfb..20a2503806 100644 --- a/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php +++ b/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -75,7 +75,7 @@ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_Code * * @var bool */ - public static $addedCustomVariables = false; + protected $addedCustomVariables = false; /** * Processes this test, when one of its tokens is encountered. @@ -88,12 +88,8 @@ class WordPress_Sniffs_NamingConventions_ValidVariableNameSniff extends PHP_Code */ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { - // Merge any custom variables with the defaults, if we haven't already. - if ( ! self::$addedCustomVariables ) { - $this->whitelisted_mixed_case_member_var_names = array_merge( $this->whitelisted_mixed_case_member_var_names, $this->customVariablesWhitelist ); - - self::$addedCustomVariables = true; - } + // Merge any custom variables with the defaults. + $this->mergeWhiteList(); $tokens = $phpcs_file->getTokens(); $var_name = ltrim( $tokens[ $stack_ptr ]['content'], '$' ); @@ -173,6 +169,9 @@ protected function processVariable( PHP_CodeSniffer_File $phpcs_file, $stack_ptr */ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { + // Merge any custom variables with the defaults. + $this->mergeWhiteList(); + $tokens = $phpcs_file->getTokens(); $var_name = ltrim( $tokens[ $stack_ptr ]['content'], '$' ); @@ -203,6 +202,7 @@ protected function processMemberVar( PHP_CodeSniffer_File $phpcs_file, $stack_pt * @return void */ protected function processVariableInString( PHP_CodeSniffer_File $phpcs_file, $stack_ptr ) { + $tokens = $phpcs_file->getTokens(); if ( preg_match_all( '|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[ $stack_ptr ]['content'], $matches ) > 0 ) { @@ -232,4 +232,17 @@ static function isSnakeCase( $var_name ) { return (bool) preg_match( '/^[a-z0-9_]+$/', $var_name ); } + /** + * Merge a custom whitelist provided via a custom ruleset with the predefined whitelist, + * if we haven't already. + * + * @return void + */ + protected function mergeWhiteList() { + if ( false === $this->addedCustomVariables && ! empty( $this->customVariablesWhitelist ) ) { + $this->whitelisted_mixed_case_member_var_names = array_merge( $this->whitelisted_mixed_case_member_var_names, $this->customVariablesWhitelist ); + $this->addedCustomVariables = true; + } + } + } // End class. From a78dba293767294fd8707b91f50bc2b893313b13 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 19 Aug 2016 04:49:52 +0200 Subject: [PATCH 120/122] Changelog for the 0.10.0 version --- CHANGELOG.md | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75116e9519..ad4b9a7afd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,61 @@ This projects adheres to [Semantic Versioning](http://semver.org/) and [Keep a C ## [Unreleased] +_Nothing yet._ + +## [0.10.0] - 2016-08-22 + ### Added -- Sniff to flag dynamic translatable strings and textdomains. +- `WordPress.WP.I18n` sniff to the `WordPress-Core` ruleset to flag dynamic translatable strings and textdomains. +- `WordPress.PHP.DisallowAlternativePHPTags` sniff to the `WordPress-Core` ruleset to flag - and fix - ASP and `