Slevomat Coding Standard

repository·master·Indexed 23 days ago

https://github.com/slevomat/coding-standard

A comprehensive set of custom sniffs for PHP_CodeSniffer designed to improve functional safety, remove dead code, and ensure consistent formatting in PHP codebases. It provides a wide array of sniffs categorized by functional area, including support for automatic error fixing via phpcbf and local suppression using @phpcsSuppress.

Tokens
14.7K
Snippets
22
Records
110
Agent score
81%

What's inside slevomat/coding-standard

  1. Overview of Slevomat Coding Standard

    master

    Slevomat Coding Standard is a collection of sniffs for PHP_CodeSniffer. The sniffs are categorized into three main types to help maintain high-quality PHP codebases:

    • Functional: Improves the safety and behavior of your code.
    • Cleaning: Detects dead code that can be removed.
    • Formatting: Ensures consistent code appearance and style.
  2. Enforce Class Keyword Order

    master
    The SlevomatCodingStandard.Classes.ClassKeywordOrder sniff enforces the correct order of class modifiers. The required order is: (final | abstract) readonly class. You must use either final or abstract (never both), followed by readonly if present, and then the class keyword.
  3. Manage Yoda conditions

    master

    Yoda conditions (e.g., if (true === $variable)) can be managed using two opposing sniffs:

    1. SlevomatCodingStandard.ControlStructures.DisallowYodaComparison: Disallows Yoda conditions and looks for/fixes them throughout the code.
    2. SlevomatCodingStandard.ControlStructures.RequireYodaComparison: Requires the use of Yoda conditions.

    If using RequireYodaComparison, you can use the alwaysVariableOnRight setting (default: false) to move variables to the right side of the operator.

  4. Understand Slevomat Coding Standard Sniff Capabilities

    master

    The Slevomat Coding Standard provides a wide array of PHP sniffs to enforce coding styles and best practices. When browsing the list of available sniffs, you can identify their capabilities using specific icons:

    • 🔧 Automatic error fixing: These sniffs can automatically fix the detected coding standard violations (e.g., via phpcs with --fix or similar tools).
    • 🚧 Local suppression: These sniffs can be suppressed locally in your code if a specific instance requires an exception to the rule.
  5. Install Slevomat Coding Standard via Composer

    master

    The recommended installation method is using Composer. Add slevomat/coding-standard to your require-dev section.

    It is also highly recommended to install php-parallel-lint/php-parallel-lint to check for syntax errors before running sniffs. Sniffs require syntactically valid code to behave predictably. You should run PHP-Parallel-Lint in your build pipeline before PHP_CodeSniffer and exit early if it fails.

    {
    	"require-dev": {
    		"slevomat/coding-standard": "~8.0"
    	}
    }
  6. Suppress sniffs locally using @phpcsSuppress

    master

    If you need to ignore a specific sniff violation for a particular piece of code, you can use the @phpcsSuppress annotation. Sniffs that support this are marked with the 🚧 symbol.

    To suppress an error, use its full error code (e.g., SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint) in the annotation.

    /**
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
     * @param int $max
     */
    public function createProgressBar($max = 0): ProgressBar
    {
    
    }
  7. Fix coding standard violations automatically with phpcbf

    master

    Sniffs marked with the 🔧 symbol support automatic fixing. To apply these fixes to your codebase, run phpcbf instead of phpcs using your ruleset.xml.

    Note: Always back up your code before running automatic fixes and manually verify the results, as the fixer can occasionally produce unexpected output.

    vendor/bin/phpcbf --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests
  8. Run selected sniffs using a custom ruleset.xml

    master

    To run only specific sniffs from the standard, create a custom ruleset.xml file. In this file, use the <config name="installed_paths" ... /> tag to point to the Slevomat Coding Standard location (relative to your PHPCS source) and then reference the specific sniffs you want to include using the <rule ref="..."/> tag.

    Once configured, run phpcs pointing to your ruleset.

    <?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>
    vendor/bin/phpcs --standard=ruleset.xml --extensions=php --tab-width=4 -sp src tests
  9. Exclude specific sniffs from the standard

    master

    You can include the entire Slevomat Coding Standard in your ruleset.xml and then exclude specific sniffs.

    Warning: This is not the recommended approach. Because the standard adds new sniffs in minor versions, your builds may break if you use version constraints like ^ or ~ in composer.json. It is better to explicitly include only the sniffs you want.

    <?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>
  10. Enforce declare(strict_types = 1)

    master

    Use SlevomatCodingStandard.TypeHints.DeclareStrictTypes to ensure every PHP file includes the declare(strict_types = 1) statement.

    Settings:

    • declareOnFirstLine: Requires the declaration to be on the first line immediately after <?php.
    • linesCountBeforeDeclare: Number of lines allowed between <?php and the declare statement (ignored if declareOnFirstLine is enabled).
    • linesCountAfterDeclare: Number of lines allowed between the declare statement and the next statement.
    • spacesCountAroundEqualsSign: Number of required spaces around the = operator.
  11. Disallow joining multiple attributes in one block

    master

    Use SlevomatCodingStandard.Attributes.DisallowAttributesJoining to ensure that each attribute is placed inside its own #[] block. This prevents comma-separated lists like #[AttributeOne, AttributeTwo] and forces them to be split into individual blocks like:

    #[AttributeOne]
    #[AttributeTwo]