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

ergebnis/rector-rules

A curated set of custom Rector rules from ergebnis to automate PHP refactoring and style consistency. Includes rules for sorting arrays and match arms, simplifying call arguments, Faker updates, namespace symbol references, and PHPUnit attribute-to-prefix changes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev ergebnis/rector-rules
    

    Add the package to your rector.php config under imports:

    use Ergebnis\Rector\Rules;
    
  2. First Use Case: Run Rector with a single rule (e.g., RemoveNamedArgumentForSingleParameterRector) on a specific file or directory:

    vendor/bin/rector process src --dry-run --rules="[\Ergebnis\Rector\Rules\Expressions\CallLikes\RemoveNamedArgumentForSingleParameterRector]"
    
  3. Key Files to Review:

    • rector.php (main config file)
    • Rule-specific docs (e.g., doc/rules/Expressions/CallLikes/RemoveNamedArgumentForSingleParameterRector.md)

Implementation Patterns

Workflows

  1. Incremental Adoption:

    • Start with non-breaking rules (e.g., SortAssociativeArrayByKeyRector or SortMatchArmsByConditionalRector).
    • Use --dry-run to preview changes before applying them:
      vendor/bin/rector process src --dry-run
      
  2. Rule Grouping:

    • Group related rules in your rector.php config:
      return static::configure()
          ->withRules([
              \Ergebnis\Rector\Rules\Expressions\Arrays\SortAssociativeArrayByKeyRector::class,
              \Ergebnis\Rector\Rules\Expressions\Matches\SortMatchArmsByConditionalRector::class,
          ]);
      
  3. PHPUnit Migration:

    • Replace #[Test] attributes with test* prefixes in bulk:
      return static::configure()
          ->withRules([
              \Ergebnis\Rector\Rules\PHPUnit\ReplaceTestAttributeWithTestPrefixRector::class,
          ]);
      
  4. Namespace Optimization:

    • Consolidate use statements for large codebases:
      return static::configure()
          ->withRules([
              \Ergebnis\Rector\Rules\Files\ReferenceNamespacedSymbolsRelativeToNamespacePrefixRector::class,
          ])
          ->withConfiguration([
              'namespacePrefixes' => ['App\Domain', 'App\Infrastructure'],
          ]);
      
  5. Faker Updates:

    • Modernize Faker property accesses to method calls:
      return static::configure()
          ->withRules([
              \Ergebnis\Rector\Rules\Faker\GeneratorPropertyFetchToMethodCallRector::class,
          ]);
      

Integration Tips

  • CI/CD Pipeline: Add Rector as a pre-commit or pre-merge step to enforce consistency:

    # .github/workflows/rector.yml
    jobs:
      rector:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - run: composer require --dev ergebnis/rector-rules
          - run: vendor/bin/rector process src --dry-run
    
  • Custom Rule Sets: Extend the package by creating custom rule sets in rector.php:

    return static::configure()
        ->withRules([
            \Ergebnis\Rector\Rules\Expressions\CallLikes\RemoveNamedArgumentForSingleParameterRector::class,
            // Add custom rules here
        ]);
    
  • Parallel Processing: Use Rector’s parallel processing for large codebases:

    vendor/bin/rector process src --parallel
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts:

    • The ReferenceNamespacedSymbolsRelativeToNamespacePrefixRector may cause conflicts if multiple prefixes overlap. Test with --dry-run first.
    • Fix: Explicitly define namespacePrefixes to avoid ambiguity.
  2. Breaking Changes:

    • Rules like ReplaceTestAttributeWithTestPrefixRector or GeneratorPropertyFetchToMethodCallRector modify method signatures or API usage. Run tests thoroughly after applying them.
  3. Performance Overhead:

    • Rules like SortMatchArmsByConditionalRector or SortAssociativeArrayByKeyRector may slow down processing for large files. Use --parallel to mitigate this.
  4. False Positives:

    • The RemoveNamedArgumentForSingleParameterRector might incorrectly modify named arguments in multi-parameter calls if not configured properly.
    • Fix: Verify the rule’s logic or exclude specific files/directories.
  5. PHP Version Mismatches:

    • Some rules may not work as expected on older PHP versions (e.g., PHP 7.4). Ensure your rector.php specifies compatible PHP versions:
      return static::configure()
          ->withPhpVersion(810); // PHP 8.1
      

Debugging

  1. Dry Runs: Always use --dry-run to preview changes:

    vendor/bin/rector process src --dry-run --rules="[\Ergebnis\Rector\Rules\Files\ReferenceNamespacedSymbolsRelativeToNamespacePrefixRector]"
    
  2. Verbose Output: Enable verbose logging to debug rule application:

    vendor/bin/rector process src --verbose
    
  3. Excluding Files/Directories: Exclude problematic files or directories from processing:

    return static::configure()
        ->withPaths([
            __DIR__.'/src',
        ])
        ->withExcludedPaths([
            __DIR__.'/tests',
            __DIR__.'/vendor',
        ]);
    
  4. Rule-Specific Config: Misconfigured rules (e.g., discoverNamespacePrefixes: true with incorrect parentNamespacePrefixes) may lead to unexpected behavior. Validate configurations in the rule’s docs.

Tips

  1. Leverage discoverNamespacePrefixes: Automatically discover namespace prefixes for large projects:

    return static::configure()
        ->withRules([
            \Ergebnis\Rector\Rules\Files\ReferenceNamespacedSymbolsRelativeToNamespacePrefixRector::class,
        ])
        ->withConfiguration([
            'discoverNamespacePrefixes' => true,
            'parentNamespacePrefixes' => ['App', 'Domain'],
        ]);
    
  2. Combine Rules: Chain rules for comprehensive refactoring (e.g., sort arrays + remove named arguments):

    return static::configure()
        ->withRules([
            \Ergebnis\Rector\Rules\Expressions\Arrays\SortAssociativeArrayByKeyRector::class,
            \Ergebnis\Rector\Rules\Expressions\CallLikes\RemoveNamedArgumentForSingleParameterRector::class,
        ]);
    
  3. Custom Rule Sets: Create reusable rule sets in rector.php for different contexts (e.g., test, production):

    return static::configure()
        ->withRuleSets([
            'test' => [
                \Ergebnis\Rector\Rules\PHPUnit\ReplaceTestAttributeWithTestPrefixRector::class,
            ],
            'production' => [
                \Ergebnis\Rector\Rules\Expressions\CallLikes\RemoveNamedArgumentForSingleParameterRector::class,
            ],
        ]);
    
  4. Git Integration: Use Rector in combination with Git to track refactoring changes:

    git add -p  # Review changes interactively
    vendor/bin/rector process src --commit
    
  5. Document Rule Usage: Add comments in your codebase to explain Rector-driven changes:

    // Rector: RemoveNamedArgumentForSingleParameterRector
    strlen('hello');
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope