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

mmoreram/php-formatter

PHP code formatter with CLI and configurable rules to standardize style across a project. Formats files or entire directories, helps enforce clean, consistent code, and integrates easily into development workflows and CI.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require mmoreram/php-formatter
    

    Require the autoloader in your project:

    require __DIR__ . '/vendor/autoload.php';
    
  2. First Use Case Format a single PHP file:

    use Mmore\PhpFormatter\PhpFormatter;
    
    $formatter = new PhpFormatter();
    $formattedCode = $formatter->formatFile('path/to/your/file.php');
    file_put_contents('path/to/your/file.php', $formattedCode);
    
  3. Where to Look First

    • Documentation: Check the GitHub repository (if available) for usage examples.
    • Source Code: Explore src/PhpFormatter.php for core functionality and src/PhpFormatterException.php for error handling.
    • Tests: Review tests/ for real-world usage patterns.

Implementation Patterns

Common Workflows

  1. Formatting a Single File

    $formatter = new PhpFormatter();
    $formattedCode = $formatter->formatFile('app/Controller.php');
    
  2. Formatting a Directory Recursively

    $formatter = new PhpFormatter();
    $formatter->formatDirectory('src/', ['.php']);
    
  3. Customizing Formatting Rules Override default rules (e.g., indentation, line breaks):

    $formatter = new PhpFormatter();
    $formatter->setIndentation(4); // Use 4 spaces instead of tabs
    $formatter->setLineBreak("\n"); // Force LF line endings
    
  4. Integration with Laravel Artisan Create a custom Artisan command:

    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Mmore\PhpFormatter\PhpFormatter;
    
    class FormatCode extends Command
    {
        protected $signature = 'code:format {--directory= : Target directory}';
        protected $description = 'Format PHP code using php-formatter';
    
        public function handle()
        {
            $formatter = new PhpFormatter();
            $directory = $this->option('directory') ?: app_path();
            $formatter->formatDirectory($directory, ['.php']);
            $this->info('Code formatted successfully!');
        }
    }
    

    Register the command in app/Console/Kernel.php:

    protected $commands = [
        \App\Console\Commands\FormatCode::class,
    ];
    
  5. Pre-Commit Hook Use the package in a Git pre-commit hook to enforce formatting:

    # .git/hooks/pre-commit
    #!/bin/bash
    php artisan code:format --directory=src/
    
  6. CI/CD Pipeline Add a step to format code before running tests:

    # .github/workflows/ci.yml
    jobs:
      test:
        steps:
          - run: composer require mmoreram/php-formatter
          - run: php artisan code:format --directory=src/
          - run: php artisan test
    

Gotchas and Tips

Pitfalls

  1. Archived Package

    • The package is archived (last release in 2017) and may not support modern PHP features (e.g., PHP 8+ syntax).
    • Mitigation: Test thoroughly or fork the package for updates.
  2. No Laravel-Specific Features

    • The package is agnostic to Laravel. You’ll need to handle paths (e.g., app_path(), base_path()) manually.
  3. Performance on Large Codebases

    • Recursive directory formatting can be slow for large projects.
    • Tip: Exclude vendor/, node_modules/, and generated files (e.g., bootstrap/cache/).
  4. Edge Cases in Formatting

    • The formatter may struggle with:
      • Heredoc/Nowdoc syntax: <<<EOF blocks might break.
      • Inline HTML/PHP mixes: <?php ?> snippets in Blade templates.
      • Custom PHPDoc tags: Non-standard annotations may not parse correctly.
    • Workaround: Manually exclude problematic files or pre-process them.
  5. Configuration Overrides

    • The package lacks a config file or environment-based settings.
    • Tip: Store formatting rules in a config file (e.g., config/php-formatter.php) and hydrate the formatter dynamically:
      $formatter = new PhpFormatter();
      $formatter->setIndentation(config('php-formatter.indentation'));
      
  6. Error Handling

    • The package throws PhpFormatterException for issues like unreadable files.
    • Tip: Wrap usage in a try-catch:
      try {
          $formatter->formatFile('unreadable-file.php');
      } catch (\Mmore\PhpFormatter\PhpFormatterException $e) {
          $this->error($e->getMessage());
      }
      

Debugging Tips

  1. Dry Run Mode Log changes before applying them:

    $formatter->setDryRun(true); // Logs changes without writing files
    $formatter->formatDirectory('src/');
    
  2. Verbose Output Enable debug mode to see skipped files or errors:

    $formatter->setVerbose(true);
    
  3. Check File Permissions Ensure the script has write access to target files/directories:

    chmod -R 775 src/
    

Extension Points

  1. Custom Rules Extend PhpFormatter by overriding methods like formatFile() or formatLine():

    class CustomFormatter extends \Mmore\PhpFormatter\PhpFormatter
    {
        protected function formatLine($line)
        {
            // Add custom logic (e.g., trim whitespace)
            return trim($line);
        }
    }
    
  2. Pre/Post-Processing Hook into the formatting pipeline:

    $formatter->setPreProcessor(function ($code) {
        return str_replace('// OLD_COMMENT', '', $code);
    });
    $formatter->setPostProcessor(function ($code) {
        return '<?php ' . $code; // Ensure opening tag
    });
    
  3. Integration with PHP-CS-Fixer Combine with friendsofphp/php-cs-fixer for advanced formatting:

    $formatter = new PhpFormatter();
    $csFixer = new \PhpCsFixer\Config();
    $code = $formatter->formatFile('file.php');
    $code = $csFixer->fix($code);
    
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