Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. CyclomaticComplexitySniff.php

function CyclomaticComplexitySniff::process

Processes this test, when one of its tokens is encountered.

Parameters

\PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.:

int $stackPtr The position of the current token: in the stack passed in $tokens.

Return value

void

Overrides Sniff::process

File

vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php, line 59

Class

CyclomaticComplexitySniff

Namespace

PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics

Code

public function process(File $phpcsFile, $stackPtr) {
    $tokens = $phpcsFile->getTokens();
    // Ignore abstract methods.
    if (isset($tokens[$stackPtr]['scope_opener']) === false) {
        return;
    }
    // Detect start and end of this function definition.
    $start = $tokens[$stackPtr]['scope_opener'];
    $end = $tokens[$stackPtr]['scope_closer'];
    // Predicate nodes for PHP.
    $find = [
        T_CASE => true,
        T_DEFAULT => true,
        T_CATCH => true,
        T_IF => true,
        T_FOR => true,
        T_FOREACH => true,
        T_WHILE => true,
        T_ELSEIF => true,
        T_INLINE_THEN => true,
        T_COALESCE => true,
        T_COALESCE_EQUAL => true,
        T_MATCH_ARROW => true,
        T_NULLSAFE_OBJECT_OPERATOR => true,
    ];
    $complexity = 1;
    // Iterate from start to end and count predicate nodes.
    for ($i = $start + 1; $i < $end; $i++) {
        if (isset($find[$tokens[$i]['code']]) === true) {
            $complexity++;
        }
    }
    if ($complexity > $this->absoluteComplexity) {
        $error = 'Function\'s cyclomatic complexity (%s) exceeds allowed maximum of %s';
        $data = [
            $complexity,
            $this->absoluteComplexity,
        ];
        $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data);
    }
    else {
        if ($complexity > $this->complexity) {
            $warning = 'Function\'s cyclomatic complexity (%s) exceeds %s; consider refactoring the function';
            $data = [
                $complexity,
                $this->complexity,
            ];
            $phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data);
        }
    }
}
RSS feed
Powered by Drupal