Skip to content

Latest commit

 

History

History
2354 lines (1692 loc) · 35.5 KB

checkers_doc.md

File metadata and controls

2354 lines (1692 loc) · 35.5 KB

Checkers

Brief statistics

Total checks Checks enabled by default Disabled checks by default Autofixable checks
103 85 18 13

Table of contents

Enabled

accessLevel checker

Description

Report erroneous member access.

Non-compliant code:

$x->privateMethod(); // privateMethod is private and can't be accessed.

Compliant code:

$x->publicMethod();


alwaysNull checker

Description

Report when use to always null object.

Non-compliant code:

if ($obj == null && $obj->method()) { ... }

Compliant code:

if ($obj != null && $obj->method()) { ... }


argCount checker

Description

Report mismatching args count inside call expressions.

Non-compliant code:

array_combine($keys) // The function takes at least two arguments.

Compliant code:

array_combine($keys, $values)


argsOrder checker

Description

Report suspicious arguments order.

Non-compliant code:

// It is possible that the arguments are in the wrong order, since 
// searching for a substring in a character does not make sense.
strpos('/', $s);

Compliant code:

strpos($s, '/');


arraySyntax checker

Auto fix available

Description

Report usages of old array() syntax.

Non-compliant code:

array(1, 2)

Compliant code:

[1, 2]


assignOp checker

Auto fix available

Description

Report assignments that can be simplified.

Non-compliant code:

$x = $x + $y;

Compliant code:

$x += $y;


badTraitUse checker

Description

Report misuse of traits.

Non-compliant code:

trait A {}
function f(A $a) {} // Traits cannot be used as type hints.

Compliant code:

class A {}
function f(A $a) {}


bareTry checker

Description

Report try blocks without catch/finally.

Non-compliant code:

try {
  doit();
}
// Missing catch or finally blocks.

Compliant code:

try {
  doit();
} catch (Exception $e) {
  // Handle $e.
}


bitwiseOps checker

Auto fix available

Description

Report suspicious usage of bitwise operations.

Non-compliant code:

if ($isURL & $verify) { ... } // Bitwise AND on two bool looks suspicious,

Compliant code:

if ($isURL && $verify) { ... }


callSimplify checker

Auto fix available

Description

Report call expressions that can be simplified.

Non-compliant code:

in_array($k, array_keys($this->data))

Compliant code:

array_key_exists($k, $this->data)


callStatic checker

Description

Report static calls of instance methods and vice versa.

Non-compliant code:

$object::instance_method() // instance_method is not a static method.

Compliant code:

$object->instance_method()


caseBreak checker

Description

Report switch cases without break.

Non-compliant code:

switch ($v) {
case 1:
  echo "one"; // May want to insert a "break" here.
case 2:
  echo "this fallthrough is intentional";
  // fallthrough
case 3:
  echo "two or three";
}

Compliant code:

switch ($v) {
case 1:
  echo "one";
  break;
case 2:
  echo "this fallthrough is intentional";
  // fallthrough
case 3:
  echo "two or three";
}


caseContinue checker

Description

Report suspicious continue usages inside switch cases.

Non-compliant code:

switch ($v) {
case STOP:
  continue; // Continue inside a switch is equivalent to break.
case INC:
  $x++;
  break;
}

Compliant code:

switch ($v) {
case STOP:
  break;
case INC:
  $x++;
  break;
}


catchOrder checker

Description

Report erroneous catch order in try statements.

Non-compliant code:

try {
  // Some code.
} catch (Exception $e) {
  // This will catch both Exception and TimeoutException.
} catch (TimeoutException $e) {
  // This is a dead code.
}

Compliant code:

try {
  // Some code.
} catch (TimeoutException $e) {
  // Ok, it can catch TimeoutException.
} catch (Exception $e) {
  // Ok, it will catch everything else.
}


concatenationPrecedence checker

Description

Report when use unparenthesized expression containing both . and binary operator.

Non-compliant code:

"id: " . $id - 10

Compliant code:

"id: " . ($id - 10)


constCase checker

Auto fix available

Description

Report built-in constants that are not in the lower case.

Non-compliant code:

return TRUE;

Compliant code:

return true;


countUse checker

Auto fix available

Description

Report comparisons count(...) which are always false or true.

Non-compliant code:

if (count($arr) >= 0) { ... }

Compliant code:

if (count($arr) != 0) { ... }


deadCode checker

Description

Report potentially unreachable code.

Non-compliant code:

thisFunctionAlwaysExits();
foo(); // Dead code.

Compliant code:

foo();
thisFunctionAlwaysExits();


deprecated checker

Description

Report usages of deprecated symbols.

Non-compliant code:

/**
 * @deprecated Use g() instead
 */
function f() {}

f();

Compliant code:

/**
 * @deprecated Use g() instead
 */
function f() {}

g();


discardExpr checker

Description

Report expressions that are evaluated but not used.

Non-compliant code:

if ($cond) {
  [$v, $err]; // Result expression is not used anywhere.
}

Compliant code:

if ($cond) {
  return [$v, $err];
}


discardVar checker

Description

Report the use of variables that were supposed to be unused, like $_.

Non-compliant code:

$_ = some();
echo $_;

Compliant code:

$someVal = some();
echo $someVal;


dupArrayKeys checker

Description

Report duplicated keys in array literals.

Non-compliant code:

[A => 1, B => 2, A => 3] // Key A is duplicated.

Compliant code:

[A => 1, B => 2, C => 3]


dupBranchBody checker

Description

Report suspicious conditional branches that execute the same action.

Non-compliant code:

// Regardless of the condition, the result will always be the same.
$pickLeft ? foo($left) : foo($left)

Compliant code:

$pickLeft ? foo($left) : foo($right)


dupCatch checker

Description

Report duplicated catch clauses.

Non-compliant code:

try {
  // some code
} catch (Exception1 $e) {
} catch (Exception1 $e) {} // <- Possibly the typo.

Compliant code:

try {
  // some code
} catch (Exception1 $e) {
} catch (Exception2 $e) {}


dupCond checker

Description

Report duplicated conditions in switch and if/else statements.

Non-compliant code:

if ($status == OK) {
  return "OK";
} elseif ($status == OK) { // Duplicated condition.
  return "NOT OK";
} else {
  return "UNKNOWN";
}

Compliant code:

if ($status == OK) {
  return "OK";
} elseif ($status == NOT_OK) {
  return "NOT OK";
} else {
  return "UNKNOWN";
}


dupGlobal checker

Description

Report repeated global statements over variables.

Non-compliant code:

global $x, $y, $x; // $x was already mentioned in global.

Compliant code:

global $x, $y;


dupSubExpr checker

Description

Report suspicious duplicated operands in expressions.

Non-compliant code:

return $x[$i] < $x[$i]; // The left and right expressions are the same.

Compliant code:

return $x[$i] < $x[$j];


emptyStmt checker

Description

Report redundant empty statements that can be safely removed.

Non-compliant code:

echo $foo;; // Second semicolon is unnecessary here.

Compliant code:

echo $foo;


emptyStringCheck checker

Description

Report string emptyness checking using strlen(...).

Non-compliant code:

if (strlen($string)) { ... }

Compliant code:

if ($string !== "") { ... }


forLoop checker

Description

Report potentially erroneous for loops.

Non-compliant code:

for ($i = 0; $i < 100; $i--) { ... }

Compliant code:

for ($i = 0; $i < 100; $i++) { ... }


implicitModifiers checker

Description

Report implicit modifiers.

Non-compliant code:

class Foo {
  function f() {} // The access modifier is implicit.
}

Compliant code:

class Foo {
  public function f() {}
}


indexingSyntax checker

Auto fix available

Description

Report the use of curly braces for indexing.

Non-compliant code:

$x{0}

Compliant code:

$x[0]


intNeedle checker

Description

Report using an integer for $needle argument of str* functions.

Non-compliant code:

strpos("hello", 10)

Compliant code:

strpos("hello", chr(10))


intOverflow checker

Description

Report potential integer overflows that may result in unexpected behavior.

Non-compliant code:

// Better to use a constant to avoid accidental overflow and float conversion.
return -9223372036854775808;

Compliant code:

return PHP_INT_MIN;


invalidDocblock checker

Description

Report malformed PHPDoc comments.

Non-compliant code:

@property $foo // Property type is missing.

Compliant code:

@property Foo $foo


invalidDocblockRef checker

Description

Report invalid symbol references inside PHPDoc.

Non-compliant code:

@see MyClass

Compliant code:

@see \Foo\MyClass


invalidDocblockType checker

Description

Report potential issues in PHPDoc types.

Non-compliant code:

@var []int $xs

Compliant code:

@var int[] $xs


invalidExtendClass checker

Description

Report inheritance from the final class.

Non-compliant code:

final class Foo {}
class Boo extends Foo {}

Compliant code:

class Foo {}
class Boo extends Foo {}


invalidNew checker

Description

Report trait or interface usages in new expressions.

Non-compliant code:

// It is forbidden to create instances of traits or interfaces.
return new SomeTrait();

Compliant code:

return new SomeClass();


keywordCase checker

Description

Report keywords that are not in the lower case.

Non-compliant code:

RETURN $x;

Compliant code:

return $x;


linterError checker

Description

Report internal linter error.


magicMethodDecl checker

Description

Report issues in magic method declarations.

Non-compliant code:

class Foo {
  private function __call($method, $args) {} // The magic method __call() must have public visibility.
  public static function __set($name, $value) {} // The magic method __set() cannot be static.
}

Compliant code:

class Foo {
  public function __call($method, $args) {}
  public function __set($name, $value) {}
}


maybeUndefined checker

Description

Report usages of potentially undefined symbols.

Non-compliant code:

if ($cond) {
  $v = 10;
}
return $v; // $v may be undefined.

Compliant code:

$v = 0; // Default value.
if ($cond) {
  $v = 10;
}
return $v;


methodSignatureMismatch checker

Description

Report a method signature mismatch in inheritance.

Non-compliant code:

class Foo {
  final public function f() {}
}

class Boo extends Foo {
  public function f() {} // Foo::f is final.
}

Compliant code:

class Foo {
  public function f() {}
}

class Boo extends Foo {
  public function f() {}
}


misspellComment checker

Description

Report commonly misspelled words in comments.

Non-compliant code:

/** This is our performace test. */
function performance_test() {}

Compliant code:

/** This is our performance test. */
function performance_test() {}


misspellName checker

Description

Report commonly misspelled words in symbol names.

Non-compliant code:

function performace_test() ...

Compliant code:

function performance_test() ...


mixedArrayKeys checker

Description

Report array literals that have both implicit and explicit keys.

Non-compliant code:

['a', 5 => 'b'] // Both explicit and implicit keys are used.

Compliant code:

[0 => 'a', 5 => 'b']


nameMismatch checker

Description

Report symbol case mismatches.

Non-compliant code:

class Foo {}
// The spelling is in lower case, although the class definition begins with an uppercase letter.
$foo = new foo();

Compliant code:

class Foo {}
$foo = new Foo();


nestedTernary checker

Description

Report an unspecified order in a nested ternary operator.

Non-compliant code:

$_ = 1 ? 2 : 3 ? 4 : 5; // There is no clear order of execution.

Compliant code:

$_ = (1 ? 2 : 3) ? 4 : 5;
// or
$_ = 1 ? 2 : (3 ? 4 : 5);


newAbstract checker

Description

Report abstract classes usages in new expressions.

Non-compliant code:

// It is forbidden to create instances of abstract classes.
return new AbstractFactory();

Compliant code:

return new NonAbstractFactory();


nonPublicInterfaceMember checker

Description

Report illegal non-public access level in interfaces.

Non-compliant code:

interface Iface {
  function a();
  public function b();
  private function c(); // Methods in an interface cannot be private.
  protected function d(); // Methods in an interface cannot be protected.
}

Compliant code:

interface Iface {
  function a();
  public function b();
  public function c();
  public function d();
}


offBy1 checker

Auto fix available

Description

Report potential off-by-one mistakes.

Non-compliant code:

$a[count($a)]

Compliant code:

$a[count($a)-1]


oldStyleConstructor checker

Description

Report old-style (PHP4) class constructors.

Non-compliant code:

class Foo {
  // Constructor in the old style of PHP 4.
  public function Foo($v) { $this->v = $v; }
}

Compliant code:

class Foo {
  public function __construct($v) { $this->v = $v; }
}


paramClobber checker

Description

Report assignments that overwrite params prior to their usage.

Non-compliant code:

function api_get_video($user_id) {
  // The arguments are assigned a new value before using the value passed to the function.
  $user_id = 0;
  return get_video($user_id);
}

Compliant code:

function api_get_video($user_id) {
  $user_id = $user_id ?: 0;
  return get_video($user_id);
}


parentConstructor checker

Description

Report missing parent::__construct calls in class constructors.

Non-compliant code:

class Foo extends Bar {
  public function __construct($x, $y) {
    // Lost call to parent constructor.
    $this->y = $y;
  }
}

Compliant code:

class Foo extends Bar {
  public function __construct($x, $y) {
    parent::__construct($x);
    $this->y = $y;
  }
}


precedence checker

Description

Report potential operation precedence issues.

Non-compliant code:

$x & $mask == 0; // == has higher precedence than &

Compliant code:

($x & $mask) == 0


printf checker

Description

Report issues in printf-like function calls.

Non-compliant code:

sprintf("id=%d") // Lost argument for '%d' specifier.

Compliant code:

sprintf("id=%d", $id)


redundantGlobal checker

Description

Report global statement over superglobal variables (which is redundant).

Non-compliant code:

global $Foo, $_GET; // $_GET is superglobal.

Compliant code:

global $Foo;


regexpSimplify checker

Description

Report regular expressions that can be simplified.

Non-compliant code:

preg_match('/x(?:a|b|c){0,}/', $s) // The regex can be simplified.

Compliant code:

preg_match('/x[abc]*/', $s)


regexpSyntax checker

Description

Report regexp syntax errors.


regexpVet checker

Description

Report suspicious regexp patterns.

Non-compliant code:

preg_match('a\d+a', $s); // 'a' is not a valid delimiter.

Compliant code:

preg_match('/\d+/', $s);


reverseAssign checker

Description

Report a reverse assign with unary plus or minus.

Non-compliant code:

$a =+ 100;

Compliant code:

$a += 100;


selfAssign checker

Description

Report self-assignment of variables.

Non-compliant code:

$x = $x;

Compliant code:

$x = $y;


stdInterface checker

Description

Report issues related to std PHP interfaces.


strangeCast checker

Description

Report a strange way of type cast.

Non-compliant code:

$x.""

Compliant code:

(string)$x


strictCmp checker

Description

Report not-strict-enough comparisons.

Non-compliant code:

in_array("what", $s)

Compliant code:

in_array("what", $s, true)


stripTags checker

Description

Report invalid strip_tags function usage.

Non-compliant code:

$s = strip_tags($s, '<br/>') // Error, self-closing tags are ignored. 

Compliant code:

$s = strip_tags($s, '<br>')


switchEmpty checker

Description

Report switch with empty body.

Non-compliant code:

switch ($a) {}

Compliant code:

switch ($a) {
  case 1:
    // do something
    break;
}


switchSimplify checker

Description

Report possibility to rewrite switch with the if.

Non-compliant code:

switch ($a) {
  case 1:
    echo 1;
    break;
}

Compliant code:

if ($a == 1) {
  echo 1;
}


syntax checker

Description

Report syntax errors.

Non-compliant code:

foo(1]

Compliant code:

foo(1)


ternarySimplify checker

Auto fix available

Description

Report ternary expressions that can be simplified.

Non-compliant code:

$x ? $x : $y

Compliant code:

$x ?: $y


unaryRepeat checker

Auto fix available

Description

Report the repetition of unary (! or ~) operators in a row.

Non-compliant code:

echo !!$a;

Compliant code:

echo (bool) $a;


undefinedClass checker

Description

Report usages of undefined class or interface.

Non-compliant code:

$foo = new UndefinedClass;

Compliant code:

$foo = new DefinedClass;


undefinedConstant checker

Description

Report usages of undefined constant.

Non-compliant code:

echo PI;

Compliant code:

echo M_PI;


undefinedFunction checker

Description

Report usages of undefined function.

Non-compliant code:

undefinedFunc();

Compliant code:

definedFunc();


undefinedMethod checker

Description

Report usages of undefined method.

Non-compliant code:

class Foo {
  public function method() {};
}

(new Foo)->method2(); // method2 is undefined.

Compliant code:

class Foo {
  public function method() {}
}

(new Foo)->method();


undefinedProperty checker

Description

Report usages of undefined property.

Non-compliant code:

class Foo {
  public string $prop;
}

(new Foo)->prop2; // prop2 is undefined.

Compliant code:

class Foo {
  public string $prop;
}

(new Foo)->prop;


undefinedTrait checker

Description

Report usages of undefined trait.

Non-compliant code:

class Foo {
  use UndefinedTrait;
}

Compliant code:

class Foo {
  use DefinedTrait;
}


undefinedVariable checker

Description

Report usages of undefined variable.

Non-compliant code:

echo $undefinedVar;

Compliant code:

$definedVar = 100;
echo $definedVar;


unimplemented checker

Description

Report classes that don't implement their contract.

Non-compliant code:

class MyObj implements Serializable {
  public function serialize() { /* ... */ }
  // Lost implementation of the unserialize method.
}

Compliant code:

class MyObj implements Serializable {
  public function serialize() { /* ... */ }
  public function unserialize(string $s) { /* ... */ }
}


unused checker

Description

Report potentially unused variables.

Non-compliant code:

$result = calculateResult(); // Unused $result.
return [$err];

Compliant code:

$result = calculateResult();
return [$result, $err];


useEval checker

Description

Report using eval function.

Non-compliant code:

eval("2 + 2");

Compliant code:

// no eval


useExitOrDie checker

Description

Report using exit or die functions.

Non-compliant code:

exit(1);

Compliant code:

// no exit


useSleep checker

Description

Report using sleep function.

Non-compliant code:

sleep(10);

Compliant code:

// no sleep


varShadow checker

Description

Report the shadow of an existing variable.

Non-compliant code:

function f(int $a) {
  // The $a variable hides the $a argument.
  foreach ([1, 2] as $a) {
    echo $a;
  }
}

Compliant code:

function f(int $a) {
  foreach ([1, 2] as $b) {
    echo $b;
  }
}


Disabled

argsReverse checker

Description

Report using variables as arguments in reverse order.

Non-compliant code:

function makeHello(string $name, int $age) {
  echo "Hello ${$name}-${$age}";
}

function main(): void {
  $name = "John";
  $age = 18;
  makeHello($age, $name); // The name should come first, and then the age.
}

Compliant code:

function makeHello(string $name, int $age) {
  echo "Hello ${$name}-${$age}";
}

function main(): void {
  $name = "John";
  $age = 18;
  makeHello($name, $age);
}


arrayAccess checker

Description

Report array access to non-array objects.

Non-compliant code:

return $foo[0]; // $foo value may not implement ArrayAccess

Compliant code:

if ($foo instanceof ArrayAccess) { 
  return $foo[0];
}


classMembersOrder checker

Description

Report the wrong order of the class members.

Non-compliant code:

class A {
  // In the class, constants and properties should go first, and then methods.
  public function func() {}
  const B = 1;
  public $c = 2;
}

Compliant code:

class A {
  const B = 1;
  public $c = 2;
  public function func() {}
}


complexity checker

Description

Report funcs/methods that are too complex.

Non-compliant code:

function checkRights() {
  // Super big function.
}

Compliant code:

function checkRights() {
  return true; // Or 42 if you need int-typed result.
}


deprecatedUntagged checker

Description

Report usages of deprecated symbols if the @deprecated tag has no description (see deprecated check).

Non-compliant code:

/**
 * @deprecated
 */
function f() {}

f();

Compliant code:

/**
 * @deprecated
 */
function f() {}

g();


errorSilence checker

Description

Report using @.

Non-compliant code:

@f();

Compliant code:

f();


getTypeMisUse checker

Auto fix available

Description

Report call gettype function.

Non-compliant code:

if (gettype($a) == "string") { ... }

Compliant code:

if (is_string($a)) { ... }


langDeprecated checker

Description

Report the use of deprecated (per language spec) features.

Non-compliant code:

$a = (real)100; // 'real' has been deprecated.
$_ = is_real($a);

Compliant code:

$a = (float)100;
$_ = is_float($a);


missingPhpdoc checker

Description

Report missing PHPDoc on public methods.

Non-compliant code:

public function process($acts, $config) {
  // Does something very complicated.
}

Compliant code:

/**
 * Process executes all $acts in a new context.
 * Processed $acts should never be processed again.
 *
 * @param Act[] $acts - acts to execute
 * @param array $config - options
 */
public function process($acts, $config) {
  // Does something very complicated.
}


packaging checker

Description

Report call @internal method outside @package.

Non-compliant code:

// file Boo.php 

namespace BooPackage; 

/** 
 * @package BooPackage 
 * @internal 
 */ 
class Boo { 
  public static function b() {} 
} 

// file Foo.php 

namespace FooPackage;

/** 
 * @package FooPackage 
 */ 
class Foo { 
  public static function f() {}

  /**
   * @internal
   */
  public static function fInternal() {}
}

// file Main.php

namespace Main;

use BooPackage\Boo;
use FooPackage\Foo;

class Main {
  public static function main(): void {
    Foo::f(); // ok, call non-internal method outside FooPackage

    Boo::b(); // error, call internal method inside other package
    Foo::fInternal(); // error, call internal method inside other package
  }
}

Compliant code:

// file Boo.php 

namespace BooPackage; 

/** 
 * @package BooPackage 
 * @internal 
 */ 
class Boo { 
  public static function b() {} 
} 

// file Foo.php 

namespace BooPackage;

/** 
 * @package BooPackage 
 */ 
class Foo { 
  public static function f() {}

  /**
   * @internal
   */
  public static function fInternal() {}
}

// file Main.php

namespace BooPackage;

/**
 * @package BooPackage
 */
class Main {
  public static function main(): void {
    Foo::f(); // ok, call internal method inside same package

    Boo::b(); // ok, call internal method inside same package
    Foo::fInternal(); // ok, call internal method inside same package
  }
}


parentNotFound checker

Description

Report using parent:: in a class without a parent class.

Non-compliant code:

class Foo {
  public function f() {
    parent::b(); // Class Foo has no parent.
  }
}

Compliant code:

class Foo extends Boo {
  public function f() {
    parent::b(); // Ok.
  }
}


propNullDefault checker

Auto fix available

Description

Report a null assignment for a not nullable property.

Non-compliant code:

class Foo {
  /**
   * @var Boo $item
   */
  public $item = null; // The type of the property is not nullable, but it is assigned null.
}

Compliant code:

class Foo {
  /**
   * @var Boo $item
   */
  public $item;
}


redundantCast checker

Description

Report redundant type casts.

Non-compliant code:

return (int)10; // The expression is already of type int.

Compliant code:

return 10;


returnAssign checker

Description

Report the use of assignment in the return statement.

Non-compliant code:

return $a = 100;

Compliant code:

return $a;


switchDefault checker

Description

Report the lack or wrong position of default.

Non-compliant code:

switch ($a) {
  case 1:
    echo 1;
    break;
}

Compliant code:

switch ($a) {
  case 1:
    echo 1;
    break;
  default:
    echo 2;
    break;
}


trailingComma checker

Auto fix available

Description

Report the absence of a comma for the last element in a multi-line array.

Non-compliant code:

$_ = [
  10,
  20 // Lost comma at the end for a multi-line array.
]

Compliant code:

$_ = [
  10,
  20,
]


typeHint checker

Description

Report misuse of type hints.

Non-compliant code:

// The array typehint is too generic, you need to specify a specialization or mixed[] in PHPDoc.
function f(array $a) {}

Compliant code:

/**
 * @param mixed[] $a
 */
function f(array $a) {}


voidResultUsed checker

Description

Report usages of the void-type expressions

Non-compliant code:

$x = var_dump($v); // var_dump returns void.

Compliant code:

$x = print_r($v, true);