PHP CS Fixer reformats PHP files according to selected rules and can apply PSR-12 and additional project preferences.
What It Does
Install a locally versioned formatter. Scope formatting to the actual source tree.
Requirements and Compatibility
Use a supported PHP runtime and install any third-party tool or extension explicitly shown in the examples. Commands should be run from the project root unless stated otherwise.
Syntax, Inputs and Results
The examples separate configuration, the smallest working operation and a realistic follow-up task. Adapt file paths and dependency versions to your own project.
Example 1: Basic Use
Install a locally versioned formatter.
composer require --dev friendsofphp/php-cs-fixer
vendor/bin/php-cs-fixer --version
Example 2: Another Case
Scope formatting to the actual source tree.
<?php
// File: .php-cs-fixer.dist.php
$finder = PhpCsFixer\Finder::create()->in(__DIR__ . '/src');
return (new PhpCsFixer\Config())->setRules(['@PSR12' => true])->setFinder($finder);
Practical Example
Review the changes before rewriting source files.
vendor/bin/php-cs-fixer fix --dry-run --diff
vendor/bin/php-cs-fixer fix
For production, apply the compatibility and edge-case limits described below.
Important Behavior and Edge Cases
Formatting rules are not semantic safety checks; use a dry-run diff and run tests after bulk changes.
Comparison with Related Functions and Tools
| Subject | Key difference |
|---|---|
| Direct function calls vs injectable services | Constructor injection exposes collaborators so they can be replaced during testing. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Relying on a demonstration as production validation | Add explicit error handling and test all inputs that can change behavior. |
| Skipping the prerequisite of this specific workflow | Install or configure the named tool and confirm the example can actually run. |
| Ignoring edge conditions | Formatting rules are not semantic safety checks; use a dry-run diff and run tests after bulk changes. |
Key Takeaways
- PHP CS Fixer reformats PHP files according to selected rules and can apply PSR-12 and additional project preferences.
- Formatting rules are not semantic safety checks; use a dry-run diff and run tests after bulk changes.
- Keep application configuration, source code and validation tests under version control.
Use these examples as a starting point, then validate the result with the actual PHP build, dependencies and inputs used by your application.