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

Twig Cs Fixer Laravel Package

vincentlanglet/twig-cs-fixer

A coding standards fixer for Twig templates. Analyze and automatically format Twig files with consistent style rules, configurable presets, and CI-friendly checks to keep templates clean and readable across your project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev vincentlanglet/twig-cs-fixer
    

    Ensure bin-dependencies is enabled in your composer.json:

    "config": {
        "bin-dir": "bin",
        "bin-dependencies": true
    }
    
  2. First Run (Linting):

    vendor/bin/twig-cs-fixer lint resources/views
    

    This checks Twig files in resources/views for coding standard violations.

  3. First Fix:

    vendor/bin/twig-cs-fixer fix resources/views
    

    Automatically applies fixes to non-compliant files.


Where to Look First

  • Default Rules: The package enforces Twig’s official coding standards by default (e.g., snake_case variables, delimiter spacing).
  • Configuration File: Create .twig-cs-fixer.php in your project root to customize rules (see Implementation Patterns).
  • CLI Help:
    vendor/bin/twig-cs-fixer --help
    
    Lists all available commands, reporters, and options.

First Use Case: Pre-Commit Hook

Integrate twig-cs-fixer into your workflow to enforce consistency before commits:

# Add to package.json (if using Laravel Mix)
"scripts": {
    "lint:twig": "twig-cs-fixer lint resources/views"
}

Or use a tool like Husky to run it automatically.


Implementation Patterns

Workflows

1. Project-Wide Enforcement

  • Configuration: Extend the default ruleset in .twig-cs-fixer.php:
    <?php
    $ruleset = new \TwigCsFixer\Ruleset\Ruleset();
    $ruleset->addStandard(new \TwigCsFixer\Standard\TwigCsFixer());
    $ruleset->overrideRule(new \TwigCsFixer\Rules\Whitespace\EmptyLinesRule(2)); // 2 lines between blocks
    
    $config = new \TwigCsFixer\Config\Config();
    $config->setRuleset($ruleset);
    return $config;
    
  • Run:
    vendor/bin/twig-cs-fixer fix resources/views --config=.twig-cs-fixer.php
    

2. Team-Specific Rules

  • Custom Rules: Disable SingleQuoteRule for legacy projects:
    $ruleset->removeRule(\TwigCsFixer\Rules\String\SingleQuoteRule::class);
    
  • File-Specific Ignores: Use .twig-cs-fixer.dist.php for team defaults and .twig-cs-fixer.php for overrides.

3. CI/CD Integration

  • GitHub Actions Example:
    - name: Lint Twig
      run: vendor/bin/twig-cs-fixer lint resources/views --report=github
    
    Outputs annotations for failed checks.

4. Partial Fixes

  • Fix only specific files/directories:
    vendor/bin/twig-cs-fixer fix resources/views/partials --dry-run
    
    Use --dry-run to preview changes.

Integration Tips

Laravel-Specific

  • Service Provider: Register the fixer as a Laravel command:
    // app/Console/Commands/FixTwigCommand.php
    namespace App\Console\Commands;
    use TwigCsFixer\Application;
    
    class FixTwigCommand extends Command {
        protected $signature = 'twig:fix';
        public function handle() {
            $app = new Application();
            $app->run(['fix', 'resources/views']);
        }
    }
    
    Add to app/Console/Kernel.php:
    protected $commands = [
        \App\Console\Commands\FixTwigCommand::class,
    ];
    
    Run with:
    php artisan twig:fix
    

IDE Integration

  • PHPStorm: Use the External Tools settings to run twig-cs-fixer on save:
    • Program: vendor/bin/twig-cs-fixer
    • Arguments: fix $FilePath$
    • Working Directory: $ProjectFileDir$

Custom Rules

  • Extend Rules: Create a custom rule by extending AbstractRule:
    namespace App\Rules;
    use TwigCsFixer\Rule\AbstractRule;
    
    class CustomBlockRule extends AbstractRule {
        public function getName() {
            return 'custom_block_rule';
        }
        public function process(\TwigCsFixer\File $file) {
            // Custom logic
        }
    }
    
    Register in .twig-cs-fixer.php:
    $ruleset->addRule(new \App\Rules\CustomBlockRule());
    

Gotchas and Tips

Pitfalls

  1. Cache Issues:

    • Problem: Cache may retain old rule configurations if the PHP version or package version changes.
    • Fix: Clear cache with --no-cache or set null in config:
      $config->setCacheFile(null);
      
  2. Non-Fixable Rules:

    • Problem: Rules like FileNameRule are non-fixable by default and may cause lint failures without fixes.
    • Fix: Explicitly allow non-fixable rules:
      $config->allowNonFixableRules();
      
  3. Twig Version Mismatch:

    • Problem: Node-based rules may fail if your Twig version doesn’t support the required AST nodes.
    • Fix: Check Twig CS Fixer’s compatibility matrix and update Twig:
      composer require twig/twig:^3.12
      
  4. Overly Strict Rules:

    • Problem: Rules like SingleQuoteRule may break legacy templates with escaped single quotes.
    • Fix: Configure exceptions:
      $ruleset->overrideRule(new \TwigCsFixer\Rules\String\SingleQuoteRule([
          'skipStringContainingSingleQuote' => false,
      ]));
      
  5. Performance:

    • Problem: Large projects may slow down due to cache or complex rules.
    • Fix: Limit scope or disable cache temporarily:
      vendor/bin/twig-cs-fixer lint resources/views --no-cache
      

Debugging

  1. Dry Runs: Use --dry-run to preview changes without modifying files:

    vendor/bin/twig-cs-fixer fix --dry-run
    
  2. Verbose Output: Enable debug mode for detailed logs:

    vendor/bin/twig-cs-fixer lint --verbose
    
  3. Rule-Specific Debugging: Isolate rule failures by testing individual rules:

    vendor/bin/twig-cs-fixer lint --rules=DelimiterSpacingRule
    
  4. Custom Reporter: Use junit or github reporters for CI debugging:

    vendor/bin/twig-cs-fixer lint --report=junit > report.xml
    

Tips

  1. Partial Fixes: Use --path-mode=union to fix only files that violate rules:

    vendor/bin/twig-cs-fixer fix --path-mode=union
    
  2. Exclude Files: Configure the Finder to skip specific files/directories:

    $finder = new \TwigCsFixer\File\Finder();
    $finder->in('resources/views')->exclude(['legacy', 'vendor']);
    $config->setFinder($finder);
    
  3. Symfony Integration: Combine with symfony/coding-standard for PHP/Twig consistency:

    composer require --dev symfony/coding-standard
    vendor/bin/ecs check src resources/views
    
  4. Custom Token Parsers: Extend Twig’s token parsing for custom syntax (e.g., Laravel Blade-like directives):

    $config->addTokenParser(new \App\Twig\CustomTokenParser());
    
  5. Git Pre-Commit: Use twig-cs-fixer in a pre-commit hook via PHP-CS-Fixer’s pre-commit example:

    # .git/hooks/pre-commit
    #!/bin/sh
    vendor/bin/twig-cs-fixer fix resources/views --allow-risky=yes
    
  6. IDE Formatting: Configure your IDE to trigger twig-cs-fixer on save (e.g., PHPStorm’s onSave actions).

  7. **Leg

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony