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.
## 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 .
./vendor/bin/php-styler preview src/MyClass.php
Apply formatting to all configured files:
./vendor/bin/php-styler apply
php-styler.php (config)tests/Examples/ (styling patterns)src/Format/ (predefined formats like DeclarationFormat)src/Rule/ (new NormalizeMemberOrder and AMemberNormalizer)CI/CD Integration:
# .github/workflows/php.yml
jobs:
style-check:
run: ./vendor/bin/php-styler check
Pre-commit Hook (via composer scripts):
{
"scripts": {
"cs-check": "php-styler check",
"cs-fix": "php-styler apply"
}
}
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
])]
);
postcss to run php-styler during build:
mix.scripts(['vendor/bin/php-styler', 'apply'], 'public', {})
.then(() => mix.copy('src', 'public'));
php-styler apply on save via File Watchers../vendor/bin/php-styler apply --workers=auto
| 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, ...]) |
Cache Removal:
cache parameter and --force flag have been removed in 0.20.0..php-styler.cache if you need a fresh start.Anonymous Class Tokens:
TConstEndSemicolon, TPropertyEndSemicolon).preview --diff.Magic Method Handling:
__construct) are now explicitly recognized via TMagicMethod tokens.__ methods are not affected.Member Ordering Quirks:
NormalizeMemberOrder skips reassembly if the order is unchanged.preview to inspect reordered members:
./vendor/bin/php-styler preview --diff
Git Blame:
.git-blame-ignore-revs as before.preview to inspect changes:
./vendor/bin/php-styler preview src/ --diff
$parser = new \PhpStyler\Parser(new \PhpStyler\Format\PlainFormat());
$tokens = $parser->parse(file_get_contents('src/File.php'));
print_r($tokens);
$format = new DeclarationFormat(rules: []);
Custom Member Order:
use PhpStyler\Rule\LineRule\NormalizeMemberOrder;
$customOrder = new NormalizeMemberOrder(order: [
NormalizeMemberOrder::ENUM_CASE,
NormalizeMemberOrder::CONSTANT,
NormalizeMemberOrder::MAGIC_METHOD,
NormalizeMemberOrder::METHOD
]);
Member Spacing Rules:
use PhpStyler\Rule\LineRule\NormalizeMemberSpacing;
$spacing = new NormalizeMemberSpacing(
betweenMagicMethods: true
);
Token Overrides:
AToken or implement AMemberClosing for custom member handling.Line Rule Hooks:
LineRule for post-processing:
use PhpStyler\Rule\LineRule;
class TrimTrailingWhitespace implements LineRule {
public function __invoke(array $lines): array {
return array_map('trim', $lines);
}
}
use PhpStyler\Files;
$files = new Files(__DIR__ . '/src', exclude: ['**/vendor/**', '**/tests/**']);
./vendor/bin/php-styler apply --workers=$(nproc)
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()
)
));
}
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',
],
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]);
}
}
cache parameter in Config.--force/-f option on apply command.NormalizeMemberOrder line rule (default in DeclarationFormat).AMemberClosing interface and AMemberNormalizer base class.TMagicMethod, etc.).NestingStack extracted from Parser.AToken::new() factory method introduced.
NO_UPDATE_NEEDED would not apply here due to significant breaking changes and new features.
How can I help you explore Laravel packages today?