Source for file CyclomaticComplexitySniff.php
Documentation is available at CyclomaticComplexitySniff.php
* Checks the cyclomatic complexity (McCabe) for functions.
* The cyclomatic complexity (also called McCabe code metrics)
* indicates the complexity within a function by counting
* the different paths the function includes.
* @author Johann-Peter Hartmann <hartmann@mayflower.de>
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2007-2014 Mayflower GmbH
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class CyclomaticComplexitySniff implements Sniff
* A complexity higher than this value will throw a warning.
* A complexity higher than this value will throw an error.
public $absoluteComplexity = 20;
* Returns an array of tokens this test wants to listen for.
public function register ()
return array (T_FUNCTION );
* Processes this test, when one of its tokens is encountered.
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
public function process (File $phpcsFile, $stackPtr)
$this->currentFile = $phpcsFile;
$tokens = $phpcsFile->getTokens ();
// Ignore abstract methods.
if (isset ($tokens[$stackPtr]['scope_opener']) === false ) {
// Detect start and end of this function definition.
$start = $tokens[$stackPtr]['scope_opener'];
$end = $tokens[$stackPtr]['scope_closer'];
// Predicate nodes for PHP.
// Iterate from start to end and count predicate nodes.
for ($i = ($start + 1 ); $i < $end; $i++ ) {
if (isset ($find[$tokens[$i]['code']]) === true ) {
if ($complexity > $this->absoluteComplexity) {
$error = 'Function\'s cyclomatic complexity (%s) exceeds allowed maximum of %s';
$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';
$phpcsFile->addWarning ($warning, $stackPtr, 'TooHigh', $data);
Documentation generated on Mon, 11 Mar 2019 15:27:22 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|