PHPackages                             ncac/php-cognitive-complexity - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. ncac/php-cognitive-complexity

ActiveLibrary[CLI &amp; Console](/categories/cli)

ncac/php-cognitive-complexity
=============================

CLI tool for measuring PHP cognitive complexity (ISO SonarQube) — integrates with CI/CD pipelines and Husky pre-commit hooks

v1.2.0(1w ago)198MITPHPPHP ^8.2CI passing

Since May 12Pushed 1w agoCompare

[ Source](https://github.com/NCAC/php-cognitive-complexity)[ Packagist](https://packagist.org/packages/ncac/php-cognitive-complexity)[ Docs](https://github.com/ncac/php-cognitive-complexity)[ RSS](/packages/ncac-php-cognitive-complexity/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (22)Versions (8)Used By (0)

PHP Cognitive Complexity
========================

[](#php-cognitive-complexity)

[![CI](https://github.com/ncac/php-cognitive-complexity/actions/workflows/ci.yml/badge.svg)](https://github.com/ncac/php-cognitive-complexity/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/9e69cc8098cb42a878ba6a3b961460805ce73f05ff6274dad0bb3c6e8ff6f68d/68747470733a2f2f636f6465636f762e696f2f67682f6e6361632f7068702d636f676e69746976652d636f6d706c65786974792f67726170682f62616467652e737667)](https://codecov.io/gh/ncac/php-cognitive-complexity)[![Packagist Version](https://camo.githubusercontent.com/37f7cc8bc7c523509a75fdf9349ed538a78054ae6586ca620962cd47c6063bc4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6361632f7068702d636f676e69746976652d636f6d706c6578697479)](https://packagist.org/packages/ncac/php-cognitive-complexity)[![PHP Version](https://camo.githubusercontent.com/4f641f77943644dab3d6ecbeae93485fc7da29562277a1934bc9760082754f05/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6e6361632f7068702d636f676e69746976652d636f6d706c6578697479)](https://packagist.org/packages/ncac/php-cognitive-complexity)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](LICENSE)

> A modern PHP CLI tool for measuring **cognitive complexity** of PHP code — ISO SonarQube (G. Ann Campbell's specification).

Two commands under one binary: **`check`** for CI/hooks (strict gate, exit 1 on violation), **`analyse`** for interactive exploration (coloured output, severity levels, always exit 0).

---

Why cognitive complexity?
-------------------------

[](#why-cognitive-complexity)

Cyclomatic complexity counts paths. **Cognitive complexity** measures how hard code is to *read*. It penalises deep nesting and rewards early returns — much closer to human perception of code quality.

This tool implements the [SonarSource specification](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) for PHP.

---

Installation
------------

[](#installation)

```
composer require --dev ncac/php-cognitive-complexity
```

---

Usage
-----

[](#usage)

### `check` — CI gate

[](#check--ci-gate)

Strict mode: exits 1 on any violation. Designed for pre-commit hooks and CI pipelines.

```
# Basic check
vendor/bin/cognitive-complexity check src/ --max=15

# With a config file
vendor/bin/cognitive-complexity check src/ --config=cognitive.yaml

# Only git-modified files (pre-commit)
vendor/bin/cognitive-complexity check src/ --max=15 --diff

# JSON output
vendor/bin/cognitive-complexity check src/ --format=json

# GitLab Code Quality artifact
vendor/bin/cognitive-complexity check src/ --format=gitlab > gl-code-quality-report.json

# Drupal/multi-extension projects
vendor/bin/cognitive-complexity check web/ --ext=php,module,inc,theme,install
```

### `analyse` — interactive exploration

[](#analyse--interactive-exploration)

Developer-experience mode: coloured output grouped by file, severity labels, always exits 0.

```
# Show only violations (default)
vendor/bin/cognitive-complexity analyse src/

# Show all functions including those below threshold
vendor/bin/cognitive-complexity analyse src/ --all

# Sort by score descending (prioritise refactoring targets)
vendor/bin/cognitive-complexity analyse src/ --sort=score

# Custom threshold
vendor/bin/cognitive-complexity analyse src/ --max=20

# Drupal/multi-extension projects
vendor/bin/cognitive-complexity analyse web/ --ext=php,module,inc,theme,install
```

**Example output:**

```
── src/Service/OrderService.php
  [ 18]  processOrder:42 — minor
  [  4]  validateItems:91
  [  0]  formatResult:112

── src/Gateway/PaymentGateway.php
  [ 32]  validate:87 — moderate

✗ 2 violation(s) / 4 function(s) in 2 file(s) — threshold=15

```

**Severity levels** (multiples of threshold, default 15):

LevelScore range`minor`threshold+1 → 2×threshold`moderate`2×threshold+1 → 3×threshold`high`3×threshold+1 → 50`critical`&gt; 50### Generate a baseline (ignore pre-existing violations)

[](#generate-a-baseline-ignore-pre-existing-violations)

```
vendor/bin/cognitive-complexity baseline src/ --output=baseline.json
vendor/bin/cognitive-complexity check src/ --baseline=baseline.json
```

---

Configuration file
------------------

[](#configuration-file)

Create a `cognitive.yaml` at the root of your project:

```
# Default threshold
max_complexity: 15

# Per-path overrides
paths:
  src/Controller/: 10
  src/Service/: 12
  tests/: 20

# Excluded paths
exclude:
  - vendor/
  - cache/
  - legacy/

# File extensions to scan (default: php)
# CLI --ext overrides this list
extensions:
  - php
  - module
  - inc
  - theme
  - install
```

---

Console output example
----------------------

[](#console-output-example)

```
✗ src/Service/OrderService.php::processOrder → 18 (max: 15) [line 42]
✗ src/Gateway/PaymentGateway.php::validate → 16 (max: 15) [line 87]

2 violation(s) found. Cognitive complexity threshold exceeded.

```

This is the output of `check`. For richer output, use [`analyse`](#analyse--interactive-exploration).

---

Integration in your project
---------------------------

[](#integration-in-your-project)

Add convenience scripts to your `composer.json` for fixed targets:

```
{
  "scripts": {
    "cc": "cognitive-complexity check src/ --max=15",
    "cc:analyse": "cognitive-complexity analyse src/ --all --sort=score",
    "cc:baseline": "cognitive-complexity baseline src/ --max=15 --output=cognitive-baseline.json"
  }
}
```

```
composer cc              # CI gate — exit 1 on violations
composer cc:analyse      # interactive report sorted by score
composer cc:baseline     # regenerate the baseline after a refactoring
```

For ad-hoc analysis on a specific path, call `cc` — the short wrapper installed alongside the main binary:

```
# cc defaults to 'check' when no sub-command is given
vendor/bin/cc src/
vendor/bin/cc src/ --max=20
vendor/bin/cc src/ --diff                        # pre-commit: git-modified files only

# Explicit sub-commands
vendor/bin/cc analyse web/modules/custom/ --all
vendor/bin/cc analyse web/modules/custom/ --sort=score --ext=php,module,inc
vendor/bin/cc baseline src/ --output=cognitive-baseline.json
```

To ignore pre-existing violations during onboarding, generate a baseline first:

```
composer cc:baseline
# then add --baseline to your cc script:
# "cc": "cognitive-complexity check src/ --max=15 --baseline=cognitive-baseline.json"
```

---

```
# .husky/pre-commit
vendor/bin/cognitive-complexity check src/ --max=15
```

---

GitLab CI/CD integration
------------------------

[](#gitlab-cicd-integration)

```
# .gitlab-ci.yml
cognitive_complexity:
  stage: quality
  script:
    - php vendor/bin/cognitive-complexity check src/ --format=gitlab > gl-code-quality-report.json
  artifacts:
    reports:
      codequality: gl-code-quality-report.json
```

---

Algorithm
---------

[](#algorithm)

Based on G. Ann Campbell's Cognitive Complexity specification:

StructureIncrement`if`, `else if`, `else`+1`for`, `foreach`, `while`, `do-while`+1`switch`+1`catch`+1Ternary `?:`+1`&&`, `||` (logical sequence changes)+1**Each nested level**+level bonus---

Development
-----------

[](#development)

```
git clone https://github.com/ncac/php-cognitive-complexity.git
cd php-cognitive-complexity
composer install

# Run tests
composer test

# Run all checks
composer check

# Coverage
composer test-coverage
```

---

License
-------

[](#license)

MIT © [Nicolas Catrice-Auzon Cape](https://gravatar.com/devncac)

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance98

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~10 days

Total

3

Last Release

8d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5a6ed8b43a9ae77cd618a8c7bbe44d3d0994dbf548ebf06a3e7b41fa9bb406b4?d=identicon)[NCAC](/maintainers/NCAC)

---

Top Contributors

[![NCAC](https://avatars.githubusercontent.com/u/10559545?v=4)](https://github.com/NCAC "NCAC (20 commits)")

---

Tags

phpclistatic analysiscode qualitypre-commitsonarqubeci-cdcognitive-complexity

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ncac-php-cognitive-complexity/health.svg)

```
[![Health](https://phpackages.com/badges/ncac-php-cognitive-complexity/health.svg)](https://phpackages.com/packages/ncac-php-cognitive-complexity)
```

###  Alternatives

[jolicode/castor

A lightweight and modern task runner. Automate everything. In PHP.

54642.4k4](/packages/jolicode-castor)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

21764.8M1.6k](/packages/drupal-core)[friendsoftypo3/content-blocks

TYPO3 CMS Content Blocks - Content Types API | Define reusable components via YAML

101466.4k44](/packages/friendsoftypo3-content-blocks)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6941.5M395](/packages/drupal-core-recommended)[aeliot/todo-registrar

Register TODOs from source code in issue tracker

153.0k](/packages/aeliot-todo-registrar)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
