DocumentedPropertyAssignment
warning native off by defaultGroup: 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,@varand@returntags count. - Every declaration the write may reach rejects every value of the stored type, through the declared type of the property or its
@vartype. - The weak-mode conversions and the exceptions of InvalidPropertyAssignment apply alike, except that an untyped property with a
@vartype is checked. - D5. Integer ranges, non-empty strings and literal string values (
'eur'|'usd') of a@vartype count only against a value whose possible values are all known (an integer or string literal such as0or'gbp'); otherwise@var positive-intaccepts any integer and@var 'eur'|'usd'any string.
Exceptions (no report)
- Assignments InvalidPropertyAssignment reports: the declared types reject what the code alone shows.
- A
@vartype naming templates, and a@vartype the declared type rejects (a stale tag). - The other value details of a
@vartype: 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.
nullstored in a property whose default value isnull, or in an untyped property declared without a default, which PHP starts as null: either makes its@vartype nullable, as a null default does for a parameter. A typed property without a default starts uninitialized, not null, and keeps its@vartype.
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