Cognitive Load is a dev-only package that statically analyses your codebase for cognitive complexity and architectural markers. It parses your app's PHP with its own AST-based engine (built on nikic/php-parser), scores every class from 0 to 100, and can snapshot a baseline so a pull request that makes the code measurably messier fails your build.
It requires PHP 8.2+ and supports Laravel 12 and 13.
composer require --dev "grafite/cognitive-load"
Then publish the config:
php artisan vendor:publish --provider="Grafite\CognitiveLoad\CognitiveLoadServiceProvider"
Every class is scored on two markers, each from 0 to 100:
Each metric adds nothing while it is at or below its threshold, then its penalty grows logarithmically past it. A category's accumulated penalty decays into a score with 100 * exp(-raw / k), where k comes from category_scaling. The two categories combine into a weighted overall score (60% complexity, 40% architecture by default), where 100 is the cleanest.
| Metric | Default Threshold |
|---|---|
line_count | 20 |
argument_count | 4 |
return_count | 3 |
variable_count | 8 |
property_access_count | 5 |
if_count | 3 |
if_nesting_depth | 2 |
else_count | 2 |
cyclomatic_complexity | 5 |
| Metric | Default Threshold |
|---|---|
class_loc | 200 |
method_count | 10 |
coupling_count (constructor dependencies + imports) | 6 |
inheritance_depth | 2 |
Scores map onto a grade and a risk band using one shared set of thresholds:
| Score | Grade | Risk |
|---|---|---|
| 80 and above | Good | Low |
| 60 to 79 | Fair | Medium |
| 40 to 59 | Poor | High |
| Below 40 | Critical | VeryHigh |
The published config/cognitive-load.php file controls what gets scanned and how strictly it is judged. The key sections are:
[
// Directories/files scanned when no path is given on the CLI
'paths' => [app_path()],
// Regex: matched against the path, filename, and fully-qualified class name
'exclude' => ['#/vendor/#', '#/tests/#', '#/database/migrations/#'],
'exclude_files' => [],
'exclude_classes' => [],
'category_weights' => [
'complexity' => 0.6,
'architecture' => 0.4,
],
'bands' => [
'thresholds' => [40, 60, 80],
'risk_labels' => ['VeryHigh', 'High', 'Medium', 'Low'],
'grade_labels' => ['Critical', 'Poor', 'Fair', 'Good'],
],
'baseline' => [
'path' => base_path('cognitive-load-baseline.json'),
],
'gate' => [
'overall_margin' => 5.0,
'class_margin' => 8.0,
'fail_if_baseline_missing' => false,
],
]
The file also contains metrics and architecture_metrics, where each metric has a threshold and scale (and per-method metrics can be turned off with enabled), plus category_scaling, which sets how quickly each category decays from 100.
Analyses the codebase and prints a report. With no path it scans config('cognitive-load.paths'), normally app/. You can pass a directory or a single file.
php artisan cognitive-load:analyse php artisan cognitive-load:analyse app/Services --format=json --detailed
| Option | Description |
|---|---|
--format= |
Output format for the terminal report: console (default) or json. |
--detailed |
Include a per-method breakdown table for each class. |
--output= |
Also write the full JSON report to this file path. |
--compare-baseline |
Load the configured baseline and report a delta against it. |
--fail-on-regression |
Exit non-zero when the comparison fails the configured gate margins. Implies --compare-baseline. |
--baseline-path= |
Override cognitive-load.baseline.path for this run. |
Snapshots the current scores as the baseline for future comparisons.
php artisan cognitive-load:baseline
| Option | Description |
|---|---|
--force |
Overwrite an existing baseline file without confirmation. |
--baseline-path= |
Override cognitive-load.baseline.path for this run. |
Once a baseline exists, --fail-on-regression fails the build when any of the following happens:
gate.overall_margin (default 5).gate.class_margin (default 8).Classes that aren't in the baseline yet are not gated. If no baseline file exists, the comparison is skipped, unless gate.fail_if_baseline_missing is true, in which case the run fails.
- name: Cognitive Load gate run: php artisan cognitive-load:analyse --compare-baseline --fail-on-regression
Commit cognitive-load-baseline.json (or your configured baseline.path) to the repo. When a regression is intentional, update it deliberately with php artisan cognitive-load:baseline --force.
Scores tell you code is hard to follow. cognitive-load:sloppy tells you it is sloppy: swallowed exceptions, half-finished stubs, dead dependencies, Eloquent misuse and copy-paste. It is the kind of debt AI coding agents often leave behind, and it applies equally to hand-written code. It runs as a separate, rule-based pass over the same paths and exclude* settings, and never changes the Complexity or Architecture scores.
php artisan cognitive-load:sloppy php artisan cognitive-load:sloppy app/Services --min-severity=medium --format=json
Each finding includes a rule ID, severity, confidence, file:line, the symbol (Class::method), what is wrong, and what to do about it.
| Rule | Name | Default Severity |
|---|---|---|
| SL101 | Swallowed exception (empty catch) | high (low when the catch only holds a comment) |
| SL102 | Not implemented (throw new …('Not implemented')) | high |
| SL103 | Placeholder comment (TODO/FIXME/XXX/HACK) | low (medium when it is the whole body) |
| SL104 | Empty method | medium |
| SL105 | Debug leftover (dd, dump, var_dump, ray, ->dd(), …) | high |
| SL201 | Unused constructor dependency | medium |
| SL202 | Unused private method | medium |
| SL203 | Unused private property | medium |
| SL204 | Unused import | low |
| SL205 | Redundant boolean return (return $x ? true : false) | low |
| SL206 | Constant condition (if (true), while (false)) | medium |
| SL207 | Commented-out code | low |
| SL301 | Query in loop | medium |
| SL302 | Filter after fetch (Model::all()->where(), ->get()->count()) | high |
| SL303 | Possible N+1 (relation read while looping over a query result) | low |
| SL304 | env() outside config/ | high |
| SL305 | Fat controller (too many actions, or DB:: in a controller) | medium |
| SL306 | Unvalidated mass assignment (create($request->all())) | high |
| SL401 | Duplicate method body (same body after renaming variables) | medium |
Gate CI on new sloppiness only. First, snapshot what exists today:
php artisan cognitive-load:sloppy-baseline
php artisan cognitive-load:sloppy --fail-on-new
Findings are fingerprinted by rule, file, symbol and the offending code, not by line number, so adding an import or moving a method doesn't make old findings look new. --fail-on-new fails only on new findings at or above sloppy.gate.fail_on (default medium). Without a baseline, every finding counts as new, unless sloppy.gate.fail_if_baseline_missing is set, in which case the run fails outright.
- name: Sloppiness gate run: php artisan cognitive-load:sloppy --fail-on-new
| Option | Description |
|---|---|
--format= |
Output format for the terminal report: console (default) or json. |
--min-severity= |
Only report findings at or above this severity: low, medium or high. |
--output= |
Also write the full JSON report to this file path. |
--compare-baseline |
Load the sloppiness baseline and report new and resolved findings. |
--fail-on-new |
Exit non-zero when new findings reach sloppy.gate.fail_on. Implies --compare-baseline. |
--baseline-path= |
Override cognitive-load.sloppy.baseline.path for this run. |
| Option | Description |
|---|---|
--force |
Overwrite an existing sloppiness baseline without confirmation. |
--baseline-path= |
Override cognitive-load.sloppy.baseline.path for this run. |
The sloppy block in config/cognitive-load.php lets you disable any rule or override its severity. A few rules take extra options:
'sloppy' => [ 'min_severity' => 'low', 'baseline' => [ 'path' => base_path('sloppy-baseline.json'), ], 'gate' => [ 'fail_on' => 'medium', 'fail_if_baseline_missing' => false, ], 'rules' => [ 'SL103' => ['severity' => 'medium'], 'SL105' => ['enabled' => true, 'functions' => ['dd', 'ddd', 'dump', 'var_dump', 'print_r', 'var_export', 'ray']], 'SL303' => ['enabled' => false], 'SL305' => ['enabled' => true, 'max_actions' => 7], 'SL401' => ['enabled' => true, 'min_statements' => 5], // ... ], 'custom_rules' => [], ],
To add your own rules, list classes implementing Grafite\CognitiveLoad\Sloppy\Rules\FileRule under custom_rules. A file rule receives one parsed file at a time. Extending AbstractRule gives you the finding() helper, which handles fingerprinting and severity overrides from config.
use Grafite\CognitiveLoad\Sloppy\FileContext; use Grafite\CognitiveLoad\Sloppy\Rules\AbstractRule; use Grafite\CognitiveLoad\Sloppy\Rules\FileRule; use Grafite\CognitiveLoad\Sloppy\Severity; use PhpParser\Node\Expr\Exit_; class NoExitCalls extends AbstractRule implements FileRule { public function id(): string { return 'APP001'; } public function name(): string { return 'exit() or die() call'; } public function defaultSeverity(): Severity { return Severity::High; } public function check(FileContext $context): array { $findings = []; foreach ($context->findInstanceOf(Exit_::class) as $node) { $findings[] = $this->finding( $context, $node, 'exit() or die() is called in application code.', 'Throw an exception or return a response instead.', ); } return $findings; } }
Register it as a class name, or as a map of class name to rule config:
'custom_rules' => [ App\CognitiveLoad\NoExitCalls::class => ['severity' => 'medium'], ],
For checks that need every scanned file at once, such as cross-file duplication, implement ProjectRule instead. It provides checkProject(array $contexts), which receives all the FileContext objects.