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

amashukov/rector-php-rules

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev amashukov/rector-php-rules
    
  2. Configure Rector: Add the package to your rector.php with the rules you want to enforce. Start with a minimal setup to avoid overwhelming your team:

    return RectorConfig::configure()
        ->withPaths([__DIR__ . '/src', __DIR__ . '/tests'])
        ->withRules([
            NoPhpstanIgnoreRector::class,
            NoSuperglobalAccessRector::class,
            NoAssertCallInSrcRector::class,
        ]);
    
  3. First Use Case: Run a dry run to identify violations without modifying files:

    vendor/bin/rector process --dry-run
    

    This will show you where the rules would apply, allowing you to review and address issues incrementally.


Implementation Patterns

Workflows

  1. Incremental Adoption:

    • Start with non-breaking rules (e.g., NoPhpstanIgnoreRector, NoSuperglobalAccessRector) that enforce best practices without rewriting logic.
    • Gradually introduce stricter rules (e.g., NoAssertCallInSrcRector, RequirePsrClockInterfaceRector) as the team adapts.
    • Use path filtering in rector.php to scope rules to specific directories (e.g., skip migrations/ or vendor/).
  2. CI Integration:

    • Add a pre-commit hook or GitHub Actions workflow to run Rector in dry-run mode:
      # .github/workflows/rector.yml
      jobs:
        rector:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - run: composer install
            - run: vendor/bin/rector process --dry-run
      
    • Fail the build if violations are found, requiring developers to address them before merging.
  3. Team Onboarding:

    • Document the why behind each rule in your team’s coding standards (e.g., link to the Rule Catalogue).
    • Provide examples of BAD/GOOD patterns in your project’s README or CONTRIBUTING.md.
    • Schedule a code review session to walk through common violations and fixes.
  4. Customizing Rules:

    • Override default paths or skip specific files/directories:
      ->skip([
          __DIR__ . '/src/Some/Excluded/Class.php',
          __DIR__ . '/tests/Unit/OldTests/',
      ])
      
    • Extend rules by creating custom Rector classes (see Rector’s documentation).

Integration Tips

  1. Pair with PHPStan:

    • Use NoPhpstanIgnoreRector alongside PHPStan to eliminate suppressions. Configure PHPStan to run in level 9 (strictest) mode:
      composer require --dev phpstan/phpstan
      vendor/bin/phpstan analyse --level=9 src/
      
  2. Combine with Other Tools:

    • Psalm: Use NoPhpstanIgnoreRector to also target @psalm-suppress annotations.
    • Pint: Run NoCommentsOutsideInterfaceMethodDocBlockRector alongside PHP-CS-Fixer or Pint for consistent formatting:
      composer require --dev friendsofphp/pint
      vendor/bin/pint
      vendor/bin/rector process
      
  3. Testing Rules:

    • For test-specific rules (e.g., NoDirectDbMutationInFunctionalTestsRector), ensure your test suite uses factories or repositories instead of direct DB access:
      // BAD (direct DB)
      $user = DB::table('users')->find(1);
      
      // GOOD (via repository)
      $user = $this->userRepository->find(1);
      
  4. YAML Hygiene:

    • Apply YamlNoCommentsRector to config files (e.g., config/services.yaml) to enforce comment-free YAML:
      ->withConfiguredRule(YamlNoCommentsRector::class, [
          YamlNoCommentsRector::PATHS => [__DIR__ . '/config'],
      ])
      

Gotchas and Tips

Pitfalls

  1. False Positives in Legacy Code:

    • Rules like NoSuperglobalAccessRector or NoEnvironmentCheckInSrcRector may flag legacy code that relies on globals or env checks. Use skip() to exclude such files temporarily while refactoring:
      ->skip([__DIR__ . '/src/Legacy/EnvChecker.php'])
      
  2. Overly Aggressive Rules:

    • Some rules (e.g., NoCommentsOutsideInterfaceMethodDocBlockRector) may remove useful documentation. Review the output of // RECTOR-BAN markers carefully before applying such rules broadly.
  3. Test-Specific Rules:

    • Rules like NoAssertInsideIfInFunctionalTestsRector or NoArrayAssertContainsInTestsRector can break existing tests. Refactor tests incrementally to avoid massive failures:
      // BAD (conditional assertion)
      if ($status === 'active') {
          self::assertTrue($user->isActive());
      }
      
      // GOOD (extract helper)
      private function assertUserIsActive(User $user): void {
          self::assertTrue($user->isActive());
      }
      
  4. YAML Rule Quirks:

    • The YamlNoCommentsRector strips all comments by default, including those in *.yaml files. If you rely on comments in configs (e.g., for ADRs), exclude those files:
      ->withConfiguredRule(YamlNoCommentsRector::class, [
          YamlNoCommentsRector::PATHS => [__DIR__ . '/config/production'],
          YamlNoCommentsRector::SKIP => [__DIR__ . '/config/adr/*.yaml'],
      ])
      

Debugging

  1. Dry-Run First: Always run rector process --dry-run to see violations before applying changes:

    vendor/bin/rector process --dry-run --format=json > rector-violations.json
    
  2. Inspect Markers: Look for // RECTOR-BAN: comments in your code. These indicate where rules would apply:

    // RECTOR-BAN: NoSuperglobalAccessRector found $_ENV['API_KEY'] at line 42
    
  3. Rule-Specific Debugging:

    • For NoAssertCallInSrcRector, ensure you replace assert() with explicit throw or if checks.
    • For RequirePsrClockInterfaceRector, verify that all new DateTime() calls are replaced with injected ClockInterface:
      // BAD
      $now = new DateTime();
      
      // GOOD
      $now = $this->clock->now();
      
  4. CI Debugging: If Rector fails in CI, check the exit code:

    • Exit code 1: Violations found (fix them).
    • Exit code 2: Configuration error (check rector.php).

Extension Points

  1. Custom Rules: Extend the package by creating your own Rector rules. For example, to ban strtolower() in favor of Stringable::toLowerCase():

    use Rector\Core\Contract\RectorInterface;
    use Rector\Core\PhpParser\Node\BetterNodeFinder;
    use PhpParser\Node;
    
    final class NoStrtolowerRector implements RectorInterface {
        public function getRuleDefinition(): RuleDefinition {
            return new RuleDefinition('Bans strtolower() in favor of Stringable::toLowerCase().');
        }
    
        public function refactor(Node $node): ?Node {
            $betterNodeFinder = new BetterNodeFinder();
            $nodes = $betterNodeFinder->findInstanceOf($node, FunctionCall::class);
            foreach ($nodes as $functionCall) {
                if ($functionCall->name->toString() === 'strtolower') {
                    return new Node\Expr\MethodCall(
                        $functionCall->args[0]->value,
                        'toLowerCase'
                    );
                }
            }
            return null;
        }
    }
    
  2. Conditional Rules: Use Rector’s Condition to apply rules conditionally (e.g., only in src/):

    ->withRules([
        new NoSuperglobalAccessRector(),
    ])
    ->withConditions([
        new NotMatchCondition('tests/'),
    ])
    
  3. Post-Rector Hooks: Combine Rector with other tools using composer scripts:

    {
      "scripts": {
        "rector": "vendor/bin/rect
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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