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 fully reformats your code for consistent spacing, indentation, and line lengths. It preserves logic and comments, is diff-friendly by default, and is customizable via styles, rules, and parses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require --dev pmjones/php-styler
    
  2. Initialize Config:

    ./vendor/bin/php-styler init
    

    This generates a php-styler.php file in your project root with default settings.

  3. First Use Case: Preview formatting changes on a single file:

    ./vendor/bin/php-styler preview src/MyClass.php
    

Where to Look First

  • Config File: php-styler.php (auto-generated by init).
  • Examples: tests/Examples/ directory for styling patterns.
  • CLI Help:
    ./vendor/bin/php-styler --help
    

Implementation Patterns

Core Workflow

  1. Configure: Extend the default php-styler.php with your preferred AFormat (e.g., DeclarationFormat for classes, Percs30Format for PER standards).

    return new Config(
        files: new Files(__DIR__ . '/src'),
        format: new DeclarationFormat(lineLen: 120, indentLen: 2),
    );
    
  2. Integrate into CI/CD: Add a check step to fail builds on formatting issues:

    # .github/workflows/php.yml
    - name: Check PHP Styler
      run: ./vendor/bin/php-styler check
    
  3. Pre-commit Hook: Use apply to auto-format staged files:

    # .git/hooks/pre-commit
    #!/bin/sh
    ./vendor/bin/php-styler apply -- $(git diff --cached --name-only --diff-filter=ACM | grep '\.php$')
    

Common Patterns

  • Team Alignment: Use apply in a pre-merge hook to enforce consistency:

    ./vendor/bin/php-styler apply src/
    git add src/
    
  • Diff-Friendly Changes: Use diff to review changes before applying:

    ./vendor/bin/php-styler diff > styling-changes.diff
    
  • Parallel Processing: Speed up large codebases with --workers:

    ./vendor/bin/php-styler apply --workers=auto
    
  • Custom Rules: Override defaults in php-styler.php:

    $format = new DeclarationFormat();
    $format->styles['TFunction'] = ['blankLineBefore' => true];
    

Integration Tips

  • IDE Support: Configure your IDE (PHPStorm, VSCode) to trigger php-styler apply on save via settings.json or IDE plugins. Example VSCode task:

    {
      "version": "2.0.0",
      "tasks": [
        {
          "label": "Format PHP",
          "type": "shell",
          "command": "./vendor/bin/php-styler apply",
          "problemMatcher": []
        }
      ]
    }
    
  • Monorepo Handling: Use Files with multiple directories or Symfony Finder for granular control:

    use Symfony\Component\Finder\Finder;
    $finder = Finder::create()->files()->name('*.php')->in(['src', 'modules']);
    return new Config(files: $finder, format: new PlainFormat());
    
  • Partial Formatting: Exclude files/directories via Files:

    return new Config(
        files: new Files(__DIR__ . '/src', ['!tests/', '!vendor/']),
        format: new DeclarationFormat(),
    );
    

Gotchas and Tips

Pitfalls

  1. Comment Preservation:

    • Block comments (/* ... */) are preserved in place but may shift vertically if surrounding code changes.
    • End-of-line comments (//) stay on their original lines but may lose alignment.
    • Workaround: Use @php-styler-expansive for critical comments to force line breaks.
  2. String Literals:

    • Long strings (heredocs, nowdocs) are not split. Use @php-styler-expansive or manual line breaks:
      $sql = <<<'SQL'
          SELECT long_column_name AS "alias"
          FROM very_long_table_name
      SQL;
      
  3. Horizontal Alignment:

    • PHP-Styler intentionally breaks aligned code (e.g., concatenation):
      // Before (aligned)
      $foo = 'long'    . $bar;
      $foo = 'short'   . $bar;
      
      // After (unaligned)
      $foo = 'long' . $bar;
      $foo = 'short' . $bar;
      
    • Tip: Use PlainFormat with concatenationSpacing: false to retain alignment.
  4. Line Length Limits:

    • If a line exceeds lineLen even after splitting (e.g., long URLs in strings), PHP-Styler will not truncate it.
    • Solution: Increase lineLen or refactor the code.
  5. Git Blame:

    • Initial reformatting will pollute git blame. Mitigate by:
      1. Running php-styler apply once.
      2. Adding the commit hash to .git-blame-ignore-revs.
  6. PHP 8.1+ Only:

    • Requires PHP 8.1+. Older versions will fail with composer require.

Debugging Tips

  • Parse Failures: Use the debug command to inspect problematic files:

    ./vendor/bin/php-styler debug src/BrokenFile.php
    
  • Cache Issues: Clear the cache if styles don’t update:

    ./vendor/bin/php-styler clear-cache
    
  • Verbose Output: Enable debug mode for detailed logs:

    ./vendor/bin/php-styler apply -vvv
    

Extension Points

  1. Custom Formats: Extend AFormat to create reusable styles:

    class MyFormat extends DeclarationFormat {
        public function __construct() {
            $this->styles['TClass'] = ['blankLineBefore' => true];
            $this->rules[] = new MyCustomRule();
        }
    }
    
  2. Token Rules: Add structural transformations by implementing IRule:

    class AddSemicolons implements IRule {
        public function apply(AToken $token, TokenStream $stream) {
            if ($token instanceof TStatement && !$token->hasSemicolon()) {
                $stream->insertAfter($token, new TSemicolon());
            }
        }
    }
    
  3. Parses (Token Replacements): Override parseAs in your format to normalize syntax:

    $format = new PlainFormat();
    $format->parseAs['TDoubleColon'] = 'TDoubleColon::class'; // Normalize `::` to `::class`
    
  4. Line Splitting: Override split priorities in Splitter for domain-specific needs:

    $format = new DeclarationFormat();
    $format->splitter->splitPoints = [
        'TArrowFunction' => 100, // Higher priority
        'TComma' => 50,
    ];
    

Config Quirks

  • Default Values: PlainFormat uses lineLen: 88, indentLen: 4. Override explicitly to avoid surprises:

    new PlainFormat(lineLen: 120, indentLen: 2)
    
  • Vendor Formats: Pre-built formats (Percs30Format, SymfonyFormat) may conflict with team preferences. Audit their rules before adopting:

    $format = new SymfonyFormat();
    $format->rules = []; // Disable all rules
    $format->styles['TFunction'] = ['blankLineBefore' => true]; // Customize
    
  • Case Sensitivity: keywordCase in PlainFormat defaults to 'lower'. Set to 'upper' for ALL-CAPS keywords (e.g., IF instead of if).

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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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