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

Ranger Laravel Package

laravel/ranger

Beta Laravel introspection library that scans your codebase to discover routes, models, enums, broadcast events, env vars, and Inertia components. Register callbacks per item or collection and receive rich DTOs as Ranger walks your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/ranger
    

    Register the service provider in config/app.php under providers:

    Laravel\Ranger\RangerServiceProvider::class,
    
  2. First Use Case: Run a basic scan in a command or controller:

    use Laravel\Ranger\Ranger;
    
    $ranger = app(Ranger::class);
    $ranger->walk(); // Triggers all registered callbacks
    
  3. Key Files:

    • app/Providers/RangerServiceProvider.php (if customizing)
    • config/ranger.php (future config, currently minimal)
    • app/Console/Commands/ (for CLI integration)

Implementation Patterns

Core Workflow: Component Discovery

  1. Register Callbacks:

    // Individual items
    $ranger->onRoute(fn($route) => $this->logRoute($route));
    $ranger->onModel(fn($model) => $this->analyzeModel($model));
    
    // Entire collections
    $ranger->onRoutes(fn(Collection $routes) => $this->generateRouteMap($routes));
    
  2. DTO-Based Processing: Each callback receives a DTO with structured data:

    $ranger->onModel(function (Components\Model $model) {
        $model->getAttributes(); // ['name' => 'string', 'email' => 'string']
        $model->getRelations();  // ['user' => 'App\Models\User']
        $model->getFilePath();   // 'app/Models/User.php'
    });
    
  3. Common Use Cases:

    • API Documentation: Generate OpenAPI/Swagger specs from routes.
    • Model Validation: Auto-generate validation rules from model attributes.
    • Inertia Prop Analysis: Detect required/optional props for type safety.
    • Environment Auditing: Log sensitive .env variables.
  4. Integration with Laravel Features:

    • Commands:
      use Laravel\Ranger\Ranger;
      
      class ScanCommand extends Command {
          public function handle() {
              $ranger = app(Ranger::class);
              $ranger->walk();
              // Process results...
          }
      }
      
    • Service Providers:
      public function boot() {
          $ranger = app(Ranger::class);
          $ranger->onRoutes($this->generateRouteCache(...));
      }
      
  5. Conditional Processing:

    $ranger->onRoute(function (Components\Route $route) {
        if ($route->isApi()) {
            $this->generateApiDocs($route);
        }
    });
    

Gotchas and Tips

Pitfalls

  1. Performance:

    • Ranger scans the entire codebase. Use in development or CI pipelines, not production.
    • For large apps, process collections (onRoutes, onModels) instead of individual items.
  2. Beta API:

    • DTO structures may change before v1.0. Avoid relying on undocumented properties.
    • Check the changelog for breaking changes.
  3. Route URIs:

    • Explicit Route::domain() URIs are returned relative to APP_URL (not absolute).
    • Example: domain('admin.app')->uri('users')/admin/users (not https://admin.app/users).
  4. Model Attributes:

    • $hidden, $visible, and $appends are respected (since v0.2.4), but custom casts may not be fully reflected.
  5. Inertia Props:

    • Union types (e.g., string|int) in Inertia props require v0.2.3+ for accurate detection.

Debugging Tips

  1. Inspect DTOs:

    $ranger->onRoute(function (Components\Route $route) {
        dd($route->toArray()); // Debug full structure
    });
    
  2. Filter Components:

    $ranger->onRoute(function (Components\Route $route) {
        if (str_contains($route->uri(), 'admin')) {
            $this->processAdminRoute($route);
        }
    });
    
  3. Skip Unnecessary Scans:

    • Exclude directories (e.g., tests/, workbench/) by modifying RangerServiceProvider:
      protected function getExcludedDirectories(): array {
          return array_merge(parent::getExcludedDirectories(), ['storage/', 'vendor/']);
      }
      
  4. Handle Missing Data:

    • Some collectors (e.g., BroadcastEvents) may return empty collections if no events are found.

Extension Points

  1. Custom Collectors: Extend Laravel\Ranger\Collectors\Collector to scan additional components (e.g., custom macros):

    class MacroCollector extends Collector {
        public function collect() {
            return $this->app->make(MacroAnalyzer::class)->analyze();
        }
    }
    
  2. Modify DTOs: Override DTO properties in a service provider:

    $ranger->onRoute(function (Components\Route $route) {
        $route->setCustomTag('api' => $route->uri() === '/api');
    });
    
  3. Post-Processing: Chain callbacks to transform data:

    $ranger->onModels(function (Collection $models) {
        $models->each(fn($model) => $this->validateModel($model));
    });
    
  4. Environment Variables:

    • Sensitive variables (e.g., DB_PASSWORD) are not exposed by default. Use cautiously:
      $ranger->onEnv(function (Components\Env $env) {
          if ($env->isSensitive()) {
              $this->logSensitiveVar($env->name());
          }
      });
      

Pro Tips

  • Generate API Docs: Combine with spatie/laravel-api-docs or darkaonline/l5-swagger by extracting route metadata.
  • Type-Safe Inertia: Use Ranger to auto-generate TypeScript interfaces for Inertia props:
    $ranger->onInertiaComponent(function (Components\InertiaComponent $component) {
        $this->generateTypeScriptInterface($component);
    });
    
  • Validation Rules: Auto-generate Laravel validation rules from model attributes:
    $ranger->onModels(function (Collection $models) {
        $models->each(fn($model) => $this->generateValidationRules($model));
    });
    
  • Dependency Analysis: Detect unused models/enums by comparing Ranger results with actual usage in routes/controllers.

```markdown
### Example: Full Command Integration
```php
use Laravel\Ranger\Ranger;
use Illuminate\Console\Command;

class RangerAuditCommand extends Command {
    protected $signature = 'ranger:audit';
    protected $description = 'Audit application components with Ranger';

    public function handle() {
        $ranger = app(Ranger::class);

        // Route analysis
        $ranger->onRoutes(function (Collection $routes) {
            $this->info("Found {$routes->count()} routes");
            $routes->each(fn($route) => $this->line("• {$route->method()} {$route->uri()}"));
        });

        // Model validation
        $ranger->onModels(function (Collection $models) {
            $models->each(fn($model) => $this->generateValidationRules($model));
        });

        $ranger->walk();
    }

    protected function generateValidationRules(Components\Model $model) {
        $rules = [];
        foreach ($model->getAttributes() as $name => $type) {
            $rules[$name] = match ($type) {
                'string' => 'required|string',
                'integer' => 'required|integer',
                default => 'required',
            };
        }
        $this->line("<comment>Validation for {$model->getName()}:</comment>");
        $this->line(print_r($rules, true));
    }
}
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
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