Convert Figma logo to code with AI

squizlabs logoPHP_CodeSniffer

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

10,665
1,480
10,665
295

Top Related Projects

Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs

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.

2,321

PHPMD is a spin-off project of PHP Depend and aims to be a PHP equivalent of the well known Java tool PMD. PHPMD can be seen as an user friendly frontend application for the raw metrics stream measured by PHP Depend.

Quick Overview

PHP_CodeSniffer is a popular open-source tool for detecting violations of coding standards in PHP code. It provides a set of sniffs that can be used to check code against various coding standards, including PSR-1, PSR-2, and PSR-12. PHP_CodeSniffer can also be used to automatically fix many of the coding standard violations it detects.

Pros

  • Highly customizable with support for custom coding standards and sniffs
  • Integrates well with various IDEs, text editors, and CI/CD pipelines
  • Can automatically fix many coding standard violations
  • Supports multiple file formats, including PHP, JavaScript, and CSS

Cons

  • Can be resource-intensive on large codebases
  • Some users find the default configuration too strict
  • Learning curve for creating custom sniffs and standards
  • Occasional false positives in certain edge cases

Code Examples

  1. Running PHP_CodeSniffer on a file:
./vendor/bin/phpcs /path/to/code/myfile.php
  1. Automatically fixing violations:
./vendor/bin/phpcbf /path/to/code/myfile.php
  1. Specifying a coding standard:
./vendor/bin/phpcs --standard=PSR12 /path/to/code
  1. Excluding specific sniffs:
./vendor/bin/phpcs --standard=PSR12 --exclude=Generic.Files.LineLength /path/to/code

Getting Started

  1. Install PHP_CodeSniffer using Composer:
composer require --dev squizlabs/php_codesniffer
  1. Run PHP_CodeSniffer on your code:
./vendor/bin/phpcs /path/to/your/code
  1. To automatically fix violations:
./vendor/bin/phpcbf /path/to/your/code
  1. Customize the coding standard by creating a phpcs.xml file in your project root:
<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>My custom coding standard.</description>
    <rule ref="PSR12"/>
    <exclude-pattern>*/vendor/*</exclude-pattern>
</ruleset>
  1. Run PHP_CodeSniffer with your custom standard:
./vendor/bin/phpcs --standard=phpcs.xml /path/to/your/code

Competitor Comparisons

Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs

Pros of coding-standard

  • More extensive set of sniffs, including advanced PHP 7+ features
  • Stricter and more opinionated rules for consistent code style
  • Regular updates and active community contributions

Cons of coding-standard

  • Steeper learning curve due to more complex configuration options
  • May require more customization to fit specific project needs
  • Potentially slower performance on large codebases

Code Comparison

PHP_CodeSniffer:

<?php
$foo = array(
    'bar' => 'baz',
    'qux' => 'quux'
);

coding-standard:

<?php
$foo = [
    'bar' => 'baz',
    'qux' => 'quux',
];

The coding-standard example enforces short array syntax and trailing commas, which are not default requirements in PHP_CodeSniffer.

Summary

While PHP_CodeSniffer provides a solid foundation for PHP code sniffing, coding-standard offers a more comprehensive and opinionated set of rules. It's particularly well-suited for projects using modern PHP features and teams seeking stricter code style enforcement. However, its complexity may require more initial setup and customization. Choose based on your project's specific needs and team preferences.

A tool to automatically fix PHP Coding Standards issues

Pros of PHP-CS-Fixer

  • Automatically fixes code style issues, not just reporting them
  • Supports a wider range of coding standards and has more fixers
  • Generally faster execution, especially for large codebases

Cons of PHP-CS-Fixer

  • Less flexible in terms of creating custom sniffs/rules
  • May sometimes make unintended changes to code structure
  • Steeper learning curve for configuration and custom rules

Code Comparison

PHP_CodeSniffer:

<?php
$phpcsFile->addError('Error message', $stackPtr, 'ErrorCode');

PHP-CS-Fixer:

<?php
$tokens[$index] = new Token([T_WHITESPACE, ' ']);

PHP_CodeSniffer focuses on detecting issues, while PHP-CS-Fixer directly modifies the code to fix style problems. PHP_CodeSniffer uses a sniff-based approach, allowing for easier custom rule creation. PHP-CS-Fixer uses fixers that automatically apply changes, which can be more efficient but potentially riskier.

Both tools are widely used in the PHP community and have their strengths. PHP_CodeSniffer is often preferred for its flexibility and ease of creating custom rules, while PHP-CS-Fixer is chosen for its automatic fixing capabilities and broader range of supported coding standards.

12,802

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

Pros of PHPStan

  • Performs advanced static analysis, detecting complex issues and potential bugs
  • Offers customizable rule levels for gradual adoption
  • Provides detailed error messages with suggestions for fixes

Cons of PHPStan

  • Steeper learning curve, especially for complex configurations
  • May produce false positives in certain scenarios
  • Requires more setup time compared to PHP_CodeSniffer

Code Comparison

PHPStan:

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

PHP_CodeSniffer:

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

PHPStan would detect the type mismatch in the function call, while PHP_CodeSniffer focuses on coding style and wouldn't catch this issue.

Summary

PHPStan excels in deep static analysis, offering advanced bug detection and customizable rule levels. However, it has a steeper learning curve and may require more setup time. PHP_CodeSniffer, on the other hand, is simpler to use and focuses primarily on coding style and standards enforcement. The choice between the two depends on project needs, with PHPStan being more suitable for catching complex issues and PHP_CodeSniffer for maintaining consistent code style.

5,537

A static analysis tool for finding errors in PHP applications

Pros of Psalm

  • Performs advanced static analysis, including type inference and taint analysis
  • Offers more comprehensive error detection, including potential runtime errors
  • Provides suggestions for fixing issues and improving code quality

Cons of Psalm

  • Steeper learning curve due to its more complex configuration options
  • May produce more false positives, requiring fine-tuning of configuration
  • Slower analysis speed compared to PHP_CodeSniffer, especially on larger codebases

Code Comparison

PHP_CodeSniffer example:

<?php
function exampleFunction($param) {
    echo $param;
}

Psalm example:

<?php
/**
 * @param string $param
 * @return void
 */
function exampleFunction(string $param): void {
    echo $param;
}

In this comparison, Psalm encourages more explicit type declarations and return type hints, which can lead to improved code clarity and reduced potential for runtime errors. PHP_CodeSniffer, on the other hand, focuses more on coding style and formatting consistency.

Both tools serve important purposes in PHP development, with PHP_CodeSniffer excelling in maintaining coding standards and Psalm providing deeper insights into potential issues and type-related problems. The choice between them depends on project requirements and team preferences.

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 advanced static analysis capabilities, including type inference and inter-procedural analysis
  • Detects a wider range of potential issues, including complex logical errors and security vulnerabilities
  • Highly configurable with numerous options for customizing analysis depth and focus

Cons of Phan

  • Steeper learning curve and more complex setup compared to PHP_CodeSniffer
  • May produce more false positives, requiring careful configuration and filtering
  • Slower analysis speed, especially on larger codebases

Code Comparison

PHP_CodeSniffer example:

<?php
function exampleFunction($param) {
    echo "Hello, " . $param;
}

Phan example:

<?php
function exampleFunction(string $param): void {
    echo "Hello, " . $param;
}

In this comparison, Phan's analysis would provide more detailed type information and potential issues, while PHP_CodeSniffer would focus on coding style and basic syntax checks. Phan's version includes type hints and return type declarations, which it can use for more thorough analysis.

Both tools serve different purposes in PHP development: PHP_CodeSniffer primarily ensures coding standards compliance, while Phan performs in-depth static analysis to catch potential bugs and security issues. Developers often use both tools in conjunction for comprehensive code quality assurance.

2,321

PHPMD is a spin-off project of PHP Depend and aims to be a PHP equivalent of the well known Java tool PMD. PHPMD can be seen as an user friendly frontend application for the raw metrics stream measured by PHP Depend.

Pros of PHPMD

  • Focuses on detecting potential problems like unused variables, empty catch blocks, and overcomplicated expressions
  • Provides a wider range of metrics and design problem detection
  • Offers more customizable rulesets for specific project needs

Cons of PHPMD

  • Less comprehensive in terms of coding style and formatting checks
  • May produce more false positives, requiring careful configuration
  • Smaller community and fewer regular updates compared to PHP_CodeSniffer

Code Comparison

PHPMD example:

<?php
class Example {
    public function unusedMethod($unusedParam) {
        $unusedVariable = 'This will trigger a warning';
    }
}

PHP_CodeSniffer example:

<?php
class Example
{
    public function formattingCheck()
    {
        // This will trigger a warning about incorrect indentation
      $incorrectlyIndented = true;
    }
}

PHPMD focuses on detecting potential bugs and design problems, while PHP_CodeSniffer primarily checks coding style and formatting. PHPMD would flag the unused method, parameter, and variable in the first example, whereas PHP_CodeSniffer would highlight the incorrect indentation in the second example.

Both tools are valuable for maintaining code quality, but they serve different purposes. PHPMD is better suited for identifying potential bugs and design issues, while PHP_CodeSniffer excels at enforcing coding standards and formatting consistency.

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

[!WARNING] This repository has been abandoned. Its successor is PHPCSStandards/PHP_CodeSniffer

See issue #3932 for more information.

About

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Build Status Build Status Code consistency Join the chat at https://gitter.im/squizlabs/PHP_CodeSniffer

Requirements

PHP_CodeSniffer requires PHP version 5.4.0 or greater, although individual sniffs may have additional requirements such as external applications and scripts. See the Configuration Options manual page for a list of these requirements.

If you're using PHP_CodeSniffer as part of a team, or you're running it on a CI server, you may want to configure your project's settings using a configuration file.

Installation

The easiest way to get started with PHP_CodeSniffer is to download the Phar files for each of the commands:

# Download using curl
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar

# Or download using wget
wget https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
wget https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar

# Then test the downloaded PHARs
php phpcs.phar -h
php phpcbf.phar -h

Composer

If you use Composer, you can install PHP_CodeSniffer system-wide with the following command:

composer global require "squizlabs/php_codesniffer=*"

Make sure you have the composer bin dir in your PATH. The default value is ~/.composer/vendor/bin/, but you can check the value that you need to use by running composer global config bin-dir --absolute.

Or alternatively, include a dependency for squizlabs/php_codesniffer in your composer.json file. For example:

{
    "require-dev": {
        "squizlabs/php_codesniffer": "3.*"
    }
}

You will then be able to run PHP_CodeSniffer from the vendor bin directory:

./vendor/bin/phpcs -h
./vendor/bin/phpcbf -h

Phive

If you use Phive, you can install PHP_CodeSniffer as a project tool using the following commands:

phive install phpcs
phive install phpcbf

You will then be able to run PHP_CodeSniffer from the tools directory:

./tools/phpcs -h
./tools/phpcbf -h

PEAR

If you use PEAR, you can install PHP_CodeSniffer using the PEAR installer. This will make the phpcs and phpcbf commands immediately available for use. To install PHP_CodeSniffer using the PEAR installer, first ensure you have installed PEAR and then run the following command:

pear install PHP_CodeSniffer

Git Clone

You can also download the PHP_CodeSniffer source and run the phpcs and phpcbf commands directly from the Git clone:

git clone https://github.com/squizlabs/PHP_CodeSniffer.git
cd PHP_CodeSniffer
php bin/phpcs -h
php bin/phpcbf -h

Getting Started

The default coding standard used by PHP_CodeSniffer is the PEAR coding standard. To check a file against the PEAR coding standard, simply specify the file's location:

phpcs /path/to/code/myfile.php

Or if you wish to check an entire directory you can specify the directory location instead of a file.

phpcs /path/to/code-directory

If you wish to check your code against the PSR-12 coding standard, use the --standard command line argument:

phpcs --standard=PSR12 /path/to/code-directory

If PHP_CodeSniffer finds any coding standard errors, a report will be shown after running the command.

Full usage information and example reports are available on the usage page.

Documentation

The documentation for PHP_CodeSniffer is available on the Github wiki.

Issues

Bug reports and feature requests can be submitted on the Github Issue Tracker.

Contributing

See CONTRIBUTING.md for information.

Versioning

PHP_CodeSniffer uses a MAJOR.MINOR.PATCH version number format.

The MAJOR version is incremented when:

  • backwards-incompatible changes are made to how the phpcs or phpcbf commands are used, or
  • backwards-incompatible changes are made to the ruleset.xml format, or
  • backwards-incompatible changes are made to the API used by sniff developers, or
  • custom PHP_CodeSniffer token types are removed, or
  • existing sniffs are removed from PHP_CodeSniffer entirely

The MINOR version is incremented when:

  • new backwards-compatible features are added to the phpcs and phpcbf commands, or
  • backwards-compatible changes are made to the ruleset.xml format, or
  • backwards-compatible changes are made to the API used by sniff developers, or
  • new sniffs are added to an included standard, or
  • existing sniffs are removed from an included standard

NOTE: Backwards-compatible changes to the API used by sniff developers will allow an existing sniff to continue running without producing fatal errors but may not result in the sniff reporting the same errors as it did previously without changes being required.

The PATCH version is incremented when:

  • backwards-compatible bug fixes are made

NOTE: As PHP_CodeSniffer exists to report and fix issues, most bugs are the result of coding standard errors being incorrectly reported or coding standard errors not being reported when they should be. This means that the messages produced by PHP_CodeSniffer, and the fixes it makes, are likely to be different between PATCH versions.