Skip to content

DocumentedOperandType ​

warning native off by default PHP ≥ 8.0

Group: Probable bugs

Report an arithmetic or bitwise operation on an array or an object when PHPDoc says the operand cannot take part in it. The code may hold a number at run time, since PHP does not check PHPDoc, but the operation and the documentation disagree. Operands the code alone proves wrong are InvalidOperandType's.

Example ​

php
<?php
/** @param int[] $counts */
function bump($counts): int
{
    return $counts * 2;
}

Reported:

  • line 5: Use a number here, not int[].

Detection ​

  • An operand of +, -, *, /, %, **, &, |, ^, << or >>, or of the compound assignment of one of them.
  • The types of both operands are the ones PHPDoc-aware inference gives: @param, @var, @return and @property tags count.
  • Every member of the operand's type is an array, or every member of it is a class whose whole hierarchy is known.

Exceptions (no report) ​

  • Operands InvalidOperandType reports.
  • + between arrays, which merges them: an array operand of + is reported only when the other operand is known and cannot be an array.
  • An operand that may also be null, a scalar or an unresolved class.
  • An object of a class that takes part in arithmetic: GMP, BcMath\Number, FFI\CData, SimpleXMLElement and their subclasses.
  • An operand whose PHPDoc type the code contradicts: when the code alone gives the operand a type that no value of the PHPDoc type fits (/** @var int $x */ over $x = new Order()), the tag is stale.
  • $this inside a closure or an arrow function, which may be bound to an object of another class.

Fix ​

None: either the operation or the documentation is wrong.

PHP versions ​

Active from PHP 8.0, where these operations throw a TypeError.

Configure ​

In custos.json:

json
{
  "rules": {
    "DocumentedOperandType": {
      "enabled": true
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file):

php
// @custos-ignore DocumentedOperandType

Released under the MIT License. Native rules and rules modeled on Php Inspections (EA Extended); independent clean-room implementation.