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

Rector Laravel Laravel Package

driftingly/rector-laravel

Rector extension for Laravel that applies automated refactors and upgrade rules based on your composer.json or selected Laravel version sets. Includes rules for core Laravel and first‑party packages like Cashier and Livewire.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev driftingly/rector-laravel
    

    Add the package as a dev dependency to avoid bloating production builds.

  2. Basic Configuration: Create or update rector.php in your project root with:

    <?php declare(strict_types=1);
    
    use Rector\Config\RectorConfig;
    use RectorLaravel\Set\LaravelSetProvider;
    
    return RectorConfig::configure()
        ->withSetProviders(LaravelSetProvider::class)
        ->withComposerBased(laravel: true);
    

    This auto-detects your Laravel version from composer.json and applies version-specific rules.

  3. First Run:

    vendor/bin/rector process src
    

    Process your src directory (adjust paths as needed). Use --dry-run first to preview changes.

First Use Case

Upgrade from Laravel 11 to 12:

composer require --dev driftingly/rector-laravel

Configure rector.php as above, then run:

vendor/bin/rector process src --level=UP_TO_LARAVEL_120

This applies all rules needed for the upgrade, including:

  • Facade alias updates (e.g., Cache::Cache::class).
  • Container string-to-FQN conversions.
  • Eloquent magic method replacements.

Implementation Patterns

Workflows

  1. Version-Specific Upgrades: Use LaravelLevelSetList constants for targeted upgrades:

    ->withSets([
        LaravelLevelSetList::LARAVEL_130, // Rules for 12→13
        LaravelLevelSetList::LARAVEL_140, // Rules for 13→14
    ])
    

    Higher versions include lower-version rules automatically.

  2. Code Quality Improvements: Combine sets for incremental refactoring:

    ->withSets([
        LaravelSetList::LARAVEL_CODE_QUALITY, // Replaces `$this->app['...']`
        LaravelSetList::LARAVEL_COLLECTION,  // Modernizes collection methods
        LaravelSetList::LARAVEL_TYPE_DECLARATIONS, // Adds type hints
    ])
    
  3. Testing Integration: Use LaravelSetList::LARAVEL_TESTING to modernize tests:

    ->withSets([
        LaravelSetList::LARAVEL_TESTING,
    ])
    

    Example transformations:

    • assertViewHas()assertViewHasAll().
    • Legacy assertDatabaseHas() → modern assertions.
  4. CI/CD Pipeline: Add a GitHub Action or GitLab CI step:

    # .github/workflows/rector.yml
    - name: Run Rector
      run: vendor/bin/rector process src --dry-run
    

    Use --dry-run to fail builds on changes without committing them.

Integration Tips

  • Exclude Files/Directories:
    ->withPaths([
        __DIR__ . '/src',
    ])
    ->withExcludedPaths([
        __DIR__ . '/tests/Feature/OldCode.php',
    ]);
    
  • Parallel Processing: Speed up large codebases with:
    vendor/bin/rector process src --parallel
    
  • Custom Rule Sets: Combine existing sets or create custom ones:
    ->withSets([
        Rector\Set\PHP80,
        LaravelSetList::LARAVEL_STATIC_TO_INJECTION,
    ]);
    

Gotchas and Tips

Pitfalls

  1. False Positives in UP_TO_LARAVEL_X Sets:

    • Rules in UP_TO_LARAVEL_130 may not apply if your codebase already uses Laravel 13 patterns.
    • Fix: Use --dry-run to preview changes and manually review.
  2. Facade-to-DI Conflicts:

    • LARAVEL_STATIC_TO_INJECTION may break code relying on facades in constructors.
    • Fix: Exclude problematic files or use partial sets:
      ->withSets([
          LaravelSetList::LARAVEL_STATIC_TO_INJECTION,
      ])
      ->withExcludedNodes([
          new PhpDocNode('*@inject*'),
      ]);
      
  3. Collection Method Ambiguity:

    • Some LARAVEL_COLLECTION rules may conflict with custom collection macros.
    • Fix: Test with --dry-run and exclude ambiguous methods:
      ->withExcludedNodes([
          new MethodCallNode('Illuminate\Support\Collection', 'customMacro'),
      ]);
      
  4. Database Schema Changes:

    • Rules like WhereToWhereLikeRector may alter query logic if not tested.
    • Fix: Run migrations and tests after applying database-related rules.
  5. Legacy Factory Conflicts:

    • LARAVEL_LEGACY_FACTORIES_TO_CLASSES may fail if factories use dynamic properties.
    • Fix: Manually update factories or exclude them:
      ->withExcludedPaths([
          __DIR__ . '/database/factories/OldFactory.php',
      ]);
      

Debugging

  1. Verbose Output:

    vendor/bin/rector process src --verbose
    

    Shows detailed rule application logs.

  2. Rule-Specific Debugging: Use --only to test individual rules:

    vendor/bin/rector process src --only LaravelSetList::LARAVEL_ELOQUENT_MAGIC_METHOD_TO_QUERY_BUILDER
    
  3. Git Diff Analysis: After a dry run, inspect changes with:

    git diff --name-only
    

    Revert unwanted changes with:

    git checkout -- .
    

Configuration Quirks

  1. Composer-Based Detection:

    • Ensure composer.json accurately reflects your Laravel version.
    • Fix: Manually specify versions if auto-detection fails:
      ->withComposerBased(laravel: '12.*')
      
  2. Rule Order Matters:

    • Some rules depend on others (e.g., LARAVEL_ARRAYACCESS_TO_METHOD_CALL before LARAVEL_CONTAINER_STRING_TO_FULLY_QUALIFIED_NAME).
    • Fix: Group related sets or use explicit rule ordering:
      ->withRules([
          \RectorLaravel\Rector\MethodCall\ArrayAccessToMethodCallRector::class,
          \RectorLaravel\Rector\MethodCall\ContainerStringToFqnRector::class,
      ]);
      
  3. IDE Support:

    • After running Rector, restart your IDE (PHPStorm/VSCode) to update symbol indexes.
    • For PHPStan/Nikita, regenerate baseline files:
      vendor/bin/phpstan generate-baseline
      

Extension Points

  1. Custom Rules: Generate a new rule with:

    composer make:rule -- MyCustomRule
    

    Example: Convert Str::of($var)->upper() to Str::upper($var):

    // src/Rector/StaticCall/MyCustomRuleRector.php
    public function refactor(StaticCall $staticCall): ?StaticCall
    {
        if ($staticCall->getName() === 'of' && $staticCall->getParent() instanceof StaticCall) {
            $parent = $staticCall->getParent();
            if ($parent->getName() === 'upper' && $parent->getClass() instanceof StaticNode) {
                $parent->setArguments([$staticCall->getArguments()[0]]);
                return $parent;
            }
        }
        return null;
    }
    
  2. Conditional Rule Application: Use Rector\Contract\Rector\ConfigurableRectorInterface for dynamic rules:

    public function getConfiguration(): array
    {
        return [
            'only_if' => fn(Node $node) => $node instanceof ClassMethod && str_contains($node->getName(), 'test'),
        ];
    }
    
  3. Pre/Post-Processing: Hook into Rector’s lifecycle with Rector\Contract\Rector\RectorInterface:

    public function refactor(Node $node): ?Node
    {
        if ($node instanceof Class_) {
            $this->logger->info('Processing class: ' . $node->getName());
        }
        return null;
    }
    
  4. Testing Rules: Use Rector’s testing utilities:

    // tests/Rector/MyCustomRuleRectorTest.php
    public function provideTestCases(): iterable
    {
        yield 'converts Str::of()->upper()' => [
            <<<'PHP'
            use Illuminate\Support\Str;
            Str::of('test')->upper();
            PHP,
            <<<'PHP'
            use Illuminate\Support\Str;
            Str
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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