PHPCS: Generic

Personal documentation for the sniffs available in the PHPCS Generic Coding Standards to help build an own rulesets and search for error explanations.

Generic.Arrays.ArrayIndent | [ref]

Generic.Arrays.DisallowLongArraySyntax | [ref]

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',
);

Generic.Arrays.DisallowShortArraySyntax | [ref]

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',
];

Generic.Classes.DuplicateClassName | [ref]

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
{
}

Generic.Classes.OpeningBraceSameLine | [ref]

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.
}

Generic.CodeAnalysis.AssignmentInCondition | [ref]

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.
}

Generic.CodeAnalysis.EmptyPHPStatement | [ref]

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 ; ?>
<?=  ?>
Valid: There is no superfluous semi-colon after a PHP statement. Invalid: There are one or more superfluous semi-colons after a PHP statement.
function_call();
if (true) {
    echo 'Hello World';
}
function_call();;;
if (true) {
    echo 'Hello World';
};

Generic.CodeAnalysis.EmptyStatement | [ref]

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
}

Generic.CodeAnalysis.ForLoopShouldBeWhileLoop | [ref]

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();
}

Generic.CodeAnalysis.ForLoopWithTestFunctionCall | [ref]

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";
}

Generic.CodeAnalysis.JumbledIncrementer | [ref]

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++) {
    }
}

Generic.CodeAnalysis.UnconditionalIfStatement | [ref]

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;
}

Generic.CodeAnalysis.UnnecessaryFinalModifier | [ref]

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()
    {
    }
}

Generic.CodeAnalysis.UnusedFunctionParameter | [ref]

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;
}

Generic.CodeAnalysis.UselessOverridingMethod | [ref]

Methods should not be defined that only call the parent method.

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

Generic.Commenting.DocComment | [ref]

Generic.Commenting.Fixme | [ref]

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;
}

Generic.Commenting.Todo | [ref]

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;
}

Generic.ControlStructures.DisallowYodaConditions | [ref]

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;
}

Generic.ControlStructures.InlineControlStructure | [ref]

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;

Generic.Debug.ClosureLinter | [ref]

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,];

Generic.Debug.CSSLint | [ref]

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 %; }

Generic.Debug.ESLint | [ref]

Generic.Debug.JSHint | [ref]

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;

Generic.Files.ByteOrderMark | [ref]

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).

Generic.Files.EndFileNewline | [ref]

Files should end with a newline character.

Generic.Files.EndFileNoNewline | [ref]

Files should not end with a newline character.

Generic.Files.ExecutableFile | [ref]

Files should not be executable.

Generic.Files.InlineHTML | [ref]

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';

Generic.Files.LineEndings | [ref]

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

Generic.Files.LineLength | [ref]

It is recommended to keep lines at approximately 80 characters long for better code readability.

Generic.Files.LowercasedFilename | [ref]

Lowercase filenames are required.

Generic.Files.OneClassPerFile | [ref]

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
{
}

Generic.Files.OneInterfacePerFile | [ref]

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
{
}

Generic.Files.OneObjectStructurePerFile | [ref]

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
{
}

Generic.Files.OneTraitPerFile | [ref]

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
{
}

Generic.Formatting.DisallowMultipleStatements | [ref]

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;

Generic.Formatting.MultipleStatementAlignment | [ref]

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.

Equals signs aligned Not aligned; harder to read
$shortVar        = (1 + 2);
$veryLongVarName = 'string';
$var             = foo($bar, $baz);
$shortVar = (1 + 2);
$veryLongVarName = 'string';
$var = foo($bar, $baz);
Equals signs aligned; only one space after longest var name Two spaces after longest var name
$shortVar       += 1;
$veryLongVarName = 1;
$shortVar        += 1;
$veryLongVarName  = 1;
Equals signs aligned Equals signs not aligned
$shortVar         = 1;
$veryLongVarName -= 1;
$shortVar        = 1;
$veryLongVarName -= 1;

Generic.Formatting.NoSpaceAfterCast | [ref]

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;

Generic.Formatting.SpaceAfterCast | [ref]

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;

Generic.Formatting.SpaceAfterNot | [ref]

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) {};

Generic.Formatting.SpaceBeforeCast | [ref]

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;

Generic.Functions.CallTimePassByReference | [ref]

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);

Generic.Functions.FunctionCallArgumentSpacing | [ref]

Function arguments should have one space after a comma, and single spaces surrounding the equals sign for default values.

Valid: Single spaces after a comma. Invalid: No spaces after a comma.
function foo($bar, $baz)
{
}
function foo($bar,$baz)
{
}
Valid: Single spaces around an equals sign in function declaration. Invalid: No spaces around an equals sign in function declaration.
function foo($bar, $baz = true)
{
}
function foo($bar, $baz=true)
{
}

Generic.Functions.OpeningFunctionBraceBsdAllman | [ref]

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

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

Generic.Functions.OpeningFunctionBraceKernighanRitchie | [ref]

Function declarations follow the "Kernighan/Ritchie style". The function brace is on the same line as the function declaration. One space is required between the closing parenthesis and the brace.

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

Generic.Metrics.CyclomaticComplexity | [ref]

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

Generic.Metrics.NestingLevel | [ref]

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

Generic.NamingConventions.AbstractClassNamePrefix | [ref]

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

Valid: Invalid:
abstract class AbstractBar
{
}
abstract class Bar
{
}

Generic.NamingConventions.CamelCapsFunctionName | [ref]

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()
{
}

Generic.NamingConventions.ConstructorName | [ref]

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()
    {
    }
}

Generic.NamingConventions.InterfaceNameSuffix | [ref]

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

Valid: Invalid:
interface BarInterface
{
}
interface Bar
{
}

Generic.NamingConventions.TraitNameSuffix | [ref]

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

Valid: Invalid:
trait BarTrait
{
}
trait Bar
{
}

Generic.NamingConventions.UpperCaseConstantName | [ref]

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

Valid: all uppercase Invalid: mixed case
define('FOO_CONSTANT', 'foo');

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

class FooClass
{
    const foo_constant = 'foo';
}

Generic.PHP.BacktickOperator | [ref]

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

Generic.PHP.CharacterBeforePHPOpeningTag | [ref]

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';

Generic.PHP.ClosingPHPTag | [ref]

All opening php tags should have a corresponding closing tag.

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

Generic.PHP.DeprecatedFunctions | [ref]

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);

Generic.PHP.DisallowAlternativePHPTags | [ref]

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.

Generic.PHP.DisallowRequestSuperglobal | [ref]

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

Generic.PHP.DisallowShortOpenTag | [ref]

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.

Generic.PHP.DiscourageGoto | [ref]

Discourage the use of the PHP goto language construct.

Generic.PHP.ForbiddenFunctions | [ref]

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);

Generic.PHP.LowerCaseConstant | [ref]

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;
}

Generic.PHP.LowerCaseKeyword | [ref]

All PHP keywords should be lowercase.

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

Generic.PHP.LowerCaseType | [ref]

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 {
}
Valid: Lowercase type used. Invalid: Non-lowercase type used.
$foo = (bool) $isValid;
$foo = (BOOL) $isValid;

Generic.PHP.NoSilencedErrors | [ref]

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";
}

Generic.PHP.RequireStrictTypes | [ref]

Generic.PHP.SAPIUsage | [ref]

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

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

Generic.PHP.Syntax | [ref]

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.

Generic.PHP.UpperCaseConstant | [ref]

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;
}

Generic.Strings.UnnecessaryStringConcat | [ref]

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';

Generic.VersionControl.GitMergeConflict | [ref]

Generic.VersionControl.SubversionProperties | [ref]

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'.

Generic.WhiteSpace.ArbitraryParenthesesSpacing | [ref]

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
);

Generic.WhiteSpace.DisallowSpaceIndent | [ref]

Tabs should be used for indentation instead of spaces.

Generic.WhiteSpace.DisallowTabIndent | [ref]

Spaces should be used for indentation instead of tabs.

Generic.WhiteSpace.IncrementDecrementSpacing | [ref]

Generic.WhiteSpace.LanguageConstructSpacing | [ref]

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;
Valid: Single space between yield and from. Invalid: No space, more than one space or newline between yield and from.
yield from [1, 2, 3];
yieldfrom [1, 2, 3];
yield  from [1, 2, 3];
yield
from [1, 2, 3];

Generic.WhiteSpace.ScopeIndent | [ref]

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;
}

Generic.WhiteSpace.SpreadOperatorSpacingAfter | [ref]

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 ],.../*comment*/array_values($keyedArray)
    );
}
avatar

Looking for a developer who
truly cares about your business?

My team and I provide expert consultations, top-notch coding, and comprehensive audits to elevate your success.

Feedback

How satisfied you are after reading this article?