tomasvotruba/cognitive-complexity

PHPStan rules to measure cognitive complexity of your classes and methods

Installs: 979 487

Dependents: 39

Suggesters: 0

Security: 0

Stars: 84

Watchers: 3

Forks: 1

Open Issues: 1

Type:phpstan-extension

0.2.2 2023-09-08 09:56 UTC

This package is auto-updated.

Last update: 2023-11-08 10:16:33 UTC


README


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

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;
}

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

How to keep cognitive complexity on 1? Read Keep Cognitive Complexity Low with PHPStan post to learn it.


Install

composer require tomasvotruba/cognitive-complexity --dev

The package is available on PHP 7.2-8.1 versions in tagged releases.


Usage

With PHPStan extension installer, everything is ready to run.

Enable each item on their own with simple configuration:

# phpstan.neon
parameters:
    cognitive_complexity:
        class: 50
        function: 8