Skip to content

Commit

Permalink
AlwaysReturnInFilter: differentiate between abstract method and parse…
Browse files Browse the repository at this point in the history
… error

This implements the suggestion made in Automattic#580 (comment)

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.
  • Loading branch information
jrfnl committed Sep 9, 2020
1 parent 8e4077d commit 5591547
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions WordPressVIPMinimum/Sniffs/Hooks/AlwaysReturnInFilterSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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'];

Expand Down

0 comments on commit 5591547

Please sign in to comment.