Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cognitive Complexity Laravel Package

tomasvotruba/cognitive-complexity

A PHPStan extension that measures cognitive complexity of functions and classes, flagging code that's hard to read. Also detects complex constructor dependency trees in services like controllers and rules.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer (PHP 7.4+ required as of 1.3.0):

    composer require --dev tomasvotruba/cognitive-complexity
    

    Enable the rules in your phpstan.neon:

    includes:
        - vendor/tomasvotruba/cognitive-complexity/phpstan-rules.neon
    
  2. First Run Execute PHPStan with the new rules:

    vendor/bin/phpstan analyse src
    

    Look for errors like:

    CognitiveComplexity\TooHighCognitiveComplexityMethod
    
  3. First Use Case Identify a method with high cognitive complexity (e.g., > 20) and refactor it. Note that as of 1.3.0, scores follow the reference cognitive complexity paper more closely, so numbers may shift versus earlier releases:

    // Before (complex)
    public function calculate($input): float {
        if ($input > 10) {
            if ($input % 2 === 0) {
                return $input * 0.1;
            } else {
                return $input * 0.2;
            }
        } else {
            return $input * 0.05;
        }
    }
    
    // After (simplified)
    public function calculate($input): float {
        $factor = $this->getFactor($input);
        return $input * $factor;
    }
    
    private function getFactor(float $input): float {
        if ($input <= 10) return 0.05;
        return $input % 2 === 0 ? 0.1 : 0.2;
    }
    

Implementation Patterns

Workflows

  1. Integrate with CI/CD Add PHPStan to your pipeline (e.g., GitHub Actions):

    - name: PHPStan
      run: vendor/bin/phpstan analyse --level=5 src
    

    Fail builds if complexity exceeds thresholds.

  2. Custom Thresholds Override defaults in phpstan.neon:

    parameters:
        cognitiveComplexity:
            maxMethodComplexity: 15
            maxClassComplexity: 50
    
  3. Focused Analysis Run on specific files/directories:

    vendor/bin/phpstan analyse src/Service/
    
  4. Pair with Other Tools Combine with phpstan/extension-installer for seamless updates:

    composer require --dev phpstan/extension-installer
    
  5. Pin the Rule Version Because 1.3.0 re-aligned scoring with the reference paper, pin the package (^1.3) in composer.lock so scores are reproducible across machines and CI agents.

Integration Tips

  • Laravel-Specific Exclude vendor/ and generated files:
    excludeFiles:
        - vendor/**
        - bootstrap/**
    
  • Refactoring Use IDE hints (e.g., PHPStorm) to visualize complexity before fixing.
  • Documentation Add @complexity PHPDoc tags to justify high-complexity methods, or use PHPStan's documented error-ignoring mechanism (see Gotchas) to suppress one-off violations:
    /**
     * @complexity 25 (legacy, but well-tested)
     */
    public function legacyMethod() { ... }
    

Gotchas and Tips

Pitfalls

  1. Scoring Shift After Upgrade (1.3.0)

    • Complexity scores now follow the original cognitive complexity paper more closely. Existing reports, stored baselines, or thresholds tuned against pre-1.3.0 numbers may now fail or pass unexpectedly. Fix: Re-run analysis on main after upgrading; recalibrate maxMethodComplexity / maxClassComplexity and refresh any stored baseline rather than blindly bumping thresholds.
  2. Dependency Tree Rule Removed (1.3.0)

    • The dependency tree rule was removed in #27. If your phpstan.neon referenced it, PHPStan will error on the unknown service/rule. Fix: Remove stale references from phpstan.neon and CI configs when upgrading to 1.3.0.
  3. False Positives

    • Nested Ternaries: May inflate complexity unnecessarily. Fix: Break into helper methods.
    • Generated Code: Avoid analyzing auto-generated classes (e.g., Eloquent models) — dead branches that were previously unreachable are now handled more strictly (see #28). Fix: Exclude in phpstan.neon:
      excludeFiles:
          - app/Models/*.php
      
  4. Performance

    • Large codebases may slow down analysis. Fix: Run incrementally or parallelize:
      vendor/bin/phpstan analyse --parallel
      
  5. Configuration Overrides

    • Local overrides (e.g., phpstan.local.neon) can conflict with team settings. Fix: Document override rules in CONTRIBUTING.md.
  6. PHP Version Floor

    • 1.3.0 requires PHP 7.4+. Projects still on PHP 7.2/7.3 must stay on an older release. Fix: Check composer.json platform constraints before composer update.

Debugging

  • Inspect Metrics Use --error-format=json to analyze raw complexity data:
    vendor/bin/phpstan analyse --error-format=json > complexity.json
    
  • Silence Specific Violations 1.3.0 documents how to ignore errors (see #28). Use an inline @phpstan-ignore or an ignoreErrors entry for justified exceptions, rather than excluding entire files:
    parameters:
        ignoreErrors:
            - '#CognitiveComplexity.*legacyMethod#'
    
  • Visualize Tools like PhpDependency can map complexity to class diagrams.

Extension Points

  1. Custom Rules Extend the package by creating your own PHPStan rules:

    use PHPStan\Rules\Rule;
    use CognitiveComplexity\Rules\ComplexityRule;
    
    class CustomComplexityRule extends ComplexityRule {
        protected function getMaxAllowedComplexity(): int { return 10; }
    }
    

    Register in phpstan.neon:

    services:
        - CognitiveComplexity\Rules\CustomComplexityRule
    
  2. Error Ignoring As documented in 1.3.0, leverage PHPStan's ignoreErrors and inline ignore comments for localized exceptions instead of forking the rule — this keeps the package upgradeable.

  3. Integration with Linters Sync with ESLint (via laravel-shift/laravel-phpstan) for frontend-backend parity.

  4. Dynamic Thresholds Use environment variables for dynamic thresholds:

    parameters:
        cognitiveComplexity:
            maxMethodComplexity: %env.int(MAX_METHOD_COMPLEXITY, 20)%
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log