Files
trueskill/docs/CodeStandard.md
Jens True adc587ac0d More coding standards.
Diagrams in API documentation
2025-05-13 12:46:11 +00:00

71 KiB

PHP_CodeSniffer Coding Standard

Array Indent

The opening brace of a multi-line array must be indented at least to the same level as the start of the statement.

Valid: Opening brace of a multi-line array indented to the same level as the start of the statement. Invalid: Opening brace of a multi-line array not indented to the same level as the start of the statement.
$b = [
    1,
    2,
];

if ($condition) {
    $a =
    [
        1,
        2,
    ];
}
if ($condition) {
    $a =
[
        1,
        2,
    ];
}
Each array element must be indented exactly four spaces from the start of the statement.
Valid: Each array element is indented by exactly four spaces. Invalid: Array elements not indented by four spaces.
$a = array(
    1,
    2,
    3,
);
$a = array(
  1,
     2,
        3,
);
The array closing brace must be on a new line.
Valid: Array closing brace on its own line. Invalid: Array closing brace not on its own line.
$a = [
    1,
    2,
];
$a = [
    1,
    2,];
The closing brace must be aligned with the start of the statement containing the array opener.
Valid: Closing brace aligned with the start of the statement containing the array opener. Invalid: Closing brace not aligned with the start of the statement containing the array opener.
$a = array(
    1,
    2,
);
$a = array(
    1,
    2,
  );

Short Array Syntax

Short array syntax must be used to define arrays.

Valid: Short form of array. Invalid: Long form of array.
$arr = [
    'foo' => 'bar',
];
$arr = array(
    'foo' => 'bar',
);

Long Array Syntax

Long array syntax must be used to define arrays.

Valid: Long form of array. Invalid: Short form of array.
$arr = array(
    'foo' => 'bar',
);
$arr = [
    'foo' => 'bar',
];

Duplicate Class Names

Class and Interface names should be unique in a project. They should never be duplicated.

Valid: A unique class name. Invalid: A class duplicated (including across multiple files).
class Foo
{
}
class Foo
{
}

class Foo
{
}

Opening Brace on Same Line

The opening brace of a class must be on the same line after the definition and must be the last thing on that line.

Valid: Opening brace on the same line. Invalid: Opening brace on the next line.
class Foo {
}
class Foo
{
}
Valid: Opening brace is the last thing on the line. Invalid: Opening brace not last thing on the line.
class Foo {
}
class Foo { // Start of class.
}

Assignment In Condition

Variable assignments should not be made within conditions.

Valid: A variable comparison being executed within a condition. Invalid: A variable assignment being made within a condition.
if ($test === 'abc') {
    // Code.
}
if ($test = 'abc') {
    // Code.
}

Empty PHP Statement

Empty PHP tags are not allowed.

Valid: There is at least one statement inside the PHP tag pair. Invalid: There is no statement inside the PHP tag pair.
<?php echo 'Hello World'; ?>
<?= 'Hello World'; ?>
<?php ; ?>
<?=  ?>
Superfluous semicolons are not allowed.
Valid: There is no superfluous semicolon after a PHP statement. Invalid: There are one or more superfluous semicolons after a PHP statement.
function_call();
if (true) {
    echo 'Hello World';
}
function_call();;;
if (true) {
    echo 'Hello World';
};

Empty Statements

Control Structures must have at least one statement inside of the body.

Valid: There is a statement inside the control structure. Invalid: The control structure has no statements.
if ($test) {
    $var = 1;
}
if ($test) {
    // do nothing
}

Condition-Only For Loops

For loops that have only a second expression (the condition) should be converted to while loops.

Valid: A for loop is used with all three expressions. Invalid: A for loop is used without a first or third expression.
for ($i = 0; $i < 10; $i++) {
    echo "{$i}\n";
}
for (;$test;) {
    $test = doSomething();
}

For Loops With Function Calls in the Test

For loops should not call functions inside the test for the loop when they can be computed beforehand.

Valid: A for loop that determines its end condition before the loop starts. Invalid: A for loop that unnecessarily computes the same value on every iteration.
$end = count($foo);
for ($i = 0; $i < $end; $i++) {
    echo $foo[$i]."\n";
}
for ($i = 0; $i < count($foo); $i++) {
    echo $foo[$i]."\n";
}

Jumbled Incrementers

Incrementers in nested loops should use different variable names.

Valid: Two different variables being used to increment. Invalid: Inner incrementer is the same variable name as the outer one.
for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
    }
}
for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $i++) {
    }
}

Require Explicit Boolean Operator Precedence

Forbids mixing different binary boolean operators (&&, ||, and, or, xor) within a single expression without making precedence clear using parentheses.

Valid: Making precedence clear with parentheses. Invalid: Not using parentheses.
$one = false;
$two = false;
$three = true;

$result = ($one && $two) || $three;
$result2 = $one && ($two || $three);
$result3 = ($one && !$two) xor $three;
$result4 = $one && (!$two xor $three);

if (
    ($result && !$result3)
    || (!$result && $result3)
) {}
$one = false;
$two = false;
$three = true;

$result = $one && $two || $three;

$result3 = $one && !$two xor $three;


if (
    $result && !$result3
    || !$result && $result3
) {}

Unconditional If Statements

If statements that are always evaluated should not be used.

Valid: An if statement that only executes conditionally. Invalid: An if statement that is always performed.
if ($test) {
    $var = 1;
}
if (true) {
    $var = 1;
}
Valid: An if statement that only executes conditionally. Invalid: An if statement that is never performed.
if ($test) {
    $var = 1;
}
if (false) {
    $var = 1;
}

Unnecessary Final Modifiers

Methods should not be declared final inside of classes that are declared final.

Valid: A method in a final class is not marked final. Invalid: A method in a final class is also marked final.
final class Foo
{
    public function bar()
    {
    }
}
final class Foo
{
    public final function bar()
    {
    }
}

Unused function parameters

All parameters in a functions signature should be used within the function.

Valid: All the parameters are used. Invalid: One of the parameters is not being used.
function addThree($a, $b, $c)
{
    return $a + $b + $c;
}
function addThree($a, $b, $c)
{
    return $a + $b;
}

Useless Overriding Method

It is discouraged to override a method if the overriding method only calls the parent method.

Valid: A method that extends functionality of a parent method. Invalid: An overriding method that only calls the parent method.
final class Foo extends Baz
{
    public function bar()
    {
        parent::bar();
        $this->doSomethingElse();
    }
}
final class Foo extends Baz
{
    public function bar()
    {
        parent::bar();
    }
}

Doc Comment

Enforces rules related to the formatting of DocBlocks ("Doc Comments") in PHP code.

DocBlocks are a special type of comment that can provide information about a structural element. In the context of DocBlocks, the following are considered structural elements:
class, interface, trait, enum, function, property, constant, variable declarations and require/include[_once] statements.

DocBlocks start with a /** marker and end on */. This sniff will check the formatting of all DocBlocks, independently of whether or not they are attached to a structural element. A DocBlock must not be empty.

Valid: DocBlock with some content. Invalid: Empty DocBlock.
/**
 * Some content.
 */
/**
 * 
 */
The opening and closing DocBlock tags must be the only content on the line.
Valid: The opening and closing DocBlock tags have to be on a line by themselves. Invalid: The opening and closing DocBlock tags are not on a line by themselves.
/**
 * Short description.
 */
/** Short description. */
The DocBlock must have a short description, and it must be on the first line.
Valid: DocBlock with a short description on the first line. Invalid: DocBlock without a short description or short description not on the first line.
/**
 * Short description.
 */
/**
 * @return int
 */

/**
 *
 * Short description.
 */
Both the short description, as well as the long description, must start with a capital letter.
Valid: Both the short and long description start with a capital letter. Invalid: Neither short nor long description starts with a capital letter.
/**
 * Short description.
 *
 * Long description.
 */
/**
 * short description.
 *
 * long description.
 */
There must be exactly one blank line separating the short description, the long description and tag groups.
Valid: One blank line separating the short description, the long description and tag groups. Invalid: More than one or no blank line separating the short description, the long description and tag groups.
/**
 * Short description.
 *
 * Long description.
 *
 * @param int $foo
 */
/**
 * Short description.
 *
 *

 * Long description.
 * @param int $foo
 */
Parameter tags must be grouped together.
Valid: Parameter tags grouped together. Invalid: Parameter tags not grouped together.
/**
 * Short description.
 *
 * @param int $foo
 * @param string $bar
 */
/**
 * Short description.
 *
 * @param int $foo
 *
 * @param string $bar
 */
Parameter tags must not be grouped together with other tags.
Valid: Parameter tags are not grouped together with other tags. Invalid: Parameter tags grouped together with other tags.
/**
 * Short description.
 *
 * @param int $foo
 *
 * @since      3.4.8
 * @deprecated 6.0.0
 */
/**
 * Short description.
 *
 * @param      int $foo
 * @since      3.4.8
 * @deprecated 6.0.0
 */
Tag values for different tags in the same group must be aligned with each other.
Valid: Tag values for different tags in the same tag group are aligned with each other. Invalid: Tag values for different tags in the same tag group are not aligned with each other.
/**
 * Short description.
 *
 * @since      0.5.0
 * @deprecated 1.0.0
 */
/**
 * Short description.
 *
 * @since 0.5.0
 * @deprecated 1.0.0
 */
Parameter tags must be defined before other tags in a DocBlock.
Valid: Parameter tags are defined first. Invalid: Parameter tags are not defined first.
/**
 * Short description.
 *
 * @param string $foo
 *
 * @return void
 */
/**
 * Short description.
 *
 * @return void
 *
 * @param string $bar
 */
There must be no additional blank (comment) lines before the closing DocBlock tag.
Valid: No additional blank lines before the closing DocBlock tag. Invalid: Additional blank lines before the closing DocBlock tag.
/**
 * Short description.
 */
/**
 * Short description.
 *
 */

Fixme Comments

FIXME Statements should be taken care of.

Valid: A comment without a fixme. Invalid: A fixme comment.
// Handle strange case
if ($test) {
    $var = 1;
}
// FIXME: This needs to be fixed!
if ($test) {
    $var = 1;
}

Todo Comments

TODO Statements should be taken care of.

Valid: A comment without a todo. Invalid: A todo comment.
// Handle strange case
if ($test) {
    $var = 1;
}
// TODO: This needs to be fixed!
if ($test) {
    $var = 1;
}

Disallow Yoda conditions

Yoda conditions are disallowed.

Valid: Value to be asserted must go on the right side of the comparison. Invalid: Value to be asserted must not be on the left.
if ($test === null) {
    $var = 1;
}
if (null === $test) {
    $var = 1;
}

Inline Control Structures

Control Structures should use braces.

Valid: Braces are used around the control structure. Invalid: No braces are used for the control structure..
if ($test) {
    $var = 1;
}
if ($test)
    $var = 1;

Closure Linter

All javascript files should pass basic Closure Linter tests.

Valid: Valid JS Syntax is used. Invalid: Trailing comma in a javascript array.
var foo = [1, 2];
var foo = [1, 2,];

CSSLint

All css files should pass the basic csslint tests.

Valid: Valid CSS Syntax is used. Invalid: The CSS has a typo in it.
.foo: { width: 100%; }
.foo: { width: 100 %; }

JSHint

All javascript files should pass basic JSHint tests.

Valid: Valid JS Syntax is used. Invalid: The Javascript is using an undefined variable.
var foo = 5;
foo = 5;

Byte Order Marks

Byte Order Marks that may corrupt your application should not be used. These include 0xefbbbf (UTF-8), 0xfeff (UTF-16 BE) and 0xfffe (UTF-16 LE).

End of File Newline

Files should end with a newline character.

No End of File Newline

Files should not end with a newline character.

Executable Files

Files should not be executable.

Inline HTML

Files that contain PHP code should only have PHP code and should not have any "inline html".

Valid: A PHP file with only PHP code in it. Invalid: A PHP file with html in it outside of the PHP tags.
<?php
$foo = 'bar';
echo $foo . 'baz';
some string here
<?php
$foo = 'bar';
echo $foo . 'baz';

Line Endings

Unix-style line endings are preferred ("\n" instead of "\r\n").

Lowercased Filenames

Lowercase filenames are required.

One Class Per File

There should only be one class defined in a file.

Valid: Only one class in the file. Invalid: Multiple classes defined in one file.
<?php
class Foo
{
}
<?php
class Foo
{
}

class Bar
{
}

One Interface Per File

There should only be one interface defined in a file.

Valid: Only one interface in the file. Invalid: Multiple interfaces defined in one file.
<?php
interface Foo
{
}
<?php
interface Foo
{
}

interface Bar
{
}

One Object Structure Per File

There should only be one class or interface or trait defined in a file.

Valid: Only one object structure in the file. Invalid: Multiple object structures defined in one file.
<?php
trait Foo
{
}
<?php
trait Foo
{
}

class Bar
{
}

One Trait Per File

There should only be one trait defined in a file.

Valid: Only one trait in the file. Invalid: Multiple traits defined in one file.
<?php
trait Foo
{
}
<?php
trait Foo
{
}

trait Bar
{
}

Multiple Statements On a Single Line

Multiple statements are not allowed on a single line.

Valid: Two statements are spread out on two separate lines. Invalid: Two statements are combined onto one line.
$foo = 1;
$bar = 2;
$foo = 1; $bar = 2;

Aligning Blocks of Assignments

There should be one space on either side of an equals sign used to assign a value to a variable. In the case of a block of related assignments, more space may be inserted to promote readability.

Valid: Equals signs aligned. Invalid: Not aligned; harder to read.
$shortVar        = (1 + 2);
$veryLongVarName = 'string';
$var             = foo($bar, $baz);
$shortVar = (1 + 2);
$veryLongVarName = 'string';
$var = foo($bar, $baz);
When using plus-equals, minus-equals etc. still ensure the equals signs are aligned to one space after the longest variable name.
Valid: Equals signs aligned; only one space after longest var name. Invalid: Two spaces after longest var name.
$shortVar       += 1;
$veryLongVarName = 1;
$shortVar        += 1;
$veryLongVarName  = 1;
Valid: Equals signs aligned. Invalid: Equals signs not aligned.
$shortVar         = 1;
$veryLongVarName -= 1;
$shortVar        = 1;
$veryLongVarName -= 1;

No Space After Cast

Spaces are not allowed after casting operators.

Valid: A cast operator is immediately before its value. Invalid: A cast operator is followed by whitespace.
$foo = (string)1;
$foo = (string) 1;

Space After Cast

Exactly one space is allowed after a cast.

Valid: A cast operator is followed by one space. Invalid: A cast operator is not followed by whitespace.
$foo = (string) 1;
$foo = (string)1;

Space After NOT operator

Exactly one space is allowed after the NOT operator.

Valid: A NOT operator followed by one space. Invalid: A NOT operator not followed by whitespace or followed by too much whitespace.
if (! $someVar || ! $x instanceOf stdClass) {};
if (!$someVar || !$x instanceOf stdClass) {};

if (!     $someVar || !
    $x instanceOf stdClass) {};

Space Before Cast

There should be exactly one space before a cast operator.

Valid: Single space before a cast operator. Invalid: No space or multiple spaces before a cast operator.
$integer = (int) $string;
$c = $a . (string) $b;
$integer =(int) $string;
$c = $a .   (string) $b;

Call-Time Pass-By-Reference

Call-time pass-by-reference is not allowed. It should be declared in the function definition.

Valid: Pass-by-reference is specified in the function definition. Invalid: Pass-by-reference is done in the call to a function.
function foo(&$bar)
{
    $bar++;
}

$baz = 1;
foo($baz);
function foo($bar)
{
    $bar++;
}

$baz = 1;
foo(&$baz);

Function Call Argument Spacing

There should be no space before and exactly one space, or a new line, after a comma when passing arguments to a function or method.

Valid: No space before and exactly one space after a comma. Invalid: A space before and no space after a comma.
foo($bar, $baz);
foo($bar ,$baz);

Opening Function Brace Bsd Allman

Function declarations must follow the "BSD/Allman style". The opening brace is on the line
following the function declaration and is indented to the same column as the start of the
function declaration. The brace must be the last content on the line.

Valid: Opening brace on the next line. Invalid: Opening brace on the same line.
function fooFunction($arg1, $arg2 = '')
{
    // Do something
}
function fooFunction($arg1, $arg2 = '') {
    // Do something
}

Opening Function Brace Kerninghan Ritchie

The function opening brace must be on the same line as the end of the function declaration, with
exactly one space between the end of the declaration and the brace. The brace must be the last
content on the line.

Valid: Opening brace on the same line. Invalid: Opening brace on the next line.
function fooFunction($arg1, $arg2 = '') {
    // Do something.
}
function fooFunction($arg1, $arg2 = '')
{
    // Do something.
}

Cyclomatic Complexity

Functions should not have a cyclomatic complexity greater than 20, and should try to stay below a complexity of 10.

Nesting Level

Functions should not have a nesting level greater than 10, and should try to stay below 5.

Abstract class name

Abstract class names must be prefixed with "Abstract", e.g. AbstractBar.

Valid: Class name starts with 'Abstract'. Invalid: Class name does not start with 'Abstract'.
abstract class AbstractBar
{
}
abstract class Bar
{
}

camelCaps Function Names

Functions should use camelCaps format for their names. Only PHP's magic methods should use a double underscore prefix.

Valid: A function in camelCaps format. Invalid: A function in snake_case format.
function doSomething()
{
}
function do_something()
{
}

Constructor name

Constructors should be named __construct, not after the class.

Valid: The constructor is named __construct. Invalid: The old style class name constructor is used.
class Foo
{
    function __construct()
    {
    }
}
class Foo
{
    function Foo()
    {
    }
}

Interface name suffix

Interface names must be suffixed with "Interface", e.g. BarInterface.

Valid: Interface name ends on 'Interface'. Invalid: Interface name does not end on 'Interface'.
interface BarInterface
{
}
interface Bar
{
}

Trait name suffix

Trait names must be suffixed with "Trait", e.g. BarTrait.

Valid: Trait name ends on 'Trait'. Invalid: Trait name does not end on 'Trait'.
trait BarTrait
{
}
trait Bar
{
}

Constant Names

Constants should always be all-uppercase, with underscores to separate words.

Valid: All uppercase constant name. Invalid: Mixed case or lowercase constant name.
define('FOO_CONSTANT', 'foo');

class FooClass
{
    const FOO_CONSTANT = 'foo';
}
define('Foo_Constant', 'foo');

class FooClass
{
    const foo_constant = 'foo';
}

Backtick Operator

Disallow the use of the backtick operator for execution of shell commands.

Opening Tag at Start of File

The opening PHP tag should be the first item in the file.

Valid: A file starting with an opening PHP tag. Invalid: A file with content before the opening PHP tag.
<?php
echo 'Foo';
Beginning content
<?php
echo 'Foo';

Closing PHP Tags

All opening PHP tags should have a corresponding closing tag.

Valid: A closing tag paired with its opening tag. Invalid: No closing tag paired with the opening tag.
<?php
echo 'Foo';
?>
<?php
echo 'Foo';

Deprecated Functions

Deprecated functions should not be used.

Valid: A non-deprecated function is used. Invalid: A deprecated function is used.
$foo = explode('a', $bar);
$foo = split('a', $bar);

Alternative PHP Code Tags

Always use <?php ?> to delimit PHP code, do not use the ASP <% %> style tags nor the <script language="php"></script> tags. This is the most portable way to include PHP code on differing operating systems and setups.

$_REQUEST Superglobal

$_REQUEST should never be used due to the ambiguity created as to where the data is coming from. Use $_POST, $_GET, or $_COOKIE instead.

PHP Code Tags

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is the most portable way to include PHP code on differing operating systems and setups.

Goto

Discourage the use of the PHP goto language construct.

Forbidden Functions

The forbidden functions sizeof() and delete() should not be used.

Valid: count() is used in place of sizeof(). Invalid: sizeof() is used.
$foo = count($bar);
$foo = sizeof($bar);

Lowercase PHP Constants

The true, false and null constants must always be lowercase.

Valid: Lowercase constants. Invalid: Uppercase constants.
if ($var === false || $var === null) {
    $var = true;
}
if ($var === FALSE || $var === NULL) {
    $var = TRUE;
}

Lowercase Keywords

All PHP keywords should be lowercase.

Valid: Lowercase array keyword used. Invalid: Non-lowercase array keyword used.
$foo = array();
$foo = Array();

Lowercase PHP Types

All PHP types used for parameter type and return type declarations should be lowercase.

Valid: Lowercase type declarations used. Invalid: Non-lowercase type declarations used.
function myFunction(int $foo) : string {
}
function myFunction(Int $foo) : STRING {
}
All PHP types used for type casting should be lowercase.
Valid: Lowercase type used. Invalid: Non-lowercase type used.
$foo = (bool) $isValid;
$foo = (BOOL) $isValid;

Silenced Errors

Suppressing Errors is not allowed.

Valid: isset() is used to verify that a variable exists before trying to use it. Invalid: Errors are suppressed.
if (isset($foo) && $foo) {
    echo "Hello\n";
}
if (@$foo) {
    echo "Hello\n";
}

Require Strict Types

The strict_types declaration must be present.

Valid: `strict_types` declaration is present. Invalid: Missing `strict_types` declaration.
declare(strict_types=1);

declare(encoding='UTF-8', strict_types=0);
declare(encoding='ISO-8859-1');
The strict_types declaration must be enabled.
Valid: `strict_types` declaration is enabled. Invalid: `strict_types` declaration is disabled.
declare(strict_types=1);
declare(strict_types=0);

SAPI Usage

The PHP_SAPI constant should be used instead of php_sapi_name().

Valid: PHP_SAPI is used. Invalid: Function call to php_sapi_name() is used.
if (PHP_SAPI === 'cli') {
    echo "Hello, CLI user.";
}
if (php_sapi_name() === 'cli') {
    echo "Hello, CLI user.";
}

PHP Syntax

The code should use valid PHP syntax.

Valid: No PHP syntax errors. Invalid: Code contains PHP syntax errors.
echo "Hello!";
$array = [1, 2, 3];
echo "Hello!" // Missing semicolon.
$array = [1, 2, 3; // Missing closing bracket.

Uppercase PHP Constants

The true, false and null constants must always be uppercase.

Valid: Uppercase constants. Invalid: Lowercase constants.
if ($var === FALSE || $var === NULL) {
    $var = TRUE;
}
if ($var === false || $var === null) {
    $var = true;
}

Unnecessary Heredoc

If no interpolation or expressions are used in the body of a heredoc, nowdoc syntax should be used instead.

Valid: Using nowdoc syntax for a text string without any interpolation or expressions. Invalid: Using heredoc syntax for a text string without any interpolation or expressions.
$nowdoc = <<<'EOD'
some text
EOD;
$heredoc = <<<EOD
some text
EOD;
Valid: Using heredoc syntax for a text string containing interpolation or expressions. Invalid: Using heredoc syntax for a text string without any interpolation or expressions.
$heredoc = <<<"EOD"
some $text
EOD;
$heredoc = <<<"EOD"
some text
EOD;

Unnecessary String Concatenation

Strings should not be concatenated together.

Valid: A string can be concatenated with an expression. Invalid: Strings should not be concatenated together.
echo '5 + 2 = ' . (5 + 2);
echo 'Hello' . ' ' . 'World';

Subversion Properties

All PHP files in a subversion repository should have the svn:keywords property set to 'Author Id Revision' and the svn:eol-style property set to 'native'.

Arbitrary Parentheses Spacing

Arbitrary sets of parentheses should have no spaces inside.

Valid: No spaces on the inside of a set of arbitrary parentheses. Invalid: Spaces or new lines on the inside of a set of arbitrary parentheses.
$a = (null !== $extra);
$a = ( null !== $extra );

$a = (
    null !== $extra
);

No Space Indentation

Tabs should be used for indentation instead of spaces.

No Tab Indentation

Spaces should be used for indentation instead of tabs.

Heredoc Nowdoc Identifier Spacing

There should be no space between the <<< and the heredoc/nowdoc identifier string.

Valid: No space between the <<< and the identifier string. Invalid: Whitespace between the <<< and the identifier string.
$heredoc = <<<EOD
some text
EOD;
$heredoc = <<<   END
some text
END;

Increment Decrement Spacing

There should be no whitespace between variables and increment/decrement operators.

Valid: No whitespace between variables and increment/decrement operators. Invalid: Whitespace between variables and increment/decrement operators.
++$i;
--$i['key']['id'];
ClassName::$prop++;
$obj->prop--;
++ $i;
--   $i['key']['id'];
ClassName::$prop    ++;
$obj->prop
--;

Language Construct Spacing

Language constructs that can be used without parentheses, must have a single space between the language construct keyword and its content.

Valid: Single space after language construct. Invalid: No space, more than one space or newline after language construct.
echo 'Hello, World!';
throw new Exception();
return $newLine;
echo'Hello, World!';
throw   new   Exception();
return
$newLine;
A single space must be used between the "yield" and "from" keywords for a "yield from" expression.
Valid: Single space between yield and from. Invalid: More than one space or newline between yield and from.
function myGenerator() {
    yield from [1, 2, 3];
}
function myGenerator() {
    yield  from [1, 2, 3];
    yield
    from [1, 2, 3];
}

Scope Indentation

Indentation for control structures, classes, and functions should be 4 spaces per level.

Valid: 4 spaces are used to indent a control structure. Invalid: 8 spaces are used to indent a control structure.
if ($test) {
    $var = 1;
}
if ($test) {
        $var = 1;
}

Spacing After Spread Operator

There should be no space between the spread operator and the variable/function call it applies to.

Valid: No space between the spread operator and the variable/function call it applies to. Invalid: Space found between the spread operator and the variable/function call it applies to.
function foo(&...$spread) {
    bar(...$spread);

    bar(
        [...$foo],
        ...array_values($keyedArray)
    );
}
function bar(... $spread) {
    bar(...
        $spread
    );

    bar(
        [... $foo ],.../*@*/array_values($keyed)
    );
}

Default Values in Function Declarations

Arguments with default values go at the end of the argument list.

Valid: Argument with default value at end of declaration. Invalid: Argument with default value at start of declaration.
function connect($dsn, $persistent = false)
{
    ...
}
function connect($persistent = false, $dsn)
{
    ...
}

Class Declaration

Each class must be in a file by itself and must be under a namespace (a top-level vendor name).

Valid: One class in a file. Invalid: Multiple classes in a single file.
<?php
namespace Foo;

class Bar {
}
<?php
namespace Foo;

class Bar {
}

class Baz {
}
Valid: A vendor-level namespace is used. Invalid: No namespace used in file.
<?php
namespace Foo;

class Bar {
}
<?php
class Bar {
}

Side Effects

A PHP file should either contain declarations with no side effects, or should just have logic (including side effects) with no declarations.

Valid: A class defined in a file by itself. Invalid: A class defined in a file with other code.
<?php
class Foo
{
}
<?php
class Foo
{
}

echo "Class Foo loaded.";

Method Name

Method names MUST be declared in camelCase.

Valid: Method name in camelCase. Invalid: Method name not in camelCase.
class Foo
{
    private function doBar()
    {
    }
}
class Foo
{
    private function do_bar()
    {
    }
}

Class Declarations

There should be exactly 1 space between the abstract or final keyword and the class keyword and between the class keyword and the class name. The extends and implements keywords, if present, must be on the same line as the class name. When interfaces implemented are spread over multiple lines, there should be exactly 1 interface mentioned per line indented by 1 level. The closing brace of the class must go on the first line after the body of the class and must be on a line by itself.

Valid: Correct spacing around class keyword. Invalid: 2 spaces used around class keyword.
abstract class Foo
{
}
abstract  class  Foo
{
}

Property Declarations

Property names should not be prefixed with an underscore to indicate visibility. Visibility should be used to declare properties rather than the var keyword. Only one property should be declared within a statement. The static declaration must come after the visibility declaration.

Valid: Correct property naming. Invalid: An underscore prefix used to indicate visibility.
class Foo
{
    private $bar;
}
class Foo
{
    private $_bar;
}
Valid: Visibility of property declared. Invalid: Var keyword used to declare property.
class Foo
{
    private $bar;
}
class Foo
{
    var $bar;
}
Valid: One property declared per statement. Invalid: Multiple properties declared in one statement.
class Foo
{
    private $bar;
    private $baz;
}
class Foo
{
    private $bar, $baz;
}
Valid: If declared as static, the static declaration must come after the visibility declaration. Invalid: Static declaration before the visibility declaration.
class Foo
{
    public static $bar;
    private $baz;
}
class Foo
{
    static protected $bar;
}

Control Structure Spacing

Control Structures should have 0 spaces after opening parentheses and 0 spaces before closing parentheses.

Valid: Correct spacing. Invalid: Whitespace used inside the parentheses.
if ($foo) {
    $var = 1;
}
if ( $foo ) {
    $var = 1;
}

Elseif Declarations

PHP's elseif keyword should be used instead of else if.

Valid: Single word elseif keyword used. Invalid: Separate else and if keywords used.
if ($foo) {
    $var = 1;
} elseif ($bar) {
    $var = 2;
}
if ($foo) {
    $var = 1;
} else if ($bar) {
    $var = 2;
}

Switch Declaration

Case and default keywords must be lowercase.

Valid: Keywords in lowercase. Invalid: Keywords not in lowercase.
switch ($foo) {
    case 'bar':
        break;
    default:
        break;
}
switch ($foo) {
    CASE 'bar':
        break;
    Default:
        break;
}
Case statements must be followed by exactly one space.
Valid: Case statement followed by one space. Invalid: Case statement not followed by one space.
switch ($foo) {
    case 'bar':
        break;
}
switch ($foo) {
    case'bar':
        break;
}
There must be no whitespace between the case value or default keyword and the colon.
Valid: Colons not preceded by whitespace. Invalid: Colons preceded by whitespace.
switch ($foo) {
    case 'bar':
        break;
    default:
        break;
}
switch ($foo) {
    case 'bar' :
        break;
    default :
        break;
}
The case or default body must start on the line following the statement.
Valid: Body starts on the next line. Invalid: Body on the same line as the case statement.
switch ($foo) {
    case 'bar':
        break;
}
switch ($foo) {
    case 'bar': break;
}
Terminating statements must be on a line by themselves.
Valid: Terminating statement on its own line. Invalid: Terminating statement not on its own line.
switch ($foo) {
    case 'bar':
        echo $foo;
        return;
}
switch ($foo) {
    case 'bar':
        echo $foo; return;
}
Terminating statements must be indented four more spaces from the case statement.
Valid: Break statement indented correctly. Invalid: Break statement not indented four spaces.
switch ($foo) {
    case 'bar':
        break;
}
switch ($foo) {
    case 'bar':
    break;
}
Case and default statements must be defined using a colon.
Valid: Using a colon for case and default statements. Invalid: Using a semi-colon or colon followed by braces.
switch ($foo) {
    case 'bar':
        break;
    default:
        break;
}
switch ($foo) {
    case 'bar';
        break;
    default: {
        break;
    }
}
There must be a comment when fall-through is intentional in a non-empty case body.
Valid: Comment marking intentional fall-through in a non-empty case body. Invalid: No comment marking intentional fall-through in a non-empty case body.
switch ($foo) {
    case 'bar':
        echo $foo;
        // no break
    default:
        break;
}
switch ($foo) {
    case 'bar':
        echo $foo;
    default:
        break;
}

Closing Tag

Checks that the file does not end with a closing tag.

Valid: Closing tag not used. Invalid: Closing tag used.
<?php
echo 'Foo';
<?php
echo 'Foo';
?>

End File Newline

PHP Files should end with exactly one newline.

Function Call Signature

Checks that the function call format is correct.

Valid: Correct spacing is used around parentheses. Invalid: Incorrect spacing used, too much space around the parentheses.
foo($bar, $baz);
foo ( $bar, $baz );
Valid: Correct number of spaces used for indent in a multi-line function call. Invalid: Incorrect number of spaces used for indent in a multi-line function call.
foo(
    $bar,
    $baz
);
foo(
  $bar,
      $baz
);
Valid: Closing parenthesis for a multi-line function call is on a new line after the last parameter. Invalid: Closing parenthesis for a multi-line function call is not on a new line after the last parameter.
foo(
    $bar,
    $baz
);
foo(
    $bar,
    $baz);
Valid: The first argument of a multi-line function call is on a new line. Invalid: The first argument of a multi-line function call is not on a new line.
foo(
    $bar,
    $baz
);
foo($bar,
    $baz
);
Valid: Only one argument per line in a multi-line function call. Invalid: Two or more arguments per line in a multi-line function call.
foo(
    $bar,
    $baz
);
foo(
    $bar, $baz
);
Valid: No blank lines in a multi-line function call. Invalid: Blank line in multi-line function call.
foo(
    $bar,
    $baz
);
foo(
    $bar,

    $baz
);

Function Closing Brace

Checks that the closing brace of a function goes directly after the body.

Valid: Closing brace directly follows the function body. Invalid: Blank line between the function body and the closing brace.
function foo()
{
    echo 'foo';
}
function foo()
{
    echo 'foo';

}

Method Declarations

Method names should not be prefixed with an underscore to indicate visibility. The static keyword, when present, should come after the visibility declaration, and the final and abstract keywords should come before.

Valid: Correct method naming. Invalid: An underscore prefix used to indicate visibility.
class Foo
{
    private function bar()
    {
    }
}
class Foo
{
    private function _bar()
    {
    }
}
Valid: Correct ordering of method prefixes. Invalid: `static` keyword used before visibility and final used after.
class Foo
{
    final public static function bar()
    {
    }
}
class Foo
{
    static public final function bar()
    {
    }
}

Namespace Declaration

There must be one blank line after the namespace declaration.

Valid: One blank line after the namespace declaration. Invalid: No blank line after the namespace declaration.
namespace Foo\Bar;

use \Baz;
namespace Foo\Bar;
use \Baz;

Namespace Declarations

Each use declaration must contain only one namespace and must come after the first namespace declaration. There should be one blank line after the final use statement.

Valid: One use declaration per namespace. Invalid: Multiple namespaces in a use declaration.
use \Foo;
use \Bar;
use \Foo, \Bar;
Valid: Use statements come after first namespace. Invalid: Namespace declared after use.
namespace \Foo;

use \Bar;
use \Bar;

namespace \Foo;
Valid: A single blank line after the final use statement. Invalid: No blank line after the final use statement.
use \Foo;
use \Bar;

class Baz
{
}
use \Foo;
use \Bar;
class Baz
{
}

Class Instantiation

When instantiating a new class, parenthesis MUST always be present even when there are no arguments passed to the constructor.

Valid: Parenthesis used. Invalid: Parenthesis not used.
new Foo();
new Foo;

Closing Brace

The closing brace of object-oriented constructs and functions must not be followed by any comment or statement on the same line.

Valid: Closing brace is the last content on the line. Invalid: Comment or statement following the closing brace on the same line.
class Foo
{
    // Class content.
}

function bar()
{
    // Function content.
}
interface Foo2
{
    // Interface content.
} echo 'Hello!';

function bar()
{
    // Function content.
} //end bar()

Opening Brace Space

The opening brace of an object-oriented construct must not be followed by a blank line.

Valid: No blank lines after opening brace. Invalid: Blank line after opening brace.
class Foo
{
    public function bar()
    {
        // Method content.
    }
}
class Foo
{

    public function bar()
    {
        // Method content.
    }
}

Boolean Operator Placement

Boolean operators between conditions in control structures must always be at the beginning or at the end of the line, not a mix of both.

This rule applies to if/else conditions, while loops and switch/match statements.

Valid: Boolean operator between conditions consistently at the beginning of the line. Invalid: Mix of boolean operators at the beginning and the end of the line.
if (
    $expr1
    && $expr2
    && ($expr3
    || $expr4)
    && $expr5
) {
    // if body.
}
if (
    $expr1 &&
    ($expr2 || $expr3)
    && $expr4
) {
    // if body.
}
Valid: Boolean operator between conditions consistently at the end of the line. Invalid: Mix of boolean operators at the beginning and the end of the line.
if (
    $expr1 ||
    ($expr2 || $expr3) &&
    $expr4
) {
    // if body.
}
match (
    $expr1
    && $expr2 ||
    $expr3
) {
    // structure body.
};

Control Structure Spacing

Single line control structures must have no spaces after the condition opening parenthesis and before the condition closing parenthesis.

Valid: No space after the opening parenthesis in a single-line condition. Invalid: Space after the opening parenthesis in a single-line condition.
if ($expr) {
}
if ( $expr) {
}
Valid: No space before the closing parenthesis in a single-line condition. Invalid: Space before the closing parenthesis in a single-line condition.
if ($expr) {
}
if ($expr ) {
}
The condition of the multi-line control structure must be indented once, placing the first expression on the next line after the opening parenthesis.
Valid: First expression of a multi-line control structure condition block is on the line after the opening parenthesis. Invalid: First expression of a multi-line control structure condition block is on the same line as the opening parenthesis.
while (
    $expr1
    && $expr2
) {
}
while ($expr1
    && $expr2
) {
}
Valid: Each line in a multi-line control structure condition block indented at least once. Default indentation is 4 spaces. Invalid: Some lines in a multi-line control structure condition block not indented correctly.
while (
    $expr1
    && $expr2
) {
}
while (
$expr1
    && $expr2
  && $expr3
) {
}
The closing parenthesis of the multi-line control structure must be on the next line after the last condition, indented to the same level as the start of the control structure.
Valid: The closing parenthesis of a multi-line control structure condition block is on the line after the last expression. Invalid: The closing parenthesis of a multi-line control structure condition block is on the same line as the last expression.
while (
    $expr1
    && $expr2
) {
}
while (
    $expr1
    && $expr2) {
}
Valid: The closing parenthesis of a multi-line control structure condition block is indented to the same level as start of the control structure. Invalid: The closing parenthesis of a multi-line control structure condition block is not indented to the same level as start of the control structure.
while (
    $expr1
    && $expr2
) {
}
while (
    $expr1
    && $expr2
  ) {
}

Import Statement

Import use statements must not begin with a leading backslash.

Valid: Import statement doesn't begin with a leading backslash. Invalid: Import statement begins with a leading backslash.
<?php

use Vendor\Package\ClassA as A;

class FooBar extends A
{
    // Class content.
}
<?php

use \Vendor\Package\ClassA as A;

class FooBar extends A
{
    // Class content.
}

Open PHP Tag

When the opening <?php tag is on the first line of the file, it must be on its own line with no other statements unless it is a file containing markup outside of PHP opening and closing tags.

Valid: Opening PHP tag on a line by itself. Invalid: Opening PHP tag not on a line by itself.
<?php

echo 'hi';
<?php echo 'hi';
Valid: Opening PHP tag not on a line by itself, but has markup outside the closing PHP tag. Invalid: Opening PHP tag not on a line by itself without any markup in the file.
<?php declare(strict_types=1); ?>
<html>
<body>
    <?php
        // ... additional PHP code ...
    ?>
</body>
</html>
<?php declare(strict_types=1); ?>

Nullable Type Declarations Functions

In nullable type declarations there MUST NOT be a space between the question mark and the type.

Valid: No whitespace used. Invalid: Superfluous whitespace used.
public function functionName(
    ?string $arg1,
    ?int $arg2
): ?string {
}
public function functionName(
    ? string $arg1,
    ? int $arg2
): ? string {
}
Valid: No unexpected characters. Invalid: Unexpected characters used.
public function foo(?int $arg): ?string
{
}
public function bar(? /* comment */ int $arg): ?
    // nullable for a reason
    string
{
}

Return Type Declaration

For function and closure return type declarations, there must be one space after the colon followed by the type declaration, and no space before the colon.

The colon and the return type declaration have to be on the same line as the argument list closing parenthesis.

Valid: A single space between the colon and type in a return type declaration. Invalid: No space between the colon and the type in a return type declaration.
$closure = function ( $arg ): string {
   // Closure body.
};
$closure = function ( $arg ):string {
   // Closure body.
};
Valid: No space before the colon in a return type declaration. Invalid: One or more spaces before the colon in a return type declaration.
function someFunction( $arg ): string {
   // Function body.
};
function someFunction( $arg )   : string {
   // Function body.
};

Short Form Type Keywords

Short form of type keywords MUST be used i.e. bool instead of boolean, int instead of integer etc.

Valid: Short form type used. Invalid: Long form type type used.
$foo = (bool) $isValid;
$foo = (boolean) $isValid;

Compound Namespace Depth

Compound namespaces with a depth of more than two MUST NOT be used.

Valid: Max depth of 2. Invalid: Max depth of 3.
use Vendor\Package\SomeNamespace\{
    SubnamespaceOne\ClassA,
    SubnamespaceOne\ClassB,
    SubnamespaceTwo\ClassY,
    ClassZ,
};
use Vendor\Package\SomeNamespace\{
    SubnamespaceOne\AnotherNamespace\ClassA,
    SubnamespaceOne\ClassB,
    ClassZ,
};

Operator Spacing

All binary and ternary (but not unary) operators MUST be preceded and followed by at least one space. This includes all arithmetic, comparison, assignment, bitwise, logical (excluding ! which is unary), string concatenation, type operators, trait operators (insteadof and as), and the single pipe operator (e.g. ExceptionType1 | ExceptionType2 $e).

Valid: At least 1 space used. Invalid: No spacing used.
if ($a === $b) {
    $foo = $bar ?? $a ?? $b;
} elseif ($a > $b) {
    $variable = $foo ? 'foo' : 'bar';
}
if ($a===$b) {
    $foo=$bar??$a??$b;
} elseif ($a>$b) {
    $variable=$foo?'foo':'bar';
}

Constant Visibility

Visibility must be declared on all class constants if your project PHP minimum version supports constant visibilities (PHP 7.1 or later).

The term "class" refers to all classes, interfaces, enums and traits.

Valid: Constant visibility declared. Invalid: Constant visibility not declared.
class Foo
{
    private const BAR = 'bar';
}
class Foo
{
    const BAR = 'bar';
}

Valid Class Name

Class names must be written in Pascal case. This means that it starts with a capital letter, and the first letter of each word in the class name is capitalized. Only letters and numbers are allowed.

Valid: Class name starts with a capital letter. Invalid: Class name does not start with a capital letter.
class PascalCaseStandard
{
}
class notPascalCaseStandard
{
}
Valid: Class name contains only letters and numbers. Invalid: Class name contains underscores.
class PSR7Response
{
}
class PSR7_Response
{
}

Foreach Loop Declarations

There should be a space between each element of a foreach loop and the as keyword should be lowercase.

Valid: Correct spacing used. Invalid: Invalid spacing used.
foreach ($foo as $bar => $baz) {
    echo $baz;
}
foreach ( $foo  as  $bar=>$baz ) {
    echo $baz;
}
Valid: Lowercase as keyword. Invalid: Uppercase as keyword.
foreach ($foo as $bar => $baz) {
    echo $baz;
}
foreach ($foo AS $bar => $baz) {
    echo $baz;
}

For Loop Declarations

In a for loop declaration, there should be no space inside the brackets and there should be 0 spaces before and 1 space after semicolons.

Valid: Correct spacing used. Invalid: Invalid spacing used inside brackets.
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
for ( $i = 0; $i < 10; $i++ ) {
    echo $i;
}
Valid: Correct spacing used. Invalid: Invalid spacing used before semicolons.
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
for ($i = 0 ; $i < 10 ; $i++) {
    echo $i;
}
Valid: Correct spacing used. Invalid: Invalid spacing used after semicolons.
for ($i = 0; $i < 10; $i++) {
    echo $i;
}
for ($i = 0;$i < 10;$i++) {
    echo $i;
}

Lowercase Control Structure Keywords

The PHP keywords if, else, elseif, foreach, for, do, switch, while, try, and catch should be lowercase.

Valid: Lowercase if keyword. Invalid: Uppercase if keyword.
if ($foo) {
    $bar = true;
}
IF ($foo) {
    $bar = true;
}

Lowercase Function Keywords

The PHP keywords function, public, private, protected, and static should be lowercase.

Valid: Lowercase function keyword. Invalid: Uppercase function keyword.
function foo()
{
    return true;
}
FUNCTION foo()
{
    return true;
}

Cast Whitespace

Casts should not have whitespace inside the parentheses.

Valid: No spaces. Invalid: Whitespace used inside parentheses.
$foo = (int)'42';
$foo = ( int )'42';

Scope Closing Brace

Indentation of a closing brace must match the indentation of the line containing the opening brace.

Valid: Closing brace aligned with line containing opening brace. Invalid: Closing brace misaligned with line containing opening brace.
function foo()
{
}

if (!class_exists('Foo')) {
    class Foo {
    }
}

<?php if ($something) { ?>
    <span>some output</span>
<?php } ?>
function foo()
{
 }

if (!class_exists('Foo')) {
    class Foo {
}
    }

<?php if ($something) { ?>
    <span>some output</span>
 <?php } ?>
Closing brace must be on a line by itself.
Valid: Close brace on its own line. Invalid: Close brace on a line containing other code.
enum Foo {
}
enum Foo {}

Scope Keyword Spacing

The PHP keywords static, public, private, and protected should have one space after them.

Valid: A single space following the keywords. Invalid: Multiple spaces following the keywords.
public static function foo()
{
}
public  static  function foo()
{
}

Superfluous Whitespace

There should be no superfluous whitespace at the start of a file.

Valid: No whitespace preceding first content in file. Invalid: Whitespace used before content in file.
<?php
echo 'opening PHP tag at start of file';
<?php
echo 'whitespace before opening PHP tag';
There should be no trailing whitespace at the end of lines.
Valid: No whitespace found at end of line. Invalid: Whitespace found at end of line.
echo 'semicolon followed by new line char';
echo 'trailing spaces after semicolon';   
There should be no consecutive blank lines in functions.
Valid: Functions do not contain multiple empty lines in a row. Invalid: Functions contain multiple empty lines in a row.
function myFunction()
{
    echo 'code here';

    echo 'code here';
}
function myFunction()
{
    echo 'code here';
    

    echo 'code here';
}
There should be no superfluous whitespace after the final closing PHP tag in a file.
Valid: A single new line appears after the last content in the file. Invalid: Multiple new lines appear after the last content in the file.
function myFunction()
{
    echo 'Closing PHP tag, then';
    echo 'Single new line char, then EOF';
}

?>
function myFunction()
{
    echo 'Closing PHP tag, then';
    echo 'Multiple new line chars, then EOF';
}

?>

Documentation generated on Tue, 13 May 2025 12:44:47 +0000 by PHP_CodeSniffer 3.13.0