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 P Laravel Package

andersundsehr/rector-p

Run Rector in large legacy projects file-by-file. rector-p prompts you per changed file to apply or skip changes, tracks unchanged files to speed repeats, supports running on specific paths/files, and can process only a chunk (e.g., 1/2) at a time.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require andersundsehr/rector-p
    

    Ensure your rector.php config exists (Laravel’s default Rector setup works here).

  2. First Run:

    rector-p
    
    • The tool scans your project for files that would change under Rector rules.
    • For each file with pending changes, it prompts:
      Apply changes to [file.php]? [y/N]
      
    • Type y to apply or n to skip.
  3. First Use Case: Refactor a single legacy file (e.g., a controller with deprecated Laravel helpers) without risking a full project-wide refactor.

    rector-p src/Http/Controllers/UserController.php
    

Where to Look First

  • Configuration: Your existing rector.php (no additional setup needed).
  • CLI Help: Run rector-p --help to explore options like --chunk, --startOver, or --dry-run.
  • Cache Location: ~/.rector-p/cache (tracks processed files; delete to reset with --startOver).

Implementation Patterns

Usage Patterns

1. Incremental Refactoring Workflow

  • Daily Local Work:
    rector-p --chunk=1/10 src/
    
    Process 10% of files daily, resuming where you left off.
  • Pre-Commit Hook: Add to .git/hooks/pre-commit to auto-refactor staged files:
    #!/bin/bash
    git diff --cached --name-only | xargs rector-p --no-interaction
    

2. Targeted Paths

  • Refactor only a module (e.g., app/Services/):
    rector-p app/Services/
    
  • Exclude specific files/dirs via Rector’s excludePaths in rector.php:
    return RectorConfig::create()->withPaths([__DIR__.'/src'])->withExcludePaths([__DIR__.'/tests']);
    

3. Chunked CI/CD Pipelines

  • Split work across branches/teams:
    • Branch A: rector-p --chunk=1/2 src/
    • Branch B: rector-p --chunk=2/2 src/
  • Automate in GitHub Actions:
    - name: Run Rector-P (Chunk 1/3)
      run: rector-p --chunk=1/3 --no-interaction
    

4. Dry Runs and Validation

  • Preview changes without applying:
    rector-p --dry-run src/Http/Controllers/
    
  • Pair with PHPUnit to validate refactored files:
    rector-p src/ && php artisan test --filter=UserControllerTest
    

Integration Tips

Laravel-Specific

  • Use Laravel Rector Presets:
    // rector.php
    use Rector\Laravel\Set\LaravelLevelSetList;
    return RectorConfig::create()
        ->withPaths([__DIR__.'/app'])
        ->withRules([
            LaravelLevelSetList::LEVEL_90, // Laravel 9+ rules
            \Rector\Php80\Rector\Class_\AnnotatedPropertyFetchToMethodCallRector::class,
        ]);
    
  • Blade Template Handling: Rector-p ignores Blade files by default. To include them, add:
    ->withPaths([__DIR__.'/resources/views'])
    ->withExcludePaths([__DIR__.'/resources/views/*.blade.php'])
    

Testing Strategies

  • Test-Driven Refactoring:
    1. Write a test for the file’s current behavior.
    2. Run rector-p --dry-run to preview changes.
    3. Apply changes and verify tests pass.
  • Mutation Testing: Use rector-p with pest --minimal to ensure refactored code doesn’t introduce regressions.

Team Collaboration

  • Shared State: Use --startOver to reset the cache when switching teams or environments.
  • Approval Workflow: Document a process for handling skipped files (e.g., "Revisit in 2 weeks" or "Exclude permanently").

Gotchas and Tips

Pitfalls

  1. Rule Conflicts:

    • Symptom: Rector fails silently on a file, leaving it "unchanged" in the cache.
    • Fix: Run with --verbose to debug:
      rector-p --verbose src/Controller/
      
    • Prevention: Start with a minimal rector.php and add rules incrementally.
  2. Cache Corruption:

    • Symptom: rector-p skips files unexpectedly or crashes.
    • Fix: Delete the cache and restart:
      rm -rf ~/.rector-p/cache && rector-p --startOver
      
  3. Interactive Mode in CI:

    • Symptom: --no-interaction still prompts for input.
    • Fix: Ensure the environment has no interactive TTY (e.g., GitHub Actions uses CI=true).
  4. Path Resolution Issues:

    • Symptom: rector-p can’t find files (e.g., No such file or directory).
    • Fix: Use absolute paths or getcwd()-relative paths:
      rector-p $(pwd)/src/
      
  5. Performance with Large Files:

    • Symptom: Slow processing on files with 10K+ lines (e.g., monolithic AppServiceProvider).
    • Fix: Split the file manually or exclude it from Rector’s paths.

Debugging

  • Log Output: Use --verbose or --vvv for debug-level logs:
    rector-p --vvv src/
    
  • Dry Run First: Always test with --dry-run before applying:
    rector-p --dry-run --verbose src/ | grep "Would change"
    
  • Check Rector’s Underlying Rules: If a file fails, run Rector directly to isolate the issue:
    vendor/bin/rector process src/File.php --dry-run
    

Configuration Quirks

  1. Chunk Mode:

    • Chunks are 1-based and inclusive (e.g., 2/2 = second half).
    • Useful for splitting work across PRs:
      # PR #1: First 30%
      rector-p --chunk=1/3 src/
      # PR #2: Next 30%
      rector-p --chunk=2/3 src/
      
  2. Quiet Mode:

    • --quiet suppresses all output except errors. Useful for CI:
      rector-p --quiet --no-interaction --chunk=1/5 src/
      
  3. Symfony Console Integration:

    • The package extends Symfony’s Command class. Customize behavior by overriding its execute() method in a subclass (advanced use case).

Extension Points

  1. Custom Prompt Logic: Override the interactive prompt by extending the package’s PartialCommand:

    // app/Console/Commands/CustomRectorCommand.php
    namespace App\Console\Commands;
    use AndersUndSehr\RectorP\Command\PartialCommand;
    class CustomRectorCommand extends PartialCommand {
        protected function askToApply(string $file): bool {
            // Custom logic (e.g., auto-approve files in `app/Old/`)
            return str_contains($file, 'Old/') || parent::askToApply($file);
        }
    }
    
  2. Pre/Post-Refactor Hooks: Use Rector’s RectorConfig to add hooks:

    ->withAutoloadFiles([__DIR__.'/rector-plugins.php'])
    

    Then define hooks in rector-plugins.php:

    RectorConfig::create()->withHooks([
        new \Rector\Hook\BeforeRefactorHook(function (FileRefactor $fileRefactor) {
            // Pre-refactor logic (e.g., log file contents)
        }),
    ]);
    
  3. Custom Cache Location: Override the default cache path by setting the RECTOR_P_CACHE_DIR environment variable:

    export RECTOR_P_CACHE_DIR=/custom/path/.rector-p-cache
    rector-p
    

Pro Tips

  • Pair with php-cs-fixer: Run rector-p followed by php-cs-fixer to auto-format refactored files:
    rector-p src/ && php-cs-fixer fix src/
    
  • Git Alias for Workflow: Add this to your .gitconfig to refactor staged files:
    [alias]
        rector = "!f() { git diff --cached --name-only | xargs vendor/bin/rector-p --
    
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.
terminal42/code-quality-tools
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