Convert Figma logo to code with AI

slevomat logocoding-standard

Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs

1,381
171
1,381
100

Top Related Projects

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

A tool to automatically fix PHP Coding Standards issues

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

5,537

A static analysis tool for finding errors in PHP applications

5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

🔰 Instant PHP quality checks from your console

Quick Overview

Slevomat Coding Standard is a collection of sniffs for PHP_CodeSniffer that enforces high coding standards and best practices in PHP projects. It provides a comprehensive set of rules to maintain code quality, consistency, and readability across PHP codebases.

Pros

  • Extensive set of customizable coding rules
  • Regular updates and active maintenance
  • Integrates seamlessly with popular IDEs and CI tools
  • Improves overall code quality and maintainability

Cons

  • Can be overwhelming for beginners due to the large number of rules
  • Some rules may be too opinionated for certain projects
  • Requires initial setup and configuration
  • May increase code review time as developers adjust to the standards

Code Examples

  1. Installing Slevomat Coding Standard:
composer require --dev slevomat/coding-standard
  1. Configuring PHP_CodeSniffer to use Slevomat Coding Standard:
<?xml version="1.0"?>
<ruleset name="MyProject">
    <rule ref="vendor/slevomat/coding-standard/SlevomatCodingStandard/ruleset.xml">
        <!-- Customize rules here -->
    </rule>
</ruleset>
  1. Running PHP_CodeSniffer with Slevomat Coding Standard:
vendor/bin/phpcs --standard=ruleset.xml src/

Getting Started

  1. Install PHP_CodeSniffer and Slevomat Coding Standard:

    composer require --dev squizlabs/php_codesniffer slevomat/coding-standard
    
  2. Create a phpcs.xml configuration file in your project root:

    <?xml version="1.0"?>
    <ruleset name="MyProject">
        <rule ref="vendor/slevomat/coding-standard/SlevomatCodingStandard/ruleset.xml">
            <!-- Customize rules as needed -->
        </rule>
    </ruleset>
    
  3. Run PHP_CodeSniffer:

    vendor/bin/phpcs --standard=phpcs.xml src/
    
  4. (Optional) Add a composer script for easier execution:

    {
        "scripts": {
            "cs": "phpcs --standard=phpcs.xml src/"
        }
    }
    

    Then run: composer cs

Competitor Comparisons

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

Pros of PHP_CodeSniffer

  • More established and widely adopted in the PHP community
  • Supports a broader range of PHP versions
  • Includes built-in standards like PSR-1, PSR-2, and PSR-12

Cons of PHP_CodeSniffer

  • Less focused on modern PHP practices and newer language features
  • Slower performance when processing large codebases
  • Configuration can be more complex for custom rulesets

Code Comparison

PHP_CodeSniffer:

<?php
$sniff = new PHP_CodeSniffer\Sniffs\Sniff();
$sniff->register();
$sniff->process($phpcsFile, $stackPtr);

Slevomat Coding Standard:

<?php
$sniff = new SlevomatCodingStandard\Sniffs\Sniff();
$sniff->register();
$sniff->process($phpcsFile, $stackPtr);

Both projects use similar APIs for creating and registering sniffs, but Slevomat Coding Standard focuses on more modern PHP practices and stricter rules. PHP_CodeSniffer provides a broader foundation for PHP code analysis, while Slevomat Coding Standard offers specialized, opinionated rules for maintaining high-quality codebases.

PHP_CodeSniffer is better suited for projects requiring compatibility with older PHP versions or those following standard PSR guidelines. Slevomat Coding Standard is ideal for teams working with modern PHP and seeking stricter code quality enforcement.

A tool to automatically fix PHP Coding Standards issues

Pros of PHP-CS-Fixer

  • More comprehensive set of fixers and rules
  • Supports automatic code fixing, not just detection
  • Highly configurable with a wide range of options

Cons of PHP-CS-Fixer

  • Can be slower for large codebases due to its extensive ruleset
  • May require more setup and configuration to achieve desired results
  • Learning curve can be steeper for beginners

Code Comparison

PHP-CS-Fixer configuration:

<?php
$config = new PhpCsFixer\Config();
return $config->setRules([
    '@PSR2' => true,
    'array_syntax' => ['syntax' => 'short'],
    'no_unused_imports' => true,
]);

Slevomat Coding Standard configuration:

<ruleset name="MyStandard">
    <rule ref="vendor/slevomat/coding-standard/SlevomatCodingStandard/ruleset.xml">
        <exclude name="SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint"/>
    </rule>
</ruleset>

Both tools aim to improve PHP code quality, but PHP-CS-Fixer offers more extensive fixing capabilities and a wider range of rules. Slevomat Coding Standard, while more focused, can be easier to set up and integrate with existing PHP_CodeSniffer configurations. The choice between the two depends on project requirements, team preferences, and the level of customization needed.

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

Pros of PHPStan

  • More comprehensive static analysis, detecting a wider range of potential issues
  • Customizable rule levels for gradual adoption and integration
  • Extensible through plugins and custom rules

Cons of PHPStan

  • Steeper learning curve due to its complexity
  • May produce more false positives, requiring fine-tuning
  • Slower analysis speed for large codebases

Code Comparison

PHPStan:

<?php
function foo(int $a, int $b): int {
    return $a + $b;
}
foo('1', 2);

Slevomat Coding Standard:

<?php
function foo($a, $b) {
    return $a + $b;
}
foo('1', 2);

PHPStan would detect the type mismatch in the function call, while Slevomat Coding Standard focuses more on coding style and best practices.

Summary

PHPStan is a powerful static analysis tool that offers deep code inspection and error detection. It excels in finding potential bugs and type-related issues. Slevomat Coding Standard, on the other hand, is primarily focused on enforcing coding standards and best practices.

While PHPStan provides more comprehensive analysis, it may require more setup and configuration. Slevomat Coding Standard is easier to integrate but offers less extensive error detection. Both tools can be valuable additions to a PHP project, often used in combination to improve code quality and maintainability.

5,537

A static analysis tool for finding errors in PHP applications

Pros of Psalm

  • More comprehensive static analysis tool, covering a wider range of PHP issues
  • Supports type inference and advanced type checking
  • Integrates with popular IDEs and CI tools

Cons of Psalm

  • Steeper learning curve due to its extensive features
  • May produce more false positives, requiring fine-tuning
  • Potentially slower analysis for large codebases

Code Comparison

Psalm:

/** @psalm-suppress PossiblyNullReference */
$result = $maybeNull->someMethod();

Coding Standard:

// No direct equivalent, focuses on coding style rather than type analysis
$result = $maybeNull->someMethod();

Key Differences

  • Psalm is a static analysis tool focusing on type checking and bug detection
  • Coding Standard is primarily a coding style checker and formatter
  • Psalm offers more advanced features for improving code quality and reliability
  • Coding Standard is easier to set up and use for basic code style enforcement

Use Cases

  • Use Psalm for comprehensive static analysis and type checking in large projects
  • Use Coding Standard for enforcing consistent coding style across a team
  • Consider using both tools in conjunction for a well-rounded code quality approach
5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

Pros of phan

  • More comprehensive static analysis, detecting a wider range of potential issues
  • Supports type checking and inference, enhancing code reliability
  • Integrates with popular IDEs and CI/CD pipelines for seamless workflow

Cons of phan

  • Steeper learning curve due to its complexity and extensive configuration options
  • May produce more false positives, requiring fine-tuning for specific projects
  • Slower analysis speed compared to simpler coding standards tools

Code Comparison

phan example:

/**
 * @param int $x
 * @return string
 */
function foo($x) {
    return $x; // phan will detect type mismatch
}

coding-standard example:

function foo($x)
{
    return $x; // coding-standard focuses on formatting
}

phan excels at detecting logical and type-related issues, while coding-standard primarily enforces coding style and formatting rules. phan offers more advanced analysis capabilities but may require more setup and configuration. coding-standard is simpler to use and faster to run but focuses mainly on code style consistency rather than deep static analysis.

🔰 Instant PHP quality checks from your console

Pros of PHP Insights

  • Provides a comprehensive analysis of PHP code, including metrics, architecture, and style
  • Offers a user-friendly CLI interface with colorful output and progress bars
  • Integrates multiple tools and rulesets into a single package

Cons of PHP Insights

  • May have a steeper learning curve due to its extensive feature set
  • Can be slower to run compared to more focused tools like Slevomat Coding Standard
  • Might require more configuration to tailor to specific project needs

Code Comparison

PHP Insights:

$insightsConfig = [
    'preset' => 'default',
    'ide' => 'phpstorm',
    'exclude' => [
        'path/to/exclude',
    ],
];

Slevomat Coding Standard:

$config = [
    'installed_paths' => 'vendor/slevomat/coding-standard',
    'sniffs' => [
        'SlevomatCodingStandard.TypeHints.DeclareStrictTypes',
    ],
];

Both tools aim to improve PHP code quality, but PHP Insights offers a more comprehensive analysis with a user-friendly interface, while Slevomat Coding Standard focuses specifically on coding standards and can be more lightweight. The choice between them depends on project requirements and team preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Slevomat Coding Standard

Latest version Downloads Build status Code coverage PHPStan

Slevomat Coding Standard for PHP_CodeSniffer provides sniffs that fall into three categories:

  • Functional - improving the safety and behaviour of code
  • Cleaning - detecting dead code
  • Formatting - rules for consistent code looks

Table of contents

  1. Alphabetical list of sniffs
  2. Installation
  3. How to run the sniffs
  1. Fixing errors automatically
  2. Suppressing sniffs locally
  3. Contributing

Alphabetical list of sniffs

🔧 = Automatic errors fixing

🚧 = Sniff check can be suppressed locally

Installation

The recommended way to install Slevomat Coding Standard is through Composer.

{
	"require-dev": {
		"slevomat/coding-standard": "~8.0"
	}
}

It's also recommended to install php-parallel-lint/php-parallel-lint which checks source code for syntax errors. Sniffs count on the processed code to be syntactically valid (no parse errors), otherwise they can behave unexpectedly. It is advised to run PHP-Parallel-Lint in your build tool before running PHP_CodeSniffer and exiting the build process early if PHP-Parallel-Lint fails.

How to run the sniffs

You can choose one of two ways to run only selected sniffs from the standard on your codebase:

Choose which sniffs to run

The recommended way is to write your own ruleset.xml by referencing only the selected sniffs. This is a sample ruleset.xml:

<?xml version="1.0"?>
<ruleset name="AcmeProject">
	<config name="installed_paths" value="../../slevomat/coding-standard"/><!-- relative path from PHPCS source location -->
	<rule ref="SlevomatCodingStandard.Arrays.TrailingArrayComma"/>
	<!-- other sniffs to include -->
</ruleset>

Then run the phpcs executable the usual way:

vendor/bin/phpcs --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests

Exclude sniffs you don't want to run

You can also mention Slevomat Coding Standard in your project's ruleset.xml and exclude only some sniffs:

<?xml version="1.0"?>
<ruleset name="AcmeProject">
	<rule ref="vendor/slevomat/coding-standard/SlevomatCodingStandard/ruleset.xml"><!-- relative path to your ruleset.xml -->
		<!-- sniffs to exclude -->
	</rule>
</ruleset>

However it is not a recommended way to use Slevomat Coding Standard, because your build can break when moving between minor versions of the standard (which can happen if you use ^ or ~ version constraint in composer.json). We regularly add new sniffs even in minor versions meaning your code won't most likely comply with new minor versions of the package.

Fixing errors automatically

Sniffs in this standard marked by the 🔧 symbol support automatic fixing of coding standard violations. To fix your code automatically, run phpcbf instead of phpcs:

vendor/bin/phpcbf --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests

Always remember to back up your code before performing automatic fixes and check the results with your own eyes as the automatic fixer can sometimes produce unwanted results.

Suppressing sniffs locally

Selected sniffs in this standard marked by the 🚧 symbol can be suppressed for a specific piece of code using an annotation. Consider the following example:

/**
 * @param int $max
 */
public function createProgressBar($max = 0): ProgressBar
{

}

The parameter $max could have a native int scalar typehint. But because the method in the parent class does not have this typehint, so this one cannot have it either. PHP_CodeSniffer shows a following error:

----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 67 | ERROR | [x] Method ErrorsConsoleStyle::createProgressBar()
    |       |     does not have native type hint for its parameter $max
    |       |     but it should be possible to add it based on @param
    |       |     annotation "int".
    |       |     (SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint)

If we want to suppress this error instead of fixing it, we can take the error code (SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint) and use it with a @phpcsSuppress annotation like this:

/**
 * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
 * @param int $max
 */
public function createProgressBar($max = 0): ProgressBar
{

}

Contributing

To make this repository work on your machine, clone it and run these two commands in the root directory of the repository:

composer install
bin/phing

After writing some code and editing or adding unit tests, run phing again to check that everything is OK:

bin/phing

We are always looking forward to your bugreports, feature requests and pull requests. Thank you.

Code of Conduct

This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.