Top Related Projects
A tool to automatically fix PHP Coding Standards issues
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
A PHP static analysis tool for finding errors and security vulnerabilities in PHP applications
PHP Static Analysis Tool - discover bugs in your code without running it!
Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.
Quick Overview
PHP-CS-Fixer is a popular tool that automatically fixes PHP coding standards issues. It analyzes your PHP code and applies fixes to adhere to coding standards, improving code quality and consistency across projects. The tool is highly configurable and can be integrated into various development workflows.
Pros
- Automatically fixes a wide range of coding standard issues
- Highly customizable with numerous configuration options
- Can be integrated into CI/CD pipelines and IDEs
- Regularly updated to support new PHP versions and coding standards
Cons
- May require initial setup and configuration time
- Can sometimes produce unexpected results if not configured properly
- Large codebases may take significant time to process
- Some complex coding standard issues may still require manual intervention
Code Examples
- Basic usage:
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('vendor');
$config = new PhpCsFixer\Config();
return $config->setRules([
'@PSR12' => true,
'array_syntax' => ['syntax' => 'short'],
])
->setFinder($finder);
This example creates a basic configuration for PHP-CS-Fixer, applying PSR-12 rules and using short array syntax.
- Custom rule configuration:
<?php
$config = new PhpCsFixer\Config();
return $config
->setRules([
'no_unused_imports' => true,
'ordered_imports' => [
'sort_algorithm' => 'alpha',
'imports_order' => ['class', 'function', 'const'],
],
]);
This configuration enables removal of unused imports and orders imports alphabetically, grouping them by type.
- Using PHP-CS-Fixer in a pre-commit hook:
#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep .php)
if [ "$FILES" != "" ]
then
vendor/bin/php-cs-fixer fix $FILES
git add $FILES
fi
This script runs PHP-CS-Fixer on staged PHP files before committing, ensuring code style consistency.
Getting Started
-
Install PHP-CS-Fixer via Composer:
composer require --dev friendsofphp/php-cs-fixer
-
Create a configuration file
.php-cs-fixer.php
in your project root:<?php $finder = PhpCsFixer\Finder::create() ->in(__DIR__); $config = new PhpCsFixer\Config(); return $config->setRules([ '@PSR12' => true, ]) ->setFinder($finder);
-
Run PHP-CS-Fixer:
vendor/bin/php-cs-fixer fix
This will apply the default PSR-12 rules to your project. Customize the configuration file as needed for your specific requirements.
Competitor Comparisons
A tool to automatically fix PHP Coding Standards issues
Pros of PHP-CS-Fixer
- Actively maintained and regularly updated
- Extensive configuration options for customizing coding standards
- Large community support and contributions
Cons of PHP-CS-Fixer
- Learning curve for complex configurations
- May require additional setup for integration with certain IDEs or CI/CD pipelines
Code Comparison
Both repositories contain the same codebase, as they are the same project. Here's an example of how to use PHP-CS-Fixer in a PHP project:
<?php
$config = new PhpCsFixer\Config();
$config
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'no_unused_imports' => true,
])
->setFinder(PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('vendor')
)
;
return $config;
This configuration file sets up PHP-CS-Fixer to use PSR-2 coding standards, short array syntax, and removes unused imports. It also excludes the 'vendor' directory from being processed.
Note: Since both repositories are identical, there are no direct comparisons to be made between them. The pros and cons listed above apply to the PHP-CS-Fixer project as a whole.
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
Pros of PHP_CodeSniffer
- More flexible and customizable, allowing users to define their own coding standards
- Supports a wider range of PHP versions, including older ones
- Can be used for both detecting and fixing coding standard violations
Cons of PHP_CodeSniffer
- Generally slower performance compared to PHP-CS-Fixer
- Less opinionated, which may require more setup and configuration
- Fixing capabilities are not as advanced as PHP-CS-Fixer
Code Comparison
PHP_CodeSniffer:
<?php
$phpcsFile = $phpcsFile;
$tokens = $phpcsFile->getTokens();
foreach ($tokens as $token) {
// Process tokens
}
PHP-CS-Fixer:
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('vendor');
$config = new PhpCsFixer\Config();
return $config->setRules([
'@PSR2' => true,
]);
Both tools aim to improve code quality and maintain consistent coding standards in PHP projects. PHP_CodeSniffer offers more flexibility and customization options, making it suitable for projects with specific coding standards. On the other hand, PHP-CS-Fixer provides better performance and more advanced fixing capabilities, making it ideal for projects that want to quickly enforce common coding standards with minimal configuration.
A PHP static analysis tool for finding errors and security vulnerabilities in PHP applications
Pros of Psalm
- Provides static analysis and type checking, enhancing code quality and catching potential errors
- Offers more comprehensive analysis of code structure and potential issues
- Supports gradual typing, allowing for incremental adoption in existing projects
Cons of Psalm
- Steeper learning curve due to its more complex features and configuration options
- May produce more false positives, requiring additional configuration to fine-tune
Code Comparison
Psalm example:
<?php
/** @psalm-param array<string, int> $data */
function processData(array $data): void {
foreach ($data as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}
PHP-CS-Fixer example:
<?php
function processData(array $data): void
{
foreach ($data as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}
Psalm focuses on type checking and static analysis, while PHP-CS-Fixer primarily handles code style and formatting. Psalm's example includes type annotations for enhanced static analysis, whereas PHP-CS-Fixer's example demonstrates consistent code formatting.
PHP Static Analysis Tool - discover bugs in your code without running it!
Pros of PHPStan
- Performs static analysis to detect bugs and errors without running the code
- Provides more in-depth type checking and inference
- Offers customizable rule levels for gradual adoption
Cons of PHPStan
- Steeper learning curve due to its complexity
- May produce false positives in certain scenarios
- Requires more configuration for optimal results
Code Comparison
PHPStan example:
<?php
function foo(int $a, string $b): void {
echo $a + $b;
}
PHPStan would detect the type mismatch in the addition operation.
PHP-CS-Fixer example:
<?php
function foo ( $a,$b ){
echo $a+$b;
}
PHP-CS-Fixer would format the code to improve readability:
<?php
function foo($a, $b)
{
echo $a + $b;
}
PHP-CS-Fixer focuses on code style and formatting, while PHPStan performs deeper static analysis. PHPStan is better suited for catching potential runtime errors and improving code quality, whereas PHP-CS-Fixer excels at maintaining consistent coding standards across projects. Both tools complement each other and can be used together for comprehensive PHP code improvement.
Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.
Pros of phan
- Performs advanced static analysis and type checking
- Detects a wider range of potential issues and bugs
- Offers more in-depth analysis of code quality and potential runtime errors
Cons of phan
- Steeper learning curve and more complex configuration
- May produce more false positives, requiring careful tuning
- Slower analysis time, especially for larger codebases
Code Comparison
PHP-CS-Fixer (fixing code style):
$foo = array("bar" => "baz");
$hello = "world";
After fixing:
$foo = ['bar' => 'baz'];
$hello = 'world';
phan (static analysis):
function greet($name) {
return "Hello, " . $name;
}
greet(42);
phan output:
test.php:4 PhanTypeMismatchArgument Argument 1 ($name) is 42 of type 42 but greet() takes string defined at test.php:1
PHP-CS-Fixer focuses on code style and formatting, while phan performs deep static analysis to detect potential bugs and type-related issues. PHP-CS-Fixer is easier to set up and use, making it more accessible for quick code style improvements. phan, on the other hand, offers more comprehensive analysis but requires more configuration and may take longer to run, especially on larger projects.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
PHP Coding Standards Fixer
The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., or other community driven ones like the Symfony one. You can also define your (team's) style through configuration.
It can modernize your code (like converting the pow
function to the **
operator on PHP 5.6)
and (micro) optimize it.
If you are already using a linter to identify coding standards problems in your code, you know that fixing them by hand is tedious, especially on large projects. This tool does not only detect them, but also fixes them for you.
Supported PHP Versions
- PHP 7.4
- PHP 8.0
- PHP 8.1
- PHP 8.2
- PHP 8.3
Note Each new PHP version requires a huge effort to support the new syntax. That's why the latest PHP version might not be supported yet. If you need it, please, consider supporting the project in any convenient way, for example with code contribution or reviewing existing PRs. To run PHP CS Fixer on yet unsupported versions "at your own risk" - leverage the PHP_CS_FIXER_IGNORE_ENV.
Documentation
Installation
The recommended way to install PHP CS Fixer is to use Composer:
composer require --dev friendsofphp/php-cs-fixer
## or when facing conflicts in dependencies:
composer require --dev php-cs-fixer/shim
For more details and other installation methods (also with Docker or behind CI), see installation instructions.
Usage
Assuming you installed PHP CS Fixer as instructed above, you can run the
following command to fix the PHP files in the src
directory:
./vendor/bin/php-cs-fixer fix src
See usage, list of built-in rules, list of rule sets and configuration file documentation for more details.
If you need to apply code styles that are not supported by the tool, you can create custom rules.
Editor Integration
Dedicated plugins exist for:
Community
The PHP CS Fixer is maintained on GitHub at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. Bug reports and ideas about new features are welcome there.
You can reach us in the GitHub Discussions regarding the project, configuration, possible improvements, ideas and questions. Please visit us there!
Contribute
The tool comes with quite a few built-in fixers, but everyone is more than welcome to contribute more of them.
Top Related Projects
A tool to automatically fix PHP Coding Standards issues
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
A PHP static analysis tool for finding errors and security vulnerabilities in PHP applications
PHP Static Analysis Tool - discover bugs in your code without running it!
Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot