PHP_CodeSniffer icon indicating copy to clipboard operation
PHP_CodeSniffer copied to clipboard

Generic/NestingLevel: should nested structures be skipped?

Open rodrigoprimo opened this issue 1 year ago • 1 comments

Describe the bug

Similar to #726, I wonder if the Generic.Metrics.NestingLevel should skip nested structures. Currently, it counts the nesting level of inner functions to the "outer" function.

Code sample

function hasNestedFunction() {
    function nestingSix() {
        if ( $condition ) {
            echo 'hi';
            switch ( $condition ) {
                case '1':
                    if ( $condition === '1' ) {
                        if ( $cond ) {
                            foreach ( $conds as $cond ) {
                                echo 'hi';
                            }
                        }
                    }
                    break;
            }
        }
    }
}

To reproduce

Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above.
  2. Run phpcs --standard=Generic --sniffs=Generic.Metrics.NestingLevel test.php
  3. See error message displayed
--------------------------------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 2 WARNINGS AFFECTING 2 LINES
--------------------------------------------------------------------------------------------------------------------------------
 3 | WARNING | Function's nesting level (7) exceeds 5; consider refactoring the function (Generic.Metrics.NestingLevel.TooHigh)
 4 | WARNING | Function's nesting level (6) exceeds 5; consider refactoring the function (Generic.Metrics.NestingLevel.TooHigh)
--------------------------------------------------------------------------------------------------------------------------------

Expected behavior

Potentially the sniff should not display an error on line 3.

Versions (please complete the following information)

Operating System not relevant
PHP version not relevant
PHP_CodeSniffer version master
Standard Generic
Install type not relevant

Please confirm

  • [x] I have searched the issue list and am not opening a duplicate issue.
  • [x] I have read the Contribution Guidelines and this is not a support question.
  • [x] I confirm that this bug is a bug in PHP_CodeSniffer and not in one of the external standards.
  • [x] I have verified the issue still exists in the master branch of PHP_CodeSniffer.

rodrigoprimo avatar Dec 09 '24 18:12 rodrigoprimo

I think that makes sense, but only for "closed" scope structures, like nested named functions, not for arrow functions, which are "open".

As for closures and anonymous classes, I'd like to hear some more opinions on whether those should be skipped over or not.

jrfnl avatar Dec 10 '24 20:12 jrfnl