Skip to content

OffsetOperations ​

error off by default

Group: Probable bugs · PhpStorm name: OffsetOperationsInspection

Offset access $x[...] only works on arrays, strings and objects that implement offset handling. Using it on a boolean, number or a plain object is a bug (or a sign of missing type annotations); using an index whose type the container does not accept (an array as a key, an object as a key) is also flagged.

Disabled by default.

Example ​

php
<?php
class Registry {
    /** @param string $name */
    public function offsetGet($name) { return null; }
}
class Dyn {
    public function __set($k, $v) {}
}

function demo(array $rows, int $limit) {
    $title = 'abc';
    echo $title[1];
    $title[array_keys($rows)] = 'z';
    $title[] = 'x';

    $count = 10;
    $count[2] = 1;

    $reg = new Registry();
    echo $reg['db'];
    echo $reg[7];

    $dyn = new Dyn();
    $dyn[new ArrayObject()] = 1;

    $plain = new DateTime();
    $plain[] = 1;

    foreach ($rows as $k => $v) {
        echo $k[0];
    }
    $tail = substr('abc', 1);
    echo $tail[0];
}

/**
 * @param mixed $m
 * @param \Countable|array $c
 * @param null|array $n
 */
function ok($m, $c, $n) {
    return [$m['a'], $c['a'], $n['a']];
}

Reported:

  • line 13: Index of type array does not fit the accepted string|int.
  • line 17: '$count' does not support offset access (types: int).
  • line 21: Index of type int does not fit the accepted string.
  • line 24: Index of type \ArrayObject does not fit the accepted string|int.
  • line 27: '$plain' does not support offset access (types: \DateTime).

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore OffsetOperations

/**
 * @noinspection OffsetOperationsInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.