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 rewrites formatting for consistent spacing, indentation, and line splitting. It preserves code logic and comments, aims for diff-friendly output, and supports customizable styles/rules for structural transformations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev pmjones/php-styler
    

    Add to composer.json under require-dev:

    "pmjones/php-styler": "0.x-dev"
    
  2. Initialize Config:

    ./vendor/bin/php-styler init
    

    This generates php-styler.php 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
    

    Apply formatting to all configured files:

    ./vendor/bin/php-styler apply
    

Key Files to Review

  • php-styler.php: Project-specific configuration (formats, file paths).
  • vendor/pmjones/php-styler/tests/Examples/: Pre-built styling examples.
  • vendor/pmjones/php-styler/src/Format/: Built-in format classes (PlainFormat, DeclarationFormat, etc.).

Implementation Patterns

Workflow Integration

  1. CI/CD Pipeline: Add to .github/workflows/php.yml:

    - name: Check PHP Styler
      run: ./vendor/bin/php-styler check
    

    Fail builds if files need formatting.

  2. Pre-Commit Hook: Use husky or pre-commit to run:

    ./vendor/bin/php-styler check
    

    Block commits with unstyled files.

  3. Onboarding: Run php-styler apply once during setup to standardize the codebase.

Common Patterns

  • Custom Format: Extend PlainFormat for project-specific rules:

    use PhpStyler\Format\PlainFormat;
    
    return new Config(
        files: new Files(__DIR__ . '/src'),
        format: new PlainFormat(
            lineLen: 100,
            rules: [
                new NormalizeImports(),
                new NormalizeTrailingCommas(),
            ],
        ),
    );
    
  • Selective Application: Target specific paths:

    ./vendor/bin/php-styler apply src/ src/tests/
    
  • Parallel Processing: Speed up large codebases:

    ./vendor/bin/php-styler apply --workers=auto
    

Integration Tips

  • IDE Support: Configure your IDE (PHPStorm, VSCode) to ignore php-styler.php and generated files. Use php-styler preview to validate changes before committing.

  • Git Ignore: Add to .gitignore:

    # Ignore PHP-Styler's cache (if used)
    .php-styler-cache/
    
  • Diff Tooling: Use php-styler diff to review changes before applying:

    ./vendor/bin/php-styler diff | less
    

Gotchas and Tips

Pitfalls

  1. Comment Preservation:

    • End-of-line comments (//) stay on their original lines but may be misaligned.
    • Block comments (/* */) are preserved in place but may lose indentation.
    • Fix: Use @php-styler-expansive for complex comments:
      /** @php-styler-expansive */
      /* Multi-line
       * comment with
       * alignment */
      
  2. String Literals:

    • Long strings or heredocs won’t be split automatically.
    • Fix: Manually break lines or use @php-styler-expansive.
  3. Horizontal Alignment:

    • PHP-Styler removes manual alignment (e.g., $foo = 'long' . $bar).
    • Fix: Use DeclarationFormat for consistent indentation.
  4. Inline Docblocks:

    • Bug in v0.10.1 caused logic breaks with inline docblocks.
    • Fix: Update to the latest version and avoid inline docblocks before =:
      // Bad (pre-v0.10.1)
      $foo =
          /** @param string $bar */
          function ($bar) { ... };
      
      // Good
      $foo = /** @param string $bar */ function ($bar) { ... };
      
  5. Git Blame:

    • Initial reformatting will clutter blame history.
    • Fix: Add the commit hash to .git-blame-ignore-revs:
      echo "$(git rev-parse HEAD)" > .git-blame-ignore-revs
      git config blame.ignoreRevsFile .git-blame-ignore-revs
      

Debugging

  • Dry Run: Use preview to inspect changes without modifying files:

    ./vendor/bin/php-styler preview src/File.php --verbose
    
  • Verbose Output: Add --verbose to see detailed token processing:

    ./vendor/bin/php-styler apply --verbose
    
  • Custom Config Path: Override config file location:

    ./vendor/bin/php-styler apply -c custom/php-styler.php
    

Extension Points

  1. Custom Rules: Extend ARule to add project-specific transformations:

    use PhpStyler\Rule\ARule;
    
    class CustomRule extends ARule {
        public function apply(Styler $styler) {
            // Modify token stream here
        }
    }
    

    Add to config:

    new Config(
        format: new PlainFormat(
            rules: [new CustomRule()],
        ),
    )
    
  2. Token Parsing: Override parseAs in formats to customize token handling:

    new PlainFormat(
        parseAs: [
            'T_DOUBLE_ARROW' => 'T_DOUBLE_FAT_ARROW', // Replace `=>` with `=>`
        ],
    )
    
  3. Line Splitting: Force splits with @php-styler-expansive or override the Splitter:

    use PhpStyler\Splitter;
    
    $splitter = new Splitter($styler, $format);
    $splitter->setSplitPriority([Splitter::ATTRIBUTES, Splitter::COMMA]);
    

Configuration Quirks

  • Line Length: Set lineLen to 0 to disable splitting (not recommended). Default is 84; adjust based on team preferences.

  • Indentation: Use indentTab: true for tab-based projects (rare in Laravel). Default is indentLen: 4 (spaces).

  • Vendor Formats: Pre-built formats (Percs30Format, SymfonyFormat) may conflict with Laravel’s PSR-12. Tip: Override specific styles:

    new SymfonyFormat(
        styles: [
            'T_FUNCTION' => ['blankLineBefore' => false],
        ],
    )
    

Performance

  • Parallel Workers: Use --workers=auto for large codebases (e.g., Laravel’s app/ directory). Avoid for small projects (<8 files).

  • Excluded Files: Exclude vendor files in Files:

    new Files(__DIR__ . '/src', exclude: ['vendor/**']),
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor