Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

PHPStan rules to measure cognitive complexity of your classes and methods

License

NotificationsYou must be signed in to change notification settings

TomasVotruba/cognitive-complexity

Repository files navigation


Cognitive complexity tells us, how difficult code is to understand by a reader.

How is cognitive complexity measured?

functionget_words_from_number(int$number):string{$amountInWords ='';if ($number ===1) {// + 1$amountInWords ='one';    }elseif ($number ===2) {// + 1$amountInWords ='couple';    }elseif ($number ===3) {// + 1$amountInWords ='a few';    }else {// + 1$amountInWords ='a lot';    }return$amountInWords;}

This function uses nesting, conditions and continue back and forth. It's hard to read and results incognitive complexity of 4.

How to keepcognitive complexity on 1? ReadCognitive load is what matters orSonar paper about cognitive complexity metrics that inspired this repository.


Install

composer require tomasvotruba/cognitive-complexity --dev

The package is available on PHP 7.4+.


Usage

WithPHPStan extension installer, everything is ready to run.

Enable each item on their own with simple configuration:

# phpstan.neonparameters:cognitive_complexity:class:50function:8

Detect complex Class Dependency Trees

In classes like controllers, Rector rules, PHPStan rules or other services of specific type, the complexity can be hidden in the __construct() dependencies. Simple class with 10 dependencies is more complex than complex class with 2 dependencies.

That's why there is a rule to detect these dependency trees. It checks:

  • complexity ofcurrent class
  • constructor dependencies and their class complexity together

Final number is compared and used as a final complexity:

# phpstan.neonparameters:cognitive_complexity:dependency_tree:150dependency_tree_types:# only these explicit types are checked, nothing else            -Rector\Contract\Rector\RectorInterface

Happy coding!

About

PHPStan rules to measure cognitive complexity of your classes and methods

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •  

Contributors3

  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp