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

Phploc Laravel Package

cmgmyr/phploc

Laravel-friendly wrapper around phpLOC for measuring PHP project size and structure. Generate lines-of-code, classes, methods, complexity-style stats from the command line or within builds to quickly gauge codebase scope and trends.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation:

    composer require --dev cmgmyr/phploc
    

    Ensure the package is registered in composer.json under require-dev.

  2. Publish the Artisan Command: Run:

    php artisan vendor:publish --provider="Cmgmyr\PHPLOC\PhpLocServiceProvider"
    

    This creates a phploc.php config file in config/ (default path: config/phploc.php).

  3. First Use Case: Run a basic analysis on your Laravel project:

    php artisan phploc
    

    By default, it scans app/, routes/, and database/ directories. Verify the output matches your expectations (e.g., class counts, LOC trends).

  4. Customize Directories: Update config/phploc.php to exclude or include specific paths:

    'directories' => [
        base_path('app'),
        base_path('routes'),
        base_path('tests'), // Example: Add tests
    ],
    'exclude' => [
        'app/Helpers/*', // Example: Exclude helpers
    ],
    

Implementation Patterns

1. Daily Development Workflow

  • Pre-Refactor Check: Run php artisan phploc before major changes to capture a baseline. Compare post-refactor metrics to validate improvements (e.g., reduced LOC, lower cyclomatic complexity).
    php artisan phploc --output=pre-refactor.json
    
  • Feature Growth Tracking: Use --log to append results to a file (e.g., storage/logs/phploc.log) and review trends over time:
    php artisan phploc --log --output-format=json
    

2. CI/CD Integration

  • GitHub Actions Example: Add a step to your workflow to fail builds if LOC exceeds thresholds:
    - name: Check LOC
      run: |
        LOC=$(php artisan phploc --logical-lines | grep "Logical Lines of Code" | awk '{print $3}')
        if [ "$LOC" -gt 5000 ]; then
          echo "LOC exceeds threshold ($LOC > 5000)"
          exit 1
        fi
    
  • Slack Notifications: Parse output in CI and post alerts for spikes in complexity:
    php artisan phploc --output-format=json | jq '.metrics["Average Complexity per Method"]' > complexity.json
    

3. Laravel-Specific Patterns

  • Exclude Vendor/Generated Code: Configure phploc.php to skip vendor/, bootstrap/cache/, and storage/framework/:
    'exclude' => [
        'vendor/*',
        'bootstrap/cache/*',
        'storage/framework/*',
    ],
    
  • Focus on Critical Paths: Target only app/Http/Controllers/ and app/Services/ for high-impact analysis:
    php artisan phploc app/Http/Controllers/ app/Services/
    

4. Reporting and Dashboards

  • Generate HTML Reports: Use --output-format=html to create a visual report (save to storage/phploc-report.html):
    php artisan phploc --output-format=html --output=storage/phploc-report.html
    
  • Export for External Tools: Output JSON for integration with tools like Grafana or custom dashboards:
    php artisan phploc --output-format=json --output=storage/phploc-metrics.json
    

Gotchas and Tips

Pitfalls

  1. False LOC Counts:

    • Issue: Phploc may overcount LOC in Blade templates or config files if not excluded.
    • Fix: Explicitly exclude non-PHP files in phploc.php:
      'exclude' => [
          'resources/views/*',
          'config/*',
          '*.blade.php',
      ],
      
  2. Performance on Large Codebases:

    • Issue: Scanning vendor/ or monorepos can be slow.
    • Fix: Limit directories or use --progress (if available in future versions) to monitor execution.
  3. Config File Missing:

    • Issue: Running php artisan phploc without publishing the config may throw errors.
    • Fix: Publish the config first or manually create config/phploc.php with defaults:
      return [
          'directories' => [base_path('app'), base_path('routes')],
          'exclude' => [],
          'logical_lines_only' => false,
      ];
      
  4. Deprecated CLI Options:

    • Issue: Options like --names (replaced by --suffix) may appear in old docs.
    • Fix: Refer to the latest changelog for valid flags.

Debugging

  • Silent Failures:

    • If the command runs but outputs nothing, check:
      • Permissions on target directories (chmod -R 755 app/).
      • PHP version compatibility (ensure ^7.4 || ^8.0 is met).
    • Run with --verbose (if supported) or check Laravel logs:
      php artisan phploc 2>&1 | grep -i error
      
  • Inconsistent Metrics:

    • Cause: Cached results or partial scans.
    • Fix: Clear cache and force a fresh scan:
      php artisan cache:clear
      php artisan phploc --force
      

Extension Points

  1. Custom Metrics:

    • Extend the Cmgmyr\PHPLOC\Application class to add project-specific metrics (e.g., "Laravel-specific complexity").
    • Example: Override getMetrics() in a service provider.
  2. Pre/Post-Scan Hooks:

    • Use Laravel’s registering and booted events in PhpLocServiceProvider to run logic before/after analysis:
      public function boot()
      {
          if ($this->app->runningInConsole()) {
              $this->commands([
                  (new \Cmgmyr\PHPLOC\Console\PhpLocCommand())
                      ->setMetricsCallback(function ($metrics) {
                          // Log custom metrics here
                      }),
              ]);
          }
      }
      
  3. Parallel Processing:

    • For large projects, consider splitting scans by directory and merging results (e.g., using parallel-lint-style workflows).

Laravel-Specific Tips

  • Service Provider Binding:

    • Bind the Phploc application to the container for reusable analysis:
      $this->app->singleton('phploc', function ($app) {
          return (new \Cmgmyr\PHPLOC\Application())
              ->addDirectory(base_path('app'))
              ->setExcludes([base_path('vendor')]);
      });
      
  • Dynamic Directory Scanning:

    • Dynamically set directories based on Laravel’s environment (e.g., exclude tests/ in production):
      'directories' => env('APP_ENV') === 'production'
          ? [base_path('app/Http')]
          : [base_path('app'), base_path('tests')],
      
  • Integration with Laravel Mix:

    • Trigger Phploc runs during npm run dev or npm run build for frontend-backend correlation:
      // webpack.mix.js
      mix.webpackConfig({
          plugins: [
              {
                  apply: (compiler) => {
                      compiler.hooks.done.tap('PhpLoc', () => {
                          require('child_process').execSync('php artisan phploc --log');
                      });
                  }
              }
          ]
      });
      
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata