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

ergebnis/php-cs-fixer-config

Factory package for friendsofphp/php-cs-fixer configs. Provides ready-made rule sets per PHP version (5.3–8.5) and helpers to build a consistent, reusable fixer configuration for your projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require --dev ergebnis/php-cs-fixer-config
    
  2. Create .php-cs-fixer.php in your project root:

    <?php
    declare(strict_types=1);
    
    use Ergebnis\PhpCsFixer\Config;
    use PhpCsFixer\Finder;
    
    $ruleSet = Config\RuleSet\Php83::create(); // Pick your PHP version
    $finder = Finder::create()->in(__DIR__);
    
    return Config\Factory::fromRuleSet($ruleSet)
        ->setCacheFile(__DIR__ . '/.build/php-cs-fixer/.php-cs-fixer.cache')
        ->setFinder($finder);
    
  3. Add cache directory to .gitignore:

    +/.build/
    
  4. Run CS Fixer:

    vendor/bin/php-cs-fixer fix
    

First Use Case

Use this package to standardize your Laravel project’s code style by:

  • Enforcing consistent formatting (e.g., PHP 8.3 rules for modern Laravel projects).
  • Automatically fixing violations via CI/CD or pre-commit hooks.
  • Example: Run in a GitHub Actions workflow or Laravel Forge deploy hook.

Implementation Patterns

1. Version-Specific Rule Sets

Leverage pre-configured rule sets for different PHP versions (e.g., Php82 for Laravel 9.x, Php83 for Laravel 10.x). Override defaults as needed:

$ruleSet = Config\RuleSet\Php83::create()
    ->withRules(Config\Rules::fromArray([
        'array_syntax' => ['syntax' => 'short'], // Force short array syntax
        'no_unused_imports' => true, // Strict unused imports check
    ]));

2. Integration with Laravel Workflows

  • Pre-Commit Hook: Use husky + php-cs-fixer to block non-compliant code:
    composer require --dev husky
    npx husky add .husky/pre-commit "vendor/bin/php-cs-fixer fix --dry-run --diff"
    
  • CI/CD: Add to Laravel’s phpunit.xml or GitHub Actions:
    - name: Run PHP-CS-Fixer
      run: vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run
    

3. Custom Fixers for Laravel-Specific Rules

Extend with custom fixers (e.g., for Laravel’s Route::prefix or Blade templates):

$ruleSet = Config\RuleSet\Php83::create()
    ->withCustomFixers(Config\Fixers::fromFixers(
        new \YourVendor\LaravelCsFixer\BladeFixer(),
    ))
    ->withRules(Config\Rules::fromArray([
        'YourVendor/blade_indentation' => true,
    ]));

4. Header Management

Add project-specific headers to all PHP files:

$header = <<<EOF
 * Copyright (c) 2024 Your Company
 * Laravel Project: {{ project_name }}
EOF;

$ruleSet = Config\RuleSet\Php83::create()->withHeader($header);

5. Performance Optimization

  • Cache: Enable caching (setCacheFile) to avoid re-parsing files.
  • Parallel Processing: Use --parallel flag for large codebases:
    vendor/bin/php-cs-fixer fix --parallel
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • Rule sets like Php83 may include PHP 8.3-specific rules (e.g., readonly_properties) that break older PHP versions. Test in your Laravel environment first.
    • Fix: Use Php82 for Laravel 9.x or validate with php-cs-fixer fix --dry-run.
  2. Custom Fixer Conflicts:

    • Third-party fixers (e.g., erickskrauch/php-cs-fixer-custom-fixers) might override core rules. Audit changes with --diff:
      vendor/bin/php-cs-fixer fix --diff
      
  3. Git Ignore Oversight:

    • Forgetting to add .build/php-cs-fixer to .gitignore can bloat your repo with cache files.
    • Fix: Use a template like laravel/gitignore.
  4. Rule Overrides Not Applied:

    • Rules merged via withRules() may be overridden by the base rule set. Use Config\Rules::fromArray() with true/false to force values:
      ->withRules(Config\Rules::fromArray([
          'strict_comparison' => true, // Explicitly enable
      ]))
      

Debugging Tips

  • Dry Run: Always test changes first:
    vendor/bin/php-cs-fixer fix --dry-run --diff
    
  • Verbose Output: Debug with --verbose to see skipped files:
    vendor/bin/php-cs-fixer fix --verbose
    
  • Rule Documentation: Check PHP-CS-Fixer’s docs for rule specifics (e.g., array_syntax supports short, short_braced, or braced).

Extension Points

  1. Dynamic Rule Sets: Create a RuleSet class to generate configs dynamically (e.g., based on Laravel’s config('coding_standards.php_version')):

    class LaravelRuleSet extends Config\RuleSet\Php83 {
        public static function create(): self {
            $rules = Config\Rules::fromArray([
                'laravel' => [
                    'use_arrow_functions' => config('coding_standards.use_arrows'),
                ],
            ]);
            return new self()->withRules($rules);
        }
    }
    
  2. Custom Finder Logic: Exclude Laravel-specific directories (e.g., storage/, vendor/) or target only app/:

    $finder = Finder::create()
        ->in(__DIR__)
        ->exclude('storage')
        ->exclude('vendor')
        ->name('*.php')
        ->notName('*.blade.php'); // Skip Blade files
    
  3. CI-Specific Configs: Use environment variables to toggle strictness in CI:

    $isCi = getenv('CI') === 'true';
    $ruleSet = Config\RuleSet\Php83::create()
        ->withRules(Config\Rules::fromArray([
            'no_unused_imports' => $isCi, // Only enforce in CI
        ]));
    

Laravel-Specific Quirks

  • Blade Files: PHP-CS-Fixer doesn’t parse Blade syntax by default. Use a custom fixer or exclude Blade files:
    $finder->notName('*.blade.php');
    
  • Artisan Commands: If fixing app/Console/Kernel.php, ensure use statements align with Laravel’s PSR-4 autoloading.
  • Testing: Add CS Fixer to Laravel’s phpunit.xml for pre-test checks:
    <php>
        <ini name="error_reporting" value="-1"/>
        <ini name="memory_limit" value="-1"/>
    </php>
    <listeners>
        <listener class="PHPUnit\Runner\BeforeFirstTestListener">
            <arguments>
                <object class="Symfony\Component\Process\PhpExecutableFinder">
                    <property name="executable" value="vendor/bin/php-cs-fixer"/>
                </object>
                <string>fix --config=.php-cs-fixer.php --dry-run</string>
            </arguments>
        </listener>
    </listeners>
    
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