Weave Code
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

Laravel Stats Phploc Laravel Package

stefanzweifel/laravel-stats-phploc

Fork of sebastianbergmann/phploc used to keep wnx/laravel-stats compatible across Laravel versions by supporting multiple sebastian/version releases. Measures PHP project size and structure (LOC, complexity, dependencies). Not intended for real projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install via Composer (Laravel Integration)

    composer require stefanzweifel/laravel-stats-phploc
    

    The package integrates seamlessly with Laravel’s service container and provides a facade (Stats) for easy access.

  2. First Usage Run a basic analysis on your project’s src directory:

    use Stats\Facades\Stats;
    
    $results = Stats::analyze(app_path('src'));
    $results->getLinesOfCode(); // Returns total LOC
    
  3. Quick CLI Check Use Artisan to generate a report:

    php artisan stats:phploc src
    

    Outputs a structured breakdown of classes, methods, complexity, etc.


Where to Look First

  • Facade API: Stats\Facades\Stats provides methods like analyze(), getLinesOfCode(), getCyclomaticComplexity(), etc.
  • Artisan Commands: Built-in commands (stats:phploc, stats:report) for CLI-driven analysis.
  • Configuration: Publish the config file for customization:
    php artisan vendor:publish --provider="StefanZweifel\LaravelStatsPhploc\StatsPhplocServiceProvider"
    

First Use Case

Track Codebase Growth Over Time

// In a controller or scheduled job
$currentLoc = Stats::analyze(app_path('src'))->getLinesOfCode();
cache()->put('last_analysis_loc', $currentLoc, now()->addDays(7));

Compare cached values to monitor LOC trends.


Implementation Patterns

Core Workflows

  1. Integrate with CI/CD Add a GitHub Action or GitLab CI step to run php artisan stats:report and fail builds if LOC exceeds thresholds:

    # .github/workflows/phploc.yml
    - name: Check LOC
      run: |
        php artisan stats:phploc src --threshold=5000
        if [ $? -ne 0 ]; exit 1;
    
  2. Dynamic Reporting Use the Stats::analyze() result object to build custom dashboards:

    $report = Stats::analyze(app_path('src'));
    return view('stats.dashboard', [
        'classes' => $report->getClasses(),
        'complexity' => $report->getAverageComplexityPerClass(),
    ]);
    
  3. Exclude Directories Configure exclusions in config/stats-phploc.php:

    'excludes' => [
        'tests/*',
        'vendor/*',
        'storage/*',
    ],
    

Integration Tips

  • Laravel Events Trigger analysis on job.processed or model.saved to log changes:

    event(new AnalyzeCodebase());
    
  • Service Providers Bind the Stats facade to a custom service for extended functionality:

    $this->app->bind('stats', function () {
        return new CustomStatsService(Stats::analyze(app_path('src')));
    });
    
  • Testing Mock Stats::analyze() in unit tests to avoid real file scans:

    Stats::shouldReceive('analyze')->andReturn(new MockReport());
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Avoid running phploc on large directories (>10k files) in production.
    • Fix: Cache results for 24 hours:
      $results = cache()->remember('phploc_results', now()->addHours(24), fn() => Stats::analyze(app_path('src')));
      
  2. False Positives in Complexity

    • Legacy code with deep inheritance may inflate cyclomatic complexity.
    • Fix: Use --ignore flags to exclude problematic directories:
      php artisan stats:phploc src --ignore="app/OldLegacyCode/*"
      
  3. PHP Version Mismatches

    • The package drops PHP 7.x support (since v8.0.0). Ensure your server meets requirements.
    • Fix: Use a .php-version file or Docker to enforce PHP 8.0+.

Debugging

  • Silent Failures If Stats::analyze() returns empty data, verify:

    • The target directory exists (!file_exists(app_path('src'))).
    • Permissions allow file traversal (chmod -R 755 app_path('src')).
  • Command-Line Debugging Run with --verbose to see raw phploc output:

    php artisan stats:phploc src --verbose
    

Extension Points

  1. Custom Metrics Extend the StefanZweifel\LaravelStatsPhploc\Report class to add project-specific metrics:

    class ExtendedReport extends Report {
        public function getTestCoverageRatio(): float {
            return $this->getLinesOfCode() / $this->getTestLinesOfCode();
        }
    }
    
  2. Database Storage Save reports to a stats_reports table:

    Stats::analyze(app_path('src'))->saveToDatabase();
    

    (Requires publishing migrations: php artisan vendor:publish --tag=migrations.)

  3. Slack/Email Alerts Hook into Laravel’s illuminate\mail or notifications to alert on LOC spikes:

    if ($report->getLinesOfCode() > config('stats.threshold')) {
        notify(new LocThresholdExceeded($report));
    }
    

Config Quirks

  • Default Excludes The package excludes vendor/, node_modules/, and tests/ by default. Override in config/stats-phploc.php:

    'excludes' => [
        'app/Console/Kernel.php', // Exclude specific files
    ],
    
  • Output Format Force JSON output for API consumers:

    php artisan stats:phploc src --format=json
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor