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

Php Coupling Detector Laravel Package

akeneo/php-coupling-detector

Detect PHP coupling issues based on configurable rules by analyzing class use statements. Supports forbidden, discouraged, and only rules, with error/warning violations. Includes commands to detect violations and list unused requirements.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require --dev akeneo/php-coupling-detector
    

    Add the package to your project’s composer.json under require-dev.

  2. Basic Configuration Create a coupling_detector.php config file in your project root (or extend Laravel’s config directory):

    return [
        'rules' => [
            'Laravel\\Framework\\Routing\\Router' => [
                'allowed' => [
                    'Laravel\\Http\\Request',
                    'Illuminate\\Contracts\\Routing\\UrlGenerator',
                ],
                'forbidden' => [
                    'App\\Services\\*', // Example: Avoid direct coupling to services
                ],
            ],
        ],
        'paths' => [
            app_path(),
            app('path.base') . '/Providers',
        ],
    ];
    
  3. First Run Execute the detector via Artisan (if integrated) or directly:

    vendor/bin/php-coupling-detector
    

    For Laravel, create a custom Artisan command (see Implementation Patterns).

  4. Review Output The tool outputs violations in a structured format (e.g., JSON or CLI table). Example:

    [ERROR] app/Http/Controllers/UserController.php:10
    - Coupling violation: Uses 'App\Services\UserService' (forbidden)
    - Rule: 'Laravel\Framework\Routing\Router' forbids 'App\Services\*'
    

Implementation Patterns

Workflows

  1. Rule Definition

    • Granularity: Define rules per class/method or globally (e.g., forbid App\Services\* in controllers).
    • Dynamic Rules: Load rules from a database or config file for flexibility:
      $rules = config('coupling_detector.rules');
      $detector->setRules($rules);
      
    • Wildcards: Use * for namespace matching (e.g., 'App\Repositories\*').
  2. Integration with Laravel

    • Artisan Command:
      // app/Console/Commands/DetectCoupling.php
      namespace App\Console\Commands;
      use Akeneo\CouplingDetector\Detector;
      class DetectCoupling extends Command {
          protected $signature = 'coupling:detect';
          public function handle() {
              $detector = new Detector(config('coupling_detector'));
              $violations = $detector->detect();
              $this->line(json_encode($violations, JSON_PRETTY_PRINT));
          }
      }
      
      Register the command in app/Console/Kernel.php:
      protected $commands = [
          Commands\DetectCoupling::class,
      ];
      
      Run with:
      php artisan coupling:detect
      
  3. CI/CD Pipeline

    • Fail builds on violations:
      # .github/workflows/coupling-check.yml
      jobs:
        coupling-check:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: vendor/bin/php-coupling-detector --fail-on-violations
      
  4. Visualization

    • Export violations to JSON/CSV and integrate with tools like SonarQube or GitHub Insights:
      file_put_contents(
          storage_path('app/coupling-violations.json'),
          json_encode($violations)
      );
      

Tips for Daily Use

  • Start Small: Begin with high-level rules (e.g., forbid App\Services\* in controllers) before diving into granular checks.
  • Exclude Tests: Add test directories to paths but exclude them from rule enforcement:
    'paths' => [
        app_path(),
        app_path('/Providers'),
    ],
    'exclude' => [
        app_path('/Tests'),
    ],
    
  • Leverage Laravel Events: Trigger coupling checks post-migration or post-deploy:
    // In a service provider
    Event::listen(Deployed::class, function () {
        $detector = new Detector(config('coupling_detector'));
        $violations = $detector->detect();
        if (!empty($violations)) {
            throw new \RuntimeException('Coupling violations detected!');
        }
    });
    

Gotchas and Tips

Pitfalls

  1. Performance

    • Large Codebases: The detector scans files recursively. For monorepos or large projects, limit paths to critical directories or run incrementally:
      vendor/bin/php-coupling-detector --paths=app/Http
      
    • Cache Results: Cache violations in a file/database to avoid rescanning unchanged code:
      $cacheFile = storage_path('coupling-cache.json');
      if (file_exists($cacheFile)) {
          $violations = json_decode(file_get_contents($cacheFile), true);
      } else {
          $violations = $detector->detect();
          file_put_contents($cacheFile, json_encode($violations));
      }
      
  2. False Positives

    • Static Analysis Limits: The detector uses static analysis (no runtime execution). False positives may occur with:
      • Dynamic class loading (e.g., class_alias).
      • Reflection-based dependencies (e.g., $service = new \App\Services\$className).
      • Workaround: Use allowed rules to whitelist edge cases:
        'allowed' => [
            'ReflectionClass',
        ],
        
  3. Rule Conflicts

    • Overlapping Rules: If a class is forbidden in multiple rules, the detector may report duplicate violations. Use priority in rules to resolve conflicts (if supported):
      'rules' => [
          'Laravel\Framework\Routing\Router' => [
            'forbidden' => ['App\Services\*'],
            'priority' => 10, // Higher priority = stricter
          ],
      ],
      
  4. Laravel-Specific Quirks

    • Service Container Coupling: The detector may flag app()->make() or resolve() calls as violations. Explicitly allow the container:
      'allowed' => [
          'Illuminate\Container\Container',
      ],
      
    • Facade Coupling: Facades (e.g., Cache::get()) are technically coupled to Illuminate\Support\Facades\Cache. Decide whether to allow or forbid:
      'forbidden' => [
          'Illuminate\Support\Facades\*',
      ],
      

Debugging

  • Verbose Output: Enable debug mode for detailed analysis:
    vendor/bin/php-coupling-detector --verbose
    
  • Inspect AST: The detector uses PHP’s Abstract Syntax Tree (AST). For complex cases, dump the AST of a file:
    $ast = include app_path('Http/Controllers/UserController.php');
    var_dump($ast);
    
  • Test Rules: Validate rules against a known violation:
    // Test file: app/Http/Controllers/TestController.php
    class TestController {
        public function __construct(\App\Services\ForbiddenService $service) {}
    }
    
    Run the detector and confirm the violation is caught.

Extension Points

  1. Custom Detectors Extend the base detector to add logic (e.g., check for circular dependencies):

    namespace App\Coupling;
    use Akeneo\CouplingDetector\Detector;
    class CircularDependencyDetector extends Detector {
        public function detectCircularDependencies() {
            // Custom logic
        }
    }
    
  2. Plugin System Design a plugin architecture to support:

    • Custom Rule Formats: YAML/JSON rule files.
    • Adapters: Integrate with PHPStan or Psalm for richer analysis.
    • Example Plugin:
      // app/Coupling/Plugins/JsonRuleLoader.php
      namespace App\Coupling\Plugins;
      use Akeneo\CouplingDetector\RuleLoaderInterface;
      class JsonRuleLoader implements RuleLoaderInterface {
          public function load(string $file): array {
              return json_decode(file_get_contents($file), true);
          }
      }
      
  3. Git Hooks Automate checks on pre-commit or pre-push:

    # .git/hooks/pre-commit
    #!/bin/bash
    vendor/bin/php-coupling-detector --fail-on-violations
    
  4. IDE Integration

    • PHPStorm: Use the detector’s output to create custom inspections.
    • VSCode: Parse violations into a task list via a custom extension.
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver