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

Php Cs Fixer Laravel Package

fabpot/php-cs-fixer

PHP CS Fixer is a command-line tool for automatically fixing PHP coding standards issues. It formats and modernizes code using configurable rulesets, supports custom rule configurations, and helps keep projects consistent and clean across teams and CI.

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require --dev fabpot/php-cs-fixer
    

    Initialize the default config (optional but recommended):

    vendor/bin/php-cs-fixer fix --config=vendor/fabpot/php-cs-fixer.php.dist --dry-run
    
  2. First Use Case Run a dry-run on a single file to verify behavior:

    vendor/bin/php-cs-fixer fix app/Http/Controllers/ExampleController.php --dry-run
    

    Check the output for changes without modifying files.

  3. Where to Look First

    • Default Config: vendor/fabpot/php-cs-fixer.php.dist (PSR12 by default).
    • CLI Help: vendor/bin/php-cs-fixer --help for available rules and options.
    • Rule Documentation: PHP-CS-Fixer Rules (official docs).

Implementation Patterns

Workflows

  1. Pre-Commit Hook Integrate with Git hooks (e.g., pre-commit) to auto-fix files before commits:

    vendor/bin/php-cs-fixer fix --dry-run --diff --allow-risky=yes
    
    • Use --diff to show changes in Git diff format.
    • --allow-risky=yes skips potentially unsafe fixes (e.g., modifying class constants).
  2. CI Pipeline Run in CI to enforce standards (fail build if fixes are needed):

    vendor/bin/php-cs-fixer fix --level=psr12 --dry-run --diff --stop-on-failure
    
    • --stop-on-failure exits with non-zero if fixes are required.
    • --level=psr12 enforces PSR12 rules (adjust as needed).
  3. Custom Config Extend the default config in .php-cs-fixer.dist.php:

    <?php
    return PhpCsFixer\Config::create()
        ->setRules([
            '@PSR12' => true,
            'no_unused_imports' => true,
            'ordered_imports' => ['sort_algorithm' => 'alpha'],
            'phpdoc_align' => false, // Disable if not needed
        ])
        ->setRiskyAllowed(true)
        ->setFinder(
            PhpCsFixer\Finder::create()
                ->in(__DIR__.'/app')
                ->exclude('app/Helpers')
        );
    
    • Key Methods:
      • setRules(): Override or add rules (use @Symfony presets for framework-specific rules).
      • setFinder(): Target specific directories/files (exclude tests, helpers, etc.).
      • setRiskyAllowed(): Enable/disable risky fixes globally.
  4. Incremental Fixing Use --path-mode=diff to only fix changed files in a PR:

    vendor/bin/php-cs-fixer fix --path-mode=diff --diff
    

Integration Tips

  • Laravel-Specific Rules: Enable Symfony presets for Laravel compatibility:
    return PhpCsFixer\Config::create()
        ->setRules([
            '@Symfony' => true,
            '@Symfony:risky' => true, // Enable risky Symfony rules
            'no_unused_imports' => true,
        ]);
    
  • IDE Integration: Configure your IDE (PHPStorm, VSCode) to use PHP-CS-Fixer for on-save formatting:
    • PHPStorm: Settings > Tools > PHP > Code Sniffer > Set PHP-CS-Fixer as default.
    • VSCode: Install the "PHP CS Fixer" extension and link it to the binary.
  • Parallel Processing: Speed up large codebases with --parallel:
    vendor/bin/php-cs-fixer fix --parallel
    

Gotchas and Tips

Pitfalls

  1. Risky Fixes

    • Some rules (e.g., class_definition, final_class) can break functionality.
    • Solution: Use --allow-risky=yes cautiously or disable risky rules:
      ->setRiskyAllowed(false)
      ->setRules(['@Symfony:risky' => false])
      
  2. Performance

    • Large codebases (e.g., 10K+ files) may slow down CI.
    • Solution:
      • Use --path-mode=diff in CI to only check changed files.
      • Cache results with php-cs-fixer cache:clear if rules change frequently.
  3. Config Conflicts

    • Merging .php-cs-fixer.dist.php from multiple sources can cause conflicts.
    • Solution: Use php-cs-fixer config:dump to generate a fresh config:
      vendor/bin/php-cs-fixer config:dump --standard=PSR12 > .php-cs-fixer.dist.php
      
  4. False Positives

    • Rules like no_unused_imports may flag Laravel-specific imports (e.g., use Illuminate\Support\Facades\Route;).
    • Solution: Exclude specific files/directories or disable the rule:
      ->setFinder(PhpCsFixer\Finder::create()->exclude('app/Providers'))
      
  5. Line Endings

    • PHP-CS-Fixer may normalize line endings (\n vs \r\n), causing Git noise.
    • Solution: Use --line-ending=unix or configure Git to handle line endings.

Debugging

  • Dry-Run Mode: Always use --dry-run first to preview changes:
    vendor/bin/php-cs-fixer fix --dry-run --diff
    
  • Verbose Output: Enable debug mode for detailed logs:
    vendor/bin/php-cs-fixer fix -v
    
  • Rule-Specific Debugging: Test individual rules with --rules:
    vendor/bin/php-cs-fixer fix --rules=ordered_imports --diff
    

Extension Points

  1. Custom Rules Extend PHP-CS-Fixer with custom rules by creating a RuleSet class:

    // CustomRule.php
    use PhpCsFixer\Fixer\FixerInterface;
    use PhpCsFixer\Fixer\ConfigurableFixerInterface;
    use PhpCsFixer\Tokenizer\Tokens;
    
    class CustomRule implements FixerInterface, ConfigurableFixerInterface {
        public function isCandidate(Tokens $tokens) { /* ... */ }
        public function isRisky() { return false; }
        public function fix(PhpCsFixer\Tokenizer\Tokens $tokens) { /* ... */ }
        public function getConfiguration() { return []; }
    }
    

    Register it in your config:

    ->registerCustomFixers([__DIR__.'/CustomRule.php'])
    
  2. Parallel Processing For custom rules, ensure thread safety by avoiding static state.

  3. Integration with Laravel Artisan Create a custom Artisan command for team-wide usage:

    php artisan make:command FixCs
    

    Example:

    // app/Console/Commands/FixCs.php
    namespace App\Console\Commands;
    use Illuminate\Console\Command;
    use Symfony\Component\Process\Process;
    
    class FixCs extends Command {
        protected $signature = 'fix:cs {--dry-run}';
        protected $description = 'Run PHP-CS-Fixer';
    
        public function handle() {
            $process = new Process(['vendor/bin/php-cs-fixer', 'fix', $this->option('dry-run') ? '--dry-run' : null]);
            $process->run();
            $this->output->write($process->getOutput());
            if (!$process->isSuccessful()) exit(1);
        }
    }
    

    Run with:

    php artisan fix:cs --dry-run
    

Config Quirks

  • Preset Overrides: Presets (e.g., @PSR12, @Symfony) can be overridden partially:
    ->setRules([
        '@PSR12' => true,
        'no_unused_imports' => false, // Disable only this rule
    ])
    
  • Finder Exclusions: Exclude files/directories using glob patterns:
    ->setFinder(
        PhpCsFixer\Finder::create()
            ->in(__DIR__)
            ->exclude(['vendor', 'storage', 'tests', '*.blade.php'])
    )
    
  • Cache Directory: PHP-CS-Fixer caches tokenized files for performance. Clear it if rules change:
    vendor/bin/php-cs-fixer cache:clear
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport