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 Custom Fixers Laravel Package

kubawerlos/php-cs-fixer-custom-fixers

Custom fixers for FriendsOfPHP PHP-CS-Fixer. Install via Composer, register the Fixers set, then enable individual rules to enforce additional style conventions (e.g., prefer class constants, remove leading global namespace slashes, tidy PHPDoc params).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package in your Laravel project:
    composer require --dev kubawerlos/php-cs-fixer-custom-fixers
    
  2. Extend your existing .php-cs-fixer.dist.php (or create one if missing):
    <?php
    return (\PhpCsFixer\Config)->create()
        ->setRules([
            // Your existing rules...
            '@PHP-CS-Fixer:risky' => true,
            '@PHP-CS-Fixer:aliases' => true,
            // New custom fixer (v3.37.2+)
            'PhpdocNoIncorrectVarAnnotationFixer' => true,
        ])
        ->setFinder(
            (\PhpCsFixer\Finder)::create()
                ->in(__DIR__.'/../src')
                ->in(__DIR__.'/../tests')
        );
    
  3. First use case: Run the fixer on your Laravel codebase:
    vendor/bin/php-cs-fixer fix
    

Key Entry Points

  • Custom Fixer List: Check the package’s Fixer class for available fixers (e.g., NoUnusedPhpDocTags, NoSuperfluousPhpDocTags, PhpdocNoIncorrectVarAnnotationFixer).
  • Laravel Integration: Pair with php-cs-fixer in composer.json scripts:
    "scripts": {
        "cs-fix": "php-cs-fixer fix",
        "cs-check": "php-cs-fixer fix --dry-run --diff"
    }
    

Implementation Patterns

Workflow Integration

  1. Pre-commit Hooks Use php-cs-fixer with tools like roave/security-advisories or Laravel’s pre-commit scripts:

    composer require --dev roave/security-advisories
    composer require --dev laravel/pint  # Optional: For parallel linting
    

    Example composer.json script:

    "scripts": {
        "test": [
            "@cs-check",
            "@phpunit"
        ],
        "cs-check": "php-cs-fixer fix --dry-run --diff"
    }
    
  2. CI/CD Pipeline Add to Laravel’s GitHub Actions (.github/workflows/php-cs-fixer.yml):

    name: PHP CS Fixer
    on: [push, pull_request]
    jobs:
      fix:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-php@v3
            with:
              php-version: '8.2'
          - run: composer install
          - run: vendor/bin/php-cs-fixer fix --dry-run --diff
    
  3. Custom Fixer Selection Enable fixers in .php-cs-fixer.dist.php:

    ->setRules([
        // Laravel-specific custom fixers
        'NoUnusedPhpDocTags' => true,
        'NoSuperfluousPhpDocTags' => true,
        'PhpdocNoIncorrectVarAnnotationFixer' => true, // New in v3.37.2
        'OrderedImports' => [
            'sort_algorithm' => 'alpha',
            'imports_order' => ['class', 'function', 'const'],
        ],
    ])
    

Laravel-Specific Patterns

  • Service Provider Fixers For fixers targeting Laravel’s ServiceProvider classes, use:
    'NoUnusedUses' => [
        'remove_unused_aliases' => true,
        'remove_unused_imports' => true,
    ],
    
  • Route/Controller Fixers Combine with pint for route files:
    vendor/bin/pint routes/web.php
    vendor/bin/php-cs-fixer fix routes/web.php
    

Gotchas and Tips

Common Pitfalls

  1. Rule Conflicts

    • Issue: Custom fixers may conflict with Laravel’s default PSR-12 rules (e.g., PhpdocNoIncorrectVarAnnotationFixer vs. @PSR12).
    • Fix: Explicitly disable conflicting rules:
      ->setRules([
          '@PSR12' => true,
          'PhpdocNoIncorrectVarAnnotationFixer' => true,
          'phpdoc_align' => false, // Disable if conflicting
      ])
      
  2. Performance Overhead

    • Issue: Custom fixers add processing time. Large Laravel apps (e.g., 50K+ lines) may slow down CI.
    • Fix:
      • Cache results with --cache-file=.php-cs-fixer.cache.
      • Exclude vendor/ and node_modules/:
        ->setFinder(
            (\PhpCsFixer\Finder)::create()
                ->exclude('vendor')
                ->exclude('node_modules')
        )
        
  3. False Positives with PhpdocNoIncorrectVarAnnotationFixer

    • Issue: May incorrectly flag PHPDoc annotations for asymmetric-visibility properties in Laravel models (e.g., protected $fillable with @var array).
    • Fix: Whitelist specific properties or adjust annotations:
      'PhpdocNoIncorrectVarAnnotationFixer' => [
          'skip_matching' => [
              '~protected \\$fillable~',
              '~private \\$guarded~',
          ],
      ]
      

Debugging Tips

  • Dry Run with Diff:
    vendor/bin/php-cs-fixer fix --dry-run --diff
    
  • Verbose Output:
    vendor/bin/php-cs-fixer fix -v
    
  • Test Individual Fixers:
    vendor/bin/php-cs-fixer fix --rules=PhpdocNoIncorrectVarAnnotationFixer path/to/Model.php
    

Extension Points

  1. Custom Fixers for Laravel Extend the package by creating a new fixer (e.g., for Laravel’s HasFactory trait docs):

    // app/CustomFixers/HasFactoryDocFixer.php
    namespace App\CustomFixers;
    
    use PhpCsFixer\Fixer\FixerInterface;
    use PhpCsFixer\Tokenizer\Tokens;
    
    class HasFactoryDocFixer implements FixerInterface {
        public function isRisky(): bool { return false; }
        public function getName(): string { return 'has_factory_doc'; }
        public function getDescription(): string { return 'Ensures HasFactory trait is documented.'; }
        public function fix(\SplFileInfo $file, Tokens $tokens) { /* ... */ }
        public function isTokenized(): bool { return true; }
    }
    

    Register it in .php-cs-fixer.dist.php:

    ->registerCustomFixers([
        __DIR__.'/../app/CustomFixers/HasFactoryDocFixer.php',
    ])
    
  2. Integration with Laravel Valet/PSA Add to ~/.php-cs-fixer.dist.php for global projects:

    ->setRules([
        'PhpdocNoIncorrectVarAnnotationFixer' => true,
        // ...
    ])
    
  3. Git Attributes Enforce fixers via .gitattributes:

    *.php diff=php-cs-fixer
    

    Configure in .git/config:

    [diff "php-cs-fixer"]
        textconv = vendor/bin/php-cs-fixer filter --rules-file=.php-cs-fixer.dist.php
    

Pro Tips

  • Laravel-Specific Presets: Combine with shivammathur/php-cs-fixer-config-laravel for pre-configured Laravel rules.
  • IDE Integration: Use php-cs-fixer with PHPStorm’s "Reformat Code" action via:
    // .php-cs-fixer.dist.php
    ->setUsingCache(true)
    
  • Team Onboarding: Document custom fixers in CONTRIBUTING.md:
    ## Code Style
    Run `composer cs-fix` to auto-fix style issues. Custom fixers:
    - `PhpdocNoIncorrectVarAnnotationFixer`: Fixes incorrect `@var` annotations for asymmetric-visibility properties (e.g., `protected $fillable`).
    - `NoUnusedPhpDocTags`: Removes redundant PHPDoc tags (e.g., `@var` for obvious types).
    - `OrderedImports`: Sorts imports alphabetically by type.
    
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.
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
anil/file-picker
broqit/fields-ai