Skip to content

DocumentedPropertyAssignment ​

warning native off by default

Group: Probable bugs

Report a value stored in a property that breaks the property's contract when PHPDoc is taken into account: the @var type of the property rejects it, or the declared type rejects a value whose type only PHPDoc describes. PHP may run such an assignment, but the code and its documentation disagree. Mismatches the code alone proves are InvalidPropertyAssignment's.

Example ​

php
<?php
final class Session
{
    /** @var string */
    public $token = '';

    public function close()
    {
        $this->token = null;
    }
}

Reported:

  • line 9: Assign string to Session::$token, not null.

Detection ​

  • Writes (assignments, by-reference assignments of a local, destructuring, foreach keys and values, ++ and --), stored values and property resolution as InvalidPropertyAssignment defines them: the written class still comes from native declarations only.
  • The type of the value is the one PHPDoc-aware inference gives: @param, @var and @return tags count.
  • Every declaration the write may reach rejects every value of the stored type, through the declared type of the property or its @var type.
  • The weak-mode conversions and the exceptions of InvalidPropertyAssignment apply alike, except that an untyped property with a @var type is checked.
  • D5. Integer ranges, non-empty strings and literal string values ('eur'|'usd') of a @var type count only against a value whose possible values are all known (an integer or string literal such as 0 or 'gbp'); otherwise @var positive-int accepts any integer and @var 'eur'|'usd' any string.

Exceptions (no report) ​

  • Assignments InvalidPropertyAssignment reports: the declared types reject what the code alone shows.
  • A @var type naming templates, and a @var type the declared type rejects (a stale tag).
  • The other value details of a @var type: string lengths other than non-empty, literal strings with a backslash, a quote or a $, and every value detail against a value whose values are not all known (see D5).
  • Every exception of InvalidPropertyAssignment other than untyped properties.
  • null stored in a property whose default value is null, or in an untyped property declared without a default, which PHP starts as null: either makes its @var type nullable, as a null default does for a parameter. A typed property without a default starts uninitialized, not null, and keeps its @var type.

Fix ​

None: either the assignment or the documentation is wrong.

PHP versions ​

No gating.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore DocumentedPropertyAssignment

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