tomasvotruba / cognitive-complexity
PHPStan rules to measure cognitive complexity of your classes and methods
Package info
github.com/TomasVotruba/cognitive-complexity
Type:phpstan-extension
pkg:composer/tomasvotruba/cognitive-complexity
Requires
- php: >=7.4
- nikic/php-parser: ^5.3
- phpstan/phpstan: ^2.0
Requires (Dev)
- php-parallel-lint/php-parallel-lint: ^1.4
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpunit/phpunit: ^13.3
- rector/jack: ^1.1
- rector/rector: ^2.6
- symplify/easy-coding-standard: ^13.3
- symplify/phpstan-rules: ^14.17
- tomasvotruba/type-coverage: ^2.3
- tomasvotruba/unused-public: ^2.2
- tracy/tracy: ^2.12
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-10-06 09:07:01 UTC
README
Cognitive complexity tells how difficult code is for a reader to understand. This package adds PHPStan rules that report classes and methods that got too complex.
How is cognitive complexity measured?
function get_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; }
Every branch makes the reader keep one more path in their head. This function results in cognitive complexity of 4.
What adds complexity:
- +1 for each
if,elseif,else,switch,match, ternary,for,foreach,while,do-whileandcatch - +1 for each sequence of boolean operators, e.g.
$a && $b && $cis +1,$a && $b || $cis +2 - +1 for
gotoandbreak/continuewith a level - +1 per nesting level for structures nested in loops, conditions, closures or
catch
How to keep cognitive complexity on 1? Read Cognitive load is what matters or Sonar paper about cognitive complexity metrics that inspired this repository.
Install
composer require tomasvotruba/cognitive-complexity --dev
The package runs on PHP 7.4+.
Usage
With PHPStan extension installer, everything is ready to run. The class and function rules are enabled by default.
Adjust the limits in your config, these are the defaults:
# phpstan.neon parameters: cognitive_complexity: class: 40 function: 9
Each rule has its own error identifier, so you can ignore it on a specific place:
complexity.classLikecomplexity.functionLike
# phpstan.neon parameters: ignoreErrors: - identifier: complexity.functionLike path: src/SomeComplexClass.php
Happy coding!
