From 5591547ed4fa992581ccc2620cf4a7403776f955 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 9 Sep 2020 17:33:20 +0200 Subject: [PATCH] AlwaysReturnInFilter: differentiate between abstract method and parse error This implements the suggestion made in https://github.com/Automattic/VIP-Coding-Standards/issues/580#issuecomment-689119006 If the method a filter callback points to is an abstract method, a warning will be thrown asking for manual inspection of the child class implementations of the abstract method. In case of parse or tokenizer error, the sniff will bow out and stay silent. --- .../Hooks/AlwaysReturnInFilterSniff.php | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/WordPressVIPMinimum/Sniffs/Hooks/AlwaysReturnInFilterSniff.php b/WordPressVIPMinimum/Sniffs/Hooks/AlwaysReturnInFilterSniff.php index c546693a..d6115611 100644 --- a/WordPressVIPMinimum/Sniffs/Hooks/AlwaysReturnInFilterSniff.php +++ b/WordPressVIPMinimum/Sniffs/Hooks/AlwaysReturnInFilterSniff.php @@ -175,12 +175,18 @@ private function processFunction( $stackPtr, $start = 0, $end = null ) { */ private function processFunctionBody( $stackPtr ) { - /** - * Stop if the function doesn't have a body, like when it is abstract. - * - * @see https://github.com/squizlabs/PHP_CodeSniffer/blob/master/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php#L87-L90 - */ - if ( isset( $this->tokens[ $stackPtr ]['scope_closer'] ) === false ) { + $filterName = $this->tokens[ $this->filterNamePtr ]['content']; + + $methodProps = $this->phpcsFile->getMethodProperties($stackPtr); + if ($methodProps['is_abstract'] === true) { + $message = 'The callback for the `%s` filter hook-in points to an abstract method. Please, make sure that all child class implementations of this abstract method always return a value.'; + $data = [ $filterName ]; + $this->phpcsFile->addWarning( $message, $stackPtr, 'AbstractMethod', $data ); + return; + } + + if ( isset( $this->tokens[ $stackPtr ]['scope_opener'], $this->tokens[ $stackPtr ]['scope_closer'] ) === false ) { + // Live coding, parse or tokenizer error. return; } @@ -198,8 +204,6 @@ private function processFunctionBody( $stackPtr ) { return; } - $filterName = $this->tokens[ $this->filterNamePtr ]['content']; - $functionBodyScopeStart = $this->tokens[ $stackPtr ]['scope_opener']; $functionBodyScopeEnd = $this->tokens[ $stackPtr ]['scope_closer'];