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

pmjones/php-styler

PHP-Styler is a PHP 8.1+ code formatter that completely rewrites formatting for consistent spacing, indentation, and line wrapping. It preserves program logic and comments, aims for diff-friendly output, and supports customizable styles, rules, and parses via a token-based pipeline.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require --dev pmjones/php-styler

Copy the default config:

cp vendor/pmjones/php-styler/resources/php-styler.php .
  1. First Use Case: Preview formatting on a file:
    ./vendor/bin/php-styler preview src/MyClass.php
    
    Apply formatting to all configured files:
    ./vendor/bin/php-styler apply
    

Key Files to Inspect

  • php-styler.php (config)
  • tests/Examples/ (styling patterns)
  • src/Format/ (predefined formats like DeclarationFormat)
  • src/Rule/ (new NormalizeMemberOrder and AMemberNormalizer)

Implementation Patterns

Workflows

  1. CI/CD Integration:

    # .github/workflows/php.yml
    jobs:
      style-check:
        run: ./vendor/bin/php-styler check
    
  2. Pre-commit Hook (via composer scripts):

    {
      "scripts": {
        "cs-check": "php-styler check",
        "cs-fix": "php-styler apply"
      }
    }
    
  3. Custom Member Ordering:

    use PhpStyler\Format\DeclarationFormat;
    use PhpStyler\Rule\LineRule\NormalizeMemberOrder;
    
    $format = new DeclarationFormat(
        rules: [new NormalizeMemberOrder(order: [
            NormalizeMemberOrder::USE_TRAIT,
            NormalizeMemberOrder::ENUM_CASE,
            NormalizeMemberOrder::CONSTANT,
            NormalizeMemberOrder::PROPERTY,
            NormalizeMemberOrder::MAGIC_METHOD,
            NormalizeMemberOrder::METHOD
        ])]
    );
    

Integration Tips

  • Laravel Mix/Webpack: Use postcss to run php-styler during build:
    mix.scripts(['vendor/bin/php-styler', 'apply'], 'public', {})
      .then(() => mix.copy('src', 'public'));
    
  • IDE Integration: Configure PHPStorm to run php-styler apply on save via File Watchers.
  • Parallel Processing: Speed up large codebases:
    ./vendor/bin/php-styler apply --workers=auto
    

Common Configurations

Use Case Config Snippet
PSR-12 Compliance new DeclarationFormat(lineLen: 120)
Symfony Standard new Vendor\SymfonyFormat()
Doctrine Standard new Vendor\DoctrineFormat(concatenationSpacing: false)
Custom Line Length new PlainFormat(lineLen: 100, indentLen: 2)
Member Ordering new NormalizeMemberOrder(order: [NormalizeMemberOrder::USE_TRAIT, ...])

Gotchas and Tips

Pitfalls

  1. Cache Removal:

    • The cache parameter and --force flag have been removed in 0.20.0.
    • Impact: All files are now reformatted on every run. Delete .php-styler.cache if you need a fresh start.
  2. Anonymous Class Tokens:

    • Anonymous class constants/properties now receive specialized ending tokens (TConstEndSemicolon, TPropertyEndSemicolon).
    • Tip: Verify anonymous class formatting with preview --diff.
  3. Magic Method Handling:

    • PHP magic methods (e.g., __construct) are now explicitly recognized via TMagicMethod tokens.
    • Caveat: User-defined __ methods are not affected.
  4. Member Ordering Quirks:

    • NormalizeMemberOrder skips reassembly if the order is unchanged.
    • Debug: Use preview to inspect reordered members:
      ./vendor/bin/php-styler preview --diff
      
  5. Git Blame:

    • Frequent reformatting (due to cache removal) may pollute blame history.
    • Solution: Use .git-blame-ignore-revs as before.

Debugging

  • Dry Run: Use preview to inspect changes:
    ./vendor/bin/php-styler preview src/ --diff
    
  • Token Inspection: Dump tokens for a file:
    $parser = new \PhpStyler\Parser(new \PhpStyler\Format\PlainFormat());
    $tokens = $parser->parse(file_get_contents('src/File.php'));
    print_r($tokens);
    
  • Rule Debugging: Disable rules in config:
    $format = new DeclarationFormat(rules: []);
    

Extension Points

  1. Custom Member Order:

    use PhpStyler\Rule\LineRule\NormalizeMemberOrder;
    
    $customOrder = new NormalizeMemberOrder(order: [
        NormalizeMemberOrder::ENUM_CASE,
        NormalizeMemberOrder::CONSTANT,
        NormalizeMemberOrder::MAGIC_METHOD,
        NormalizeMemberOrder::METHOD
    ]);
    
  2. Member Spacing Rules:

    use PhpStyler\Rule\LineRule\NormalizeMemberSpacing;
    
    $spacing = new NormalizeMemberSpacing(
        betweenMagicMethods: true
    );
    
  3. Token Overrides:

    • Extend AToken or implement AMemberClosing for custom member handling.
  4. Line Rule Hooks:

    • Implement LineRule for post-processing:
      use PhpStyler\Rule\LineRule;
      
      class TrimTrailingWhitespace implements LineRule {
          public function __invoke(array $lines): array {
              return array_map('trim', $lines);
          }
      }
      

Performance Tips

  • Exclude Large Files:
    use PhpStyler\Files;
    $files = new Files(__DIR__ . '/src', exclude: ['**/vendor/**', '**/tests/**']);
    
  • Parallel Workers: Optimal for >100 files:
    ./vendor/bin/php-styler apply --workers=$(nproc)
    

Laravel-Specific Tips

  1. Artisan Command:

    // app/Console/Commands/FormatCode.php
    use PhpStyler\Styler;
    
    class FormatCode extends Command {
        protected $signature = 'code:format';
        public function handle(Styler $styler) {
            $result = $styler->apply();
            $this->info("Formatted {$result['files']} files.");
        }
    }
    

    Register in AppServiceProvider:

    public function boot() {
        $this->app->singleton(Styler::class, fn() => new Styler(
            new \PhpStyler\Config(
                files: new \PhpStyler\Files(app_path('Http/Controllers')),
                format: new \PhpStyler\Format\DeclarationFormat()
            )
        ));
    }
    
  2. Service Provider:

    // config/php-styler.php
    'enabled' => env('STYLER_ENABLED', false),
    'paths' => [
        app_path('Http/Controllers'),
        app_path('Console/Commands'),
    ],
    'member_order' => [
        'NormalizeMemberOrder::USE_TRAIT',
        'NormalizeMemberOrder::ENUM_CASE',
    ],
    
  3. Event Listener (auto-format on file save):

    use Illuminate\Filesystem\Events\FileUpdated;
    
    public function handle(FileUpdated $event) {
        if (str_ends_with($event->path, '.php')) {
            $styler = app(Styler::class);
            $styler->apply([$event->path]);
        }
    }
    

Breaking Changes (0.20.0)

  • Removed:
    • cache parameter in Config.
    • --force/-f option on apply command.
  • New Features:
    • NormalizeMemberOrder line rule (default in DeclarationFormat).
    • AMemberClosing interface and AMemberNormalizer base class.
    • Magic method token support (TMagicMethod, etc.).
  • Parser Refactoring:
    • NestingStack extracted from Parser.
    • AToken::new() factory method introduced.
    • Token dispatch logic optimized.

NO_UPDATE_NEEDED would not apply here due to significant breaking changes and new features.
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