Search by

hampel / xenforo-phpstan

hampel

PHPStan for XenForo add-ons - the configuration an add-on needs to be analysed against a forum, the methods class extensions add to core classes, the container shortcuts, and the legacy class names XenForo 2.3 aliases at runtime

Package info

github.com/hampel/xenforo-phpstan

Type:phpstan-extension

pkg:composer/hampel/xenforo-phpstan

Statistics

Installs: 527

Dependents: 1

Suggesters: 1

Stars: 1

Open Issues: 1

1.3.2 2026-11-30 22:54 UTC

README

Tests Latest Version on Packagist Total Downloads Open Issues License

By Simon Hampel

A PHPStan extension for add-ons developed inside a XenForo 2 install. It carries what every add-on would otherwise have to work out alone: the configuration that lets PHPStan see the forum without analysing it, the legacy class names XenForo 2.3 aliases at runtime, the XFCP_ parent of every class extension, the methods those extensions add to core classes, and the container shortcuts given the short Vendor\AddOn:Name identifier.

Without it, PHPStan reports a working add-on as broken. On a real add-on the count at level 2 went from 262 errors to 12 on configuration alone, and from 12 to 2 once the extensions were in place; across seven add-ons the residual fell by between a quarter and six sevenths. What is left is real.

Installation

In the add-on's directory:

composer require --dev hampel/xenforo-phpstan
vendor/bin/xenforo-phpstan generate

generate reads the forum the add-on sits in and writes four files into <forum>/internal_data/phpstan/: a stub declaring every legacy class name the forum aliases, a stub declaring the XFCP_ parent of every class extension the install has, the map the extensions read, and a copy of the forum's XF\Options class for PHPStan to scan. Run it again after upgrading XenForo or changing a class extension — a stale set fails loudly, naming the two versions and this command.

The simplest way never to forget is to run it in front of every analysis. It takes a fraction of a second (0.2 s on a forum with 963 aliases and 123 class extensions), and it writes nothing when the set already there is current, so PHPStan's result cache, which records the hash of every stub file and starts over when one changes, is left alone:

"scripts": {
    "analyse": [
        "xenforo-phpstan generate",
        "phpstan analyse"
    ]
}

That holds on a forum several add-ons share: a set that is current is left untouched, and it is rewritten only when the forum itself has changed, which is when every add-on there needs the new one.

From 1.0 a ^1.0 constraint takes every later 1.x release with composer update. A minor can still change what an add-on sees at its level, because typing a value that was mixed reports what was passed over before and makes a guard on it redundant, so read the changelog when a count moves. An add-on still on a ^0.x constraint stays on that minor until the constraint is changed: if composer update reports nothing to do after a release, that is the constraint, not Packagist.

The forum is found four directories above the working directory, which is where it is from an add-on at src/addons/<Vendor>/<AddOn>. From anywhere else, name it:

vendor/bin/xenforo-phpstan generate --root=/path/to/forum

The set is shared by every add-on on the forum, so before regenerating it under someone else's analysis, ask whether it is still current:

vendor/bin/xenforo-phpstan generate --check

It writes nothing: exit 0 and the generated date when the set is the one generate would write now, exit 1 and the reason when it is not. It applies the test PHPStan applies on first use, which refuses a set that is missing, written by an older release or generated for another XenForo, and then builds the set again in memory and compares, which is what notices a class extension added, removed or switched off since, naming each one.

Configuration

The add-on's own phpstan.neon includes the fragment and supplies what is the add-on's: its paths, its level, and the directories of its own that are not source.

includes:
    - vendor/hampel/xenforo-phpstan/extension.neon

parameters:
    level: 2

    # The add-on's own result cache; without it every add-on on the machine shares one.
    tmpDir: .phpstan.cache

    paths:
        - .

    excludePaths:
        # Scanned through the Composer autoloader already; scanning the directory as well lets a
        # dependency's scaffold shadow the add-on's own classes of the same name.
        analyseAndScan:
            - vendor (?)
        # Generated by XenForo, and not the add-on's code.
        analyse:
            - _output (?)
            - _releases (?)
            - _data (?)

The (?) marks a path optional. PHPStan refuses to start when an excluded path does not exist, and an add-on that extends nothing has no _output/, one that has never been built has no _releases/.

tmpDir gives the add-on a result cache of its own. PHPStan's default is one directory under the system's temporary directory, so every add-on analysed on the machine reads and writes the same cache: analysing a second add-on discards the first one's, and each run after a switch starts cold; two runs at once write one file. The path is relative to the configuration file. Being a dot directory it is already left out of the scan, and it wants two more lines of the add-on's own, since it is neither source nor part of a release: /.phpstan.cache/ in .gitignore, and its removal in build.json, as for PHPUnit's cache if the add-on has one:

{
    "exec": [
        "rm -rf _build/upload/src/addons/{addon_id}/.phpstan.cache"
    ]
}

If the add-on uses phpstan/extension-installer, the includes line is not needed.

The forum root

extension.neon takes the forum to be four directories above where PHPStan runs. To analyse an add-on from somewhere else — a checkout outside the install, a CI job with a forum unpacked beside it — set the root, and if the generated files are elsewhere, that too:

parameters:
    xenforo:
        root: /path/to/forum
        generated: /path/to/forum/internal_data/phpstan

Magic properties

Entity columns, options and route parameters are magic properties, and PHPStan reports each access as undefined. The add-on object's are typed individually, as the next section describes; these three classes have no static answer, and crates.neon opts them into PHPStan's object-crate treatment:

includes:
    - vendor/hampel/xenforo-phpstan/extension.neon
    - vendor/hampel/xenforo-phpstan/crates.neon

It is a separate file because the cost is real: a crate accepts any property name, so a mistyped column is silenced as readily as a correct one. The precise alternative for entities is php cmd.php xf-dev:entity-class-properties, which writes @property docblocks into the add-on's own entity classes — an edit to committed source, so a decision for each add-on rather than a default. An add-on with no entity of its own usually needs neither: XenForo's own entities carry @property docblocks, so $visitor->user_id is already typed, and a crate would only hide a mistyped name.

The three classes need not go together. Route parameters have no static type anywhere, while entity columns have one wherever a @property docblock exists, so an add-on that wants $params->user_id quiet without crating every entity lists the one class itself instead of including the file:

parameters:
    universalObjectCratesClasses:
        - XF\Mvc\ParameterBag

Options have a precise answer of their own. XenForo writes an _output/option_hint.php for every add-on in development mode, each declaring an empty XF\Options with that add-on's options as @property lines, so an install declares the class once for real and once per add-on, and the declaration PHPStan's directory scan settled on was not XenForo's: \XF::options() had none of its ArrayObject methods, and carried some add-on's options or none depending on the add-on's phpVersion. The fragment scans XenForo's own class by name, which PHPStan consults ahead of the directories, so the class is the real one everywhere. The file it names is generate's copy of src/XF/Options.php, because PHPStan stops on a scan file that does not exist and XenForo 2.3.0 has no such class: there its options are a plain ArrayObject, the copy declares nothing, and the analysis runs. \XF::options() is that ArrayObject there, so every option read is reported as an undefined property of it, with or without a hint stub, which types nothing the code reads; that is true of that release, and an ignore for the report is the add-on's to write. Code that names XF\Options itself is an unknown class there unless some add-on's hint file is on the forum to declare it. Measured against the 2.3.0 source. On any later forum an add-on types its own options by listing its hint as a stub:

parameters:
    stubFiles:
        - _output/option_hint.php

The stub's @property lines are read because the real class allows dynamic properties. Any other option, core's included, stays undefined, which is the point: a mistyped name of the add-on's own is reported. The stub replaces the class docblock, so getArrayCopy() becomes array<mixed> with it in place. An add-on that crates XF\Options instead is unaffected by any of this, and the choice is the usual one: the stub reports a mistyped name of its own and every core option it reads, so moving from the crate to the stub costs one ignore per boardTitle, or the core stub below; the crate checks neither. An add-on that reads core options throughout wants the generated file below from the start: with the hint alone, one such add-on began level 2 with 43 reports, nearly all of them core options. An add-on with no options of its own that reads one or two of core's has no hint to list, so its choice is between the generated file below and the crate, and for a boardUrl read the crate is the usual answer: there is no name of its own for the stub to check, and nothing to regenerate.

Core options can be typed the same way. XenForo's xf-dev:generate-options-stub writes a file of the same shape for any set of add-ons, core alone by default, from the option data, so it needs development mode and the database:

php cmd.php xf-dev:generate-options-stub --addon=XF --addon=Vendor/AddOn /path/to/Options.stub

Name that one file in stubFiles in place of the hint, and \XF::options()->boardTitle is string|null beside the add-on's own options, while a misspelt name is still reported. One file, because a class may be declared in one stub only, which is why core and the add-on go into the same run. It is generated from option data rather than committed source, so it is stale the moment an option changes and nothing regenerates it for you; keep it with the other generated files rather than in the add-on.

Either file writes an array option with no sub-option structure as a bare array, four of core's on 2.3.13 and one more nested inside a fifth's shape, and PHPStan reports each on the stub's class line as a missing iterable value type. That report can be neither ignored nor excluded: PHPStan refuses an ignoreErrors entry for a stub's own errors, and an excludePaths entry does not reach them, measured both ways. The remedy is to widen the bare arrays in the generated file, which is XenForo's output rather than committed source:

sed -E -i '/@property/ s/\barray\b([^<{-]|$)/array<mixed>\1/g' /path/to/Options.stub

An add-on whose own options include such an array meets the same report through its hint, and XenForo rewrites the hint whenever options change, so that add-on wants the generated stub, with the line above, rather than the hint.

XenForo writes every typed option as nullable, the add-on's own included, and from level 8 each read of one is reported where a null is not accepted. A core option may be absent from an older forum, so its |null is worth keeping. An installed add-on's own options always exist, and the same generated file can say so, by the prefix the add-on gives its option ids:

sed -E -i '/ \$acmeDemo/ s/\|null \$/ $/' /path/to/Options.stub

On one add-on that was 36 of the 93 reports level 8 added.

A crate also decides what a class extension's added columns look like, and the answer depends on the PHPStan release. The current release asks the extensions in this package before it applies the crate, so a crated XF\Entity\User still types $visitor->vendor_addon_column from the extension's @property and still reports a write to a @property-read; PHPStan 2.1.22 applies the crate first, and on a crated entity every added column is mixed and nothing is reported. Without crates the extension answers on both.

A PHP floor below the analysing PHP

An add-on whose floor is below the PHP it is analysed on can have PHPStan hold it to the floor:

parameters:
    phpVersion:
        min: 70400
        max: 80500

That reports syntax newer than the floor, and nothing else. A match, a union type, a nullsafe call is caught; a call to str_contains() on a 7.4 floor is not, because PHPStan reads functions from the PHP it runs on. It also applies to everything analysed, and PHPUnit 12 is not readable as 7.4 code, so a suite under tests/ becomes one method.notFound per assertion. The shape that works is a second config for the shipped code alone, included from the first:

# phpstan.floor.neon
includes:
    - phpstan.neon

parameters:
    phpVersion:
        min: 70400
        max: 80500
    excludePaths:
        analyse:
            - tests

vendor/bin/phpstan analyse -c phpstan.floor.neon is then the floor check, and the plain run analyses the tests. It inherits the level as well as the paths, so it is a second full analysis of the shipped code, not a syntax check; level: 0 in the floor file makes it the syntax check alone, because a parse error is reported at every level. It inherits ignoreErrors too: an ignore whose path names one file under tests is silent there, but one with a pattern for a path, or with no path, has nothing left to match and is reported as unmatched, which reportUnmatchedIgnoredErrors: false in the floor file answers. An add-on whose release build already lints on the floor PHP may decide that is enough and leave phpVersion out. PHPStan's own floor is 70100, so an add-on that supports XenForo 2.2's PHP 7.0 holds at 7.1, which is as low as the setting goes.

With no phpVersion set, PHPStan takes the floor from composer.json and the ceiling from the PHP it runs on. An add-on with a vendor/ directory and "php": ">=7.4" under require is held to 7.4 syntax, tests included, so a native union type in a test that only ever runs on 8.3 is reported as unsupported; config.platform.php does not change that, and an explicit phpVersion does. With no php requirement the floor is the running PHP too.

So upgrading the PHP that PHPStan runs on can move an add-on's count with no change to the add-on or to this package. PHP 8.5 deprecates null as an array key, and under it every $map[$entity->some_id] whose id XenForo documents as int|null is reported as a possibly invalid array key. One add-on that was clean at level max reported 14 the day its command-line PHP became 8.5, on every release of this package it tried, and none under phpVersion: 80300. The reports are true of 8.5: narrow the key, or set phpVersion to the range the add-on supports if that stops below it. PHPStan's own version moves it as well: 2.3.1 reports a nullable key under 8.5 and 2.3.7 does not, measured on the same file, so two machines on different patch releases can disagree about an unchanged add-on.

Supporting XenForo 2.2

The forum analysed against is a 2.3 install, so a guard for a 2.3 method is always true there:

if (method_exists('XF', 'accessToken')) { // function.alreadyNarrowedType at level 4 and above

The guard is right, and the report is PHPStan being told the truth about one forum. Ignore it by identifier and path, so a guard that stops being needed is still noticed:

parameters:
    ignoreErrors:
        -
            identifier: function.alreadyNarrowedType
            path: Cli/Command/Validate.php

The same applies to class_exists() on a class 2.3 added, and to any branch that runs only on 2.2.

Level 6 asks for a return type on every method, and on a class other add-ons extend the native form is a breaking change: an override written without it, as every one against the untyped original was, is an incompatible declaration, which PHP refuses to load. That covers any class the add-on registers through extendClass(), and any other it expects to be subclassed. Type those methods by docblock, which PHPStan reads the same way and PHP does not check; a class nobody extends can take the native type.

A class declared twice, inside if (\XF::$versionId >= 2030000) and its else, because 2.3 added a return type to a method the extension overrides, is a different case: read against 2.3, the untyped 2.2 declaration is an incompatible override, and method.childReturnType is one of the reports PHPStan refuses to ignore. Excluding the file loses the 2.3 branch with it. Put the two declarations in two files, required from the one the autoloader finds by the same test, and exclude the 2.2 file alone.

Container keys

A container entry is mixed until the add-on says what it holds. An entry is a closure registered at runtime, in an app_setup listener or a sub-container's initialize(), so no docblock states its type and every getter that returns one hands PHPStan mixed. Declare the keys the add-on reads, once:

parameters:
    xenforo:
        container:
            acme.api: Acme\Demo\SubContainer\Api
            acme.hosts: 'array<int, string>'
        subContainers:
            Acme\Demo\SubContainer\Api:
                client: Acme\Demo\Api\Client
                retries: int

Each value is a PHPDoc type: a class name written in full, or anything else a @return could say. Quote a value that contains a comma, because NEON reads a bare one as the start of the next entry and the configuration does not load. A type alias a class declares with @phpstan-type is not known here; write the type out.

  • container is the application's container, and types $app->container('acme.api'), $app->get('acme.api'), $app['acme.api'] and $app->container()['acme.api'].
  • subContainers is keyed by the sub-container class first, because a sub-container keeps its entries in a container of its own, under keys that mean nothing outside it. It types $this->container['client'] written inside that class or a subclass, and $api['client'] and $api->get('client') on the sub-container from outside.

A key that is not declared is left as it was, and so is a key that is not a constant string. A key of another add-on's, such as a shared logger, is declared by each add-on that reads it.

The declaration is a claim, checked against nothing. It moves what a @var beside every read would say into one place, and like a @var it is wrong the day the closure returns something else. Where the entry is built by extendClass(), declare the class the add-on wrote: an extension of it is a subclass.

What it does

Scans the forum, analyses the add-on

PHPStan is told where XenForo's classes are without being asked to report on them: src/XF, src/vendor and src/addons are scanned for symbols, src/XF.php and src/utf8.php are read as files because XenForo require()s them rather than autoloading them, generate's copy of src/XF/Options.php is read as a file because every add-on's option hint declares that class too, and every add-on's vendor/, _build/ and dot directories are left out of the scan. The first matters more than it looks: PHPStan consults a scanned directory before the Composer autoloader, so without it an add-on resolves a shared dependency from whichever sibling vendored an older release of it. The second is the copy of itself a release build makes under _build/upload/, which declares every class of that add-on twice while it exists, and aborts the run if the build deletes a file as PHPStan reads it. A dot directory is tooling's: a git worktree checked out under one is a second copy of the whole add-on, possibly from another branch. The generator skips the same directories, and any path with a segment that is not a PHP identifier, since no class can be autoloaded from one.

Legacy class names

XenForo 2.3 renamed its classes with type suffixes — Tools became ToolsController, SessionActivity became SessionActivityRepository — and registered an autoloader that class_alias()es each old name to the new one. PHPStan cannot follow a runtime alias, so an add-on that extends or type-hints a legacy name sees every inherited member as undefined.

The generated stub declares each legacy name as a subclass of the renamed class. The mapping comes from the forum itself, by asking \XF::getAliasForClass() for every class file under src/XF and src/addons, so it covers all ten suffixes XenForo's table abbreviates and never invents a name core does not alias. On 2.3.13 that is 864 declarations for core alone; 43 further aliases strip to Abstract, a reserved word, and are skipped, because no source could have referenced them either.

An add-on supporting XenForo 2.2 cannot avoid this by renaming its extensions: the suffixed classes do not exist in 2.2, and 2.2 has no alias machinery, so the legacy name is the only one valid across the range.

Methods and properties added by class extensions

A class extension adds methods to a core class at runtime — Vendor\AddOn\XF\Entity\User adds canUseThing(), and every $user in the forum can call it. Statically every call site is typed to XF\Entity\User, so PHPStan reports each such method as undefined. On a fleet of 43 add-ons this was 396 of the 757 errors left once the configuration was right.

The reflection extension answers for those methods from the extension classes recorded at generation time: for a call on a core class, or anything below it, it offers a method any extension of that class declares. The map covers every add-on installed in the forum, not only the one being analysed, because the methods a third-party add-on's extensions add are reachable from any other add-on — and a packaged add-on ships without the _output/extension_hint.php that would declare its XFCP_ parents, so those are generated too, from each add-on's committed _data/class_extensions.xml.

Two things XenForo decides when it registers an extension are mirrored. An extension registered active="0" has its XFCP_ parent declared, so the class still compiles, and nothing it adds is offered, since XenForo never applies it. An extension of a class the forum does not have, as an optional integration's extension of an add-on that is not installed, gets the fake base XenForo substitutes when it requests a view, a finder or a repository by name, XF\Mvc\View, Finder or Repository, so everything below it resolves; anywhere else XenForo applies no extension at all, and the parent is left naming the class it cannot find. Such a file cannot be analysed on a forum without the other add-on, and excluding it under excludePaths, with a comment naming the add-on it waits for, is the answer.

The same goes for a column or a relation an extension adds in getStructure(). The extension declares it as XenForo declares its own, @property string $vendor_addon_column or @property-read Thing|null $Thing on the class, which is what xf-dev:entity-class-properties writes; inside the extension PHPStan already reads that, and through the core type, which is what \XF::visitor(), a finder result or a test helper gives you, the read was property.notFound from level 2. A second reflection extension offers every property the recorded extensions of a class declare, with the declared type and writability, so $visitor->vendor_addon_column = $x is typed and $visitor->Thing = null is reported against a @property-read. A property the core class declares itself is left to PHPStan's own reading of it.

A typed relation exposes the entity behind it. Once $visitor->Thing is a Thing rather than mixed, every column read on it is checked, so an add-on entity reached through a relation needs its own @property block or its columns are reported as undefined from level 2. One adopter's move to 0.9 surfaced six such reads on an entity that had never been typed; the docblock from xf-dev:entity-class-properties cleared them. That is the add-on's gap, found rather than caused.

Container shortcuts

$this->repository('Vendor\AddOn:Name'), \XF::service(), $this->em()->find('XF:User', $id) and the rest are typed as @template T with a class-string<T> argument in 2.3, which the short identifier defeats: the call returns the base type, and everything called on it is undefined. The return type extensions expand the identifier as \XF::stringToClass() does, for every shortcut on XF, XF\App, XF\Mvc\Controller, XF\Mvc\Entity\Manager, Repository, Entity, XF\Service\AbstractService and XF\Widget\AbstractWidget — the finders, repositories, services, entities, data classes, controller plugins, behaviours, jobs, searchers, filterers, helpers, validators, criteria and notifiers, and a controller's assertRecordExists() family — and the argument itself is no longer reported against the class-string annotation at level 5, or as an unresolved template type at level 6.

$this->em()->findByIds('XF:Thread', $ids) is typed as a collection of the entity named, so a foreach over it yields threads. It is a collection of the core entity even within the add-on that extends it: XenForo declares the collection's template without variance, and a collection of the extension would not pass where the add-on declares one of the core entity.

extendClass() carries the same annotation and is ignored the same way when it is given a string: the class it extends is usually a name read from a column or held in a variable.

Within the add-on that extends the class, the shortcut returns that extension rather than the core class: at runtime it is what comes back, and it is the only type under which a method the extension overrides with a different signature is called correctly. Elsewhere the core class is returned, with every extension's added methods reachable through it. Which add-on a file belongs to is its directory under src/addons, so the add-on's tests count as its own.

Passing ::class is typed by XenForo's own annotation without any of this, and within the add-on that extends the class it still returns the extension. It is the better form for the add-on's own classes. It is not safe for a renamed core class while the add-on supports 2.2: \XF\Repository\UserRepository::class is a string whatever is installed, and on 2.2 the class it names does not exist.

One class name XenForo's annotation cannot describe is an entity's given to a finder shortcut. XenForo 2.3 accepts $this->finder(Widget::class) and hands back that entity's finder, where the annotation asks for the class of a finder, so the result was a bare Finder yielding plain entities, and within the add-on that extends the entity it was typed as the entity itself. It is typed as the identifier form is: the entity's finder class where it has one, and the generic Finder of that entity where it has none, so fetch() and a foreach yield the entity. That is XenForo 2.3's behaviour, whoever owns the entity. An adopter with a 2.2 floor read 2.2.19's Manager::getFinder() as taking a name with no colon to be the finder class itself, so an entity's class given to finder() or findByIds() builds the entity as a finder there, and a suite run on 2.3 passes; that reading has not been run here. An add-on that supports 2.2 keeps the identifier form for these calls.

$app->container() with no key is the container itself, XF\Container. XenForo documents the method as Container|mixed, which PHPStan reads as mixed on both paths, so an add-on that reaches the container to register or read an entry called every method on it undefined. A read by key is typed where the add-on has declared the key, see Container keys, and stays mixed for any other: what an entry holds is a fact about the add-on that registered it.

Undeclared return types

XenForo declares no return type on many of the methods every add-on calls. Below level 7 that costs nothing; at level 7 and above each result is mixed, and everything it is passed to is reported. stubs/core.stub restates each with the type the method body returns, read from 2.3.13, and stubs/db-schema.stub does the same for the schema builder. The stub is the reference for the type itself; these are the members it types.

Every reading here, and the plugin actions, save processes and finder conditions further down, was checked again against 2.3.14 on 2026-12-01: nothing moved. One correction below is XenForo's own from that release, which documents Request::getFile() as the stub does.

class members
XF phrase(), config() with no key, $DS, getRootDirectory(), getSourceDirectory(), getAddOnDirectory()
XF\App findByContentType(), applyExternalDataUrl(), getGlobalTemplateData(), config() with no key
XF\Language phrase(), dateTime()
XF\SimpleCache getSet()
XF\ContinuationResult completed()

The request, the controller and what it returns:

class members
XF\Mvc\Controller view(), redirect(), error(), message(), exception(), formAction(), reroute(), rerouteController(), reroutePath(), buildLinkHash(), $request
the reply classes the parameter getters
XF\Mvc\View getTemplateName()
XF\Mvc\FormAction every step, which returns the action so that ->basicEntitySave(...)->run() chains, and run() itself
XF\Mvc\Router buildLink(), prepareStringForUrl()
XF\Http\Request filter(), getIp(), getUserAgent(), getBasePath(), getRequestMethod()
XF\Pub\Controller\AccountController accountDetailsSaveProcess(), preferencesSaveProcess()
XF\Api\Controller\AbstractController apiResult(), apiSuccess(), apiBoolResult(), apiError()
XF\Api\Mvc\Reply\ApiResult getApiResult()

Entities, finders and the database:

class members
XF\Mvc\Entity\Entity save(), getErrors(), toArray()
XF\Mvc\Entity\Finder the fluent methods, columnSqlName(), columnUtf8(), caseInsensitive(), quote(), escapeLike(), getIterator()
XF\Mvc\Entity\AbstractCollection keys(), getIterator()
XF\Mvc\Entity\Manager getBasicCollection(), getEmptyCollection()
XF\Mvc\Entity\Structure $shortName, $contentType, $table, $primaryKey, $columns, $relations, $getters, $defaultWith, $options, $behaviors, $columnAliases, $withAliases
XF\Db\AbstractAdapter quote(), escapeLike(), fetchRow(), fetchAll(), fetchAllColumn(), fetchAllKeyed(), fetchPairs(), getQueryCount()
XF\Db\Schema\AbstractDdl addColumn()
XF\Db\Schema\Column the fluent setters

Core's own entities, repositories and services:

class members
XF\Entity\User canFollowUser(), canViewFullProfile(), canViewBasicProfile(), hasAdminPermission(), hasPermission(), hasContentPermission(), hasNodePermission()
XF\Entity\Node getBreadcrumbs(), getNodeListExtras()
every core entity that leaves it undeclared getMasterPhrase(), and getMasterTitlePhrase() with getMasterDescriptionPhrase() where an entity keeps the two apart
XF\Repository\NodeRepository getFullNodeList(), filterViewable(), mergeNodeListExtras()
XF\Repository\UserRepository getUsersByNames(), documented as a bare collection
XF\Repository\TagRepository normalizeTag()
XF\Service\ValidateAndSavableTrait validate(), and what it writes to $errors
XF\Service\User\MergeService setSource(), setTarget(), merge()
XF\Service\User\RegistrationService _save()

Add-ons, templates and the rest:

class members
XF\AddOn\Manager getById()
XF\AddOn\AddOn getJson(), getAddOnDirectory(), getInstalledAddOn()
XF\Template\Templater callMacro(), callAdsMacro(), fnAvatar(), $defaultParams, and the form helpers it leaves undeclared, formRow(), formTextBoxRow(), formSelectRow() and the rest, which an option renderer returns
XF\Option\AbstractOption the five row helpers
XF\BbCode\Traverser render(), renderAst(), renderSubTree(), renderSubTreePlain(), renderUnparsedTag()
XF\BbCode\Renderer\Html filterString()
XF\Str\Formatter getLinkClassTarget(), getProxiedUrlIfActive()
XF\Util\File getTempFile() and its three temp-path siblings, canonicalizePath(), getCodeCachePath(), stripRootPathPrefix()
XF\Spam\Checker\AbstractProvider $app

Documented types are corrected rather than transcribed where XenForo's own code contradicts the docblock, and the stub says so at each one. Each is held by a fixture class carrying XenForo's docblock, and every one is reported against the previous stub.

member XenForo documents the code does
the schema builder's index name null takes a name
AbstractAdapter::query()'s parameters an array core itself passes a scalar, and the statement wraps it
AbstractSetup's install(), upgrade() and uninstall() null|StepResult a setup with a single step falls out without returning, as most do, so the stub adds void; only core reads the result
Finder::expression() static, the finder returns a FinderExpression, which is what where() and order() take
AbstractCollection::filter()'s callback returns bool the body is array_filter(), which keeps any truthy result
AbstractCollection::groupBy()'s callables callable(T $e): int|string, which PHPDoc reads as a callable returning int beside a plain string a callable returning either
Controller::noPermission()'s message one message goes to error(), which takes a list too
Controller::filter()'s $type a string the request it calls takes an array of filters too
Request::getFile() an upload or a list of them one upload asked for is the upload, null where the key was not sent or false where no file came; only $multiple gives the list
AbstractWidget::render() string|null every core widget returns $this->renderer()
Purchase::$purchasableId a string core's own purchasable assigns an entity id
ActivityLogRepository::log()'s values a list of maps core's handlers pass one map
AttachmentRepository::addAttachmentsToContent() AbstractCollection|Entity[], read as a collection only iterates whatever it is given, an array included
the activity log handler's getReplyMetricsSimple() parameters a map bound positionally
the activity log handler's getReactionMetrics() the handler's own entity core's thread handler passes the first post
Stats\AbstractHandler::adjustStatValue() an int the attachment handler returns round(..., 2)
ModeratorLog\AbstractHandler::getContentTitle(), InlineMod\AbstractAction::getTitle(), ConnectedAccount\Provider\AbstractProvider::getTitle() a string core's own implementations return a phrase, so an add-on's doing the same was an incompatible declaration
Manager::instantiateEntity() nullable for an int-mask of the proxied flag, which includes the default of 0, so every plain call read as nullable returns null only under a non-zero option, the allow-invalid one the mask leaves out included
getMasterPhrase() on StyleProperty and StylePropertyGroup the renderable XF\Phrase, by an import returns the XF\Entity\Phrase entity, so setting its text and saving it was reported from level 2
the four request methods of Http\Reader $saveTo and $error as null the first is the path or stream the body is written to and the second comes back holding the failure, so downloading to a file was reported from level 5 and every check of the error read as always false
Mailer::getTransportFromOption() the transport interface every branch returns an AbstractTransport, the only type the mailer accepts back
XF::$version @var string and @var int in one block meant for it and $versionId together, which reads as neither the stub gives each its own
Util\Ip::convertIpStringToBinary() and convertIpBinaryToString(), both deprecated bool|string no path returns true
Util\Ip::parseIpRangeString() array|bool, with the keys in prose false, or one array of six known keys

The finder's fluent methods are declared as returning static, so a chain keeps the entity type the finder was created with, which XenForo's own @return Finder on order() lost; the schema Column's setters are declared the same way. An add-on's own finder carries an entity type only if it declares one, @extends Finder<Thing> as XenForo's finders do; xf-dev:entity-class-properties writes nothing for a finder, and one without the line fetches Entity. Three of the types are wider than an adopter asked for, because the body is: hasPermission() and its two siblings return the permission's value, a bool for a flag and an int for an integer permission such as maxMentionedUsers; getUserAgent() returns getServer()'s default of false when the request sent no agent, which a string column set from it does not survive; and getTempFile() returns tempnam(), false when the temp directory cannot be written, which XenForo does not check. Iterating a collection, or a finder, yields its entity: getIterator() is restated on both, because a class declared in a stub loses XenForo's own docblock on that one method. The manager's two collection factories are documented as a bare ArrayCollection, which reads as a collection of Entity and cannot be returned where a typed collection is declared. getBasicCollection() is a collection of exactly what it was given: XenForo declares the collection's template without variance, so a collection of an extension's user is not a collection of core's, and an array built from a nullable lookup is reported before it becomes one. getEmptyCollection() is a collection of nothing, which passes wherever any typed collection is expected, the short circuit XenForo describes it for. Templater::func(), a template function called directly as a test does, is typed by an extension rather than a stub: the result is escaped, so a string, unless $escape is passed false, when it is whatever the function returned.

The add-on object AddOn\Manager::getById() returns answers $addOn->title and $addOn->version_string by magic, nine keys of its own and then any column of the installed XF\Entity\AddOn. Each is typed individually, the keys from their getters and the columns from the entity's own docblock, so a mistyped key is still reported. A key that exists only in the add-on's addon.json is not offered; read it through getJson(). XF\Job\JobResult answers $result->completed the same way, the one key its __get() has, and the stub declares it.

Plucked columns

$finder->pluckFrom('user_id') replaces each fetched entity with that column, or with what a closure returns, and XenForo declares it as returning the finder, so fetch()->toArray() after it was still an array of entities. It is typed over the plucked value instead: the entity's own type for the column, an extension's column included, the closure's return type for a closure, and mixed for a column nothing declares. fetchOne() after pluckFrom('username') is string|null.

Relations by name

$user->getRelation('Auth') and getRelationOrDefault('Auth') are typed from the receiver's own @property-read UserAuth|null $Auth, which every XenForo entity declares for each relation and an extension declares for the relations it adds, through the core type as well since the properties extension offers them there. getRelation() keeps the declared nullability; getRelationOrDefault() creates the default, so the result is the entity itself. A name the receiver does not declare leaves the call as XenForo left it.

$user->get('username') is typed the same way, from the @property line for the name, because Entity::__get() is that call: it is $user->username by another spelling, getter included. A name with the trailing underscore that bypasses a getter is typed only where the entity declares it, and a name held in a variable is not typed at all. $user['username'] is the same call again and is typed with it.

$user->getValue('username') reads the column past any getter. For a column that has one, XenForo's xf-dev:entity-class-properties writes two lines, @property string $content_title_ for the stored value and $content_title for the getter's, so getValue() is typed from the underscored line where the entity declares it and from the plain line where it does not. An entity whose docblock was written by hand, with a getter over a column and no underscored line, is typed as the getter there; regenerate the docblock or add the line. getExistingValue() and getPreviousValue() read the same column from the stored and the previous values, and are typed as getValue() is.

Controller actions

Every controller action returns a reply, since the dispatcher rejects anything else, and XenForo declares none of them. An action* method with no return type of its own is typed AbstractReply, through $this-> and through parent::, so return parent::actionIndex() in a controller extension is no longer mixed. An action that declares a return type, XenForo's or the add-on's, keeps it.

The actions of XenForo's own controller plugins are typed the same way, so an extension of the warning or delete plugin returning parent::actionWarn() is a reply too. Nothing enforces that of a plugin as the dispatcher does of a controller, so it is claimed only of a method a class under XF\ControllerPlugin declares, each read from 2.3.13; a plugin of another add-on, or of the add-on's own, declares its return or stays mixed.

Save processes

A core controller's save process, userSaveProcess() and its like, builds a form action, fills it and returns it, with no declared return type: 67 of the 70 in 2.3.13. So $form = parent::userSaveProcess($user) in a controller extension, the line every added field starts from, was mixed, and so was each step added to it. A *SaveProcess() method declared by a controller under XF\Admin\Controller, XF\Pub\Controller or XF\Api\Controller is typed FormAction, through $this-> and parent::. The other three, the custom field processes, are handed the form as their first parameter and return nothing; they are told apart by that parameter and left alone, as is a save process another add-on or the add-on itself declares.

Finder conditions

The conditions XenForo's own finders add, isValidUser(), inForum(), skipIgnored(), newerThan() and the rest, return the finder and declare nothing, so the next call in a chain was on mixed at level 7 and above. The 62 of them under XF\Finder in 2.3.13, each read to return $this on every path, are typed as the finder they were called on, which keeps the entity through to fetch(). A finder of another add-on, or the add-on's own, declares @return static or stays mixed.

Request input

$this->filter('id', 'uint') on a controller, and filter() on the request, are typed from the filter string, as XF\InputFilterer casts the value: str is a string, uint an int, bool a bool, num an int or float, datetime,obj a DateTime, array-uint an array of int, and a leading ? lets null through. An array of filters is an array shape with one entry per key, nested arrays included, so $input['username'] is a string, and so is the array given as the filter for one name, filter('search', ['text' => 'str']). A filter in a variable, or a name the filterer does not have, leaves the call mixed as before.

XF\Tree and XF\SubTree are generic over the record they hold. NodeRepository::createNodeTree() returns a Tree<Node>, a tree built by hand is typed by what it was given, and a subtree's record, children() and parent() follow. That makes a bare Tree or SubTree in an add-on's own docblock a missing-generics report at level 6 and above, as a bare Finder already is; write SubTree<Node>.

The parameters are left as XenForo declares them, mixed where it declares nothing. A parameter type is a claim about every caller, and this package types what comes back.

Levels

Level 2 is the place to start. On a fleet of 43 add-ons with this configuration, the median add-on had 8 errors at level 2, 27 of the 43 had ten or fewer, and most of what remained was the add-on's own to fix. Level 5 is a reasonable target once the call sites are tidy; level 6 is the missing-typehint wall. With the stubs above, level max is reachable: on one small add-on it reports a third fewer than without them, and what remains is the add-on's own typing and route parameters, which no static type can know. The climb finds things on the way: level 8 is where a nullable return is reported at the place it is used, and one add-on learned there that XFMG's MediaItem::getThumbnailUrl() returns null until a thumbnail exists, having rendered the null as an empty src until then.

Above level 8, most of what is left is the add-on describing itself, not the forum. PHPStan never infers a return type across a method boundary, so an untyped method of the add-on's own hands mixed to every caller, and each use of the result is a report. On one add-on, half of the level-max total came from a single untyped test helper; typing the helpers answered all of it. What remains once the add-on's own methods are typed is core methods with no declared return type that the stubs do not yet cover. An inline @var on the result narrows one in shipped code, and assertIsString() and its siblings narrow one in a test; the list above grows from exactly these reports, the last six from one add-on. Before reading a residual as XenForo's, \PHPStan\dumpType() on the value says whose type is missing. One residual that is neither: Symfony Console's getOption() and getArgument() return mixed by Symfony's own declaration, so a CLI command narrows them itself. Another is a view's parameters: a listener or a controller extension reading $reply->getParams() gets an array whose values are whatever a template was handed, mixed by nature and typed by no stub, so each one is narrowed where it is read, with is_numeric() or an instanceof in front of its use. Narrow by what arrives, not by what the name suggests: an option renderer's $htmlParams['inputName'] is an XF\PreEscaped, because the option template builds it from a macro, so is_string() on it is false and the narrowing that satisfies PHPStan renders every input with an empty name. A test of the rendered page finds that; analysis cannot.

A custom BB code callback is a method of the add-on's own, so its parameters are the add-on's to declare, and XenForo's documented signature is wider than what arrives. The renderer parameter is documented as AbstractRenderer, but only Html::getCustomTagConfig() registers a callback and Html::renderTag() passes itself, so the renderer is always Html or one of its subclasses, and declaring it so is accurate where the abstract type leaves filterString() undefined. The parsed tag has one shape, each child a string or another tag of the same shape:

/**
 * @param list<string|array<string, mixed>> $children
 * @param string|null $option
 * @param array{tag: string, option: string|null, original: array{string, string}, children: list<string|array<string, mixed>>} $tag
 * @param array<string, mixed> $options
 */
public static function renderTagExample($children, $option, array $tag, array $options, Html $renderer)

A tag whose definition has has_option set to yes never arrives with a null option, because RuleSet::validateTag() rejects one before the callback is reached.

Limitations

  • A legacy name is a subclass, not an alias. PHPStan has no notion of two names for one class, so a value typed to the renamed class does not satisfy a parameter typed to the legacy name. The shortcuts return the legacy name when the add-on used it, which keeps the add-on's own types consistent; a value from XenForo's own typed API may still need a docblock.
  • An overridden signature is seen only through the add-on's own shortcut. A value that arrives typed as the core class from anywhere else, XenForo's own typed API included, carries the core signature.
  • A method reached through a base type stays undefined. $entity->canUseThing() on a value typed XF\Mvc\Entity\Entity cannot be resolved by anything here, because the extension is on XF\Entity\User; that is the variable's type being too wide, and the fix is at the variable.
  • A runtime check that the add-on's own extension is applied reads as always true. Inside the add-on that extends XF\Entity\User, create('XF:User') instanceof Extension\User is reported instanceof.alwaysTrue, because the shortcut returns the extension. The check is still worth making at runtime, where a disabled add-on or a broken extension chain would fail it; put the instanceof behind a method taking object, so that nothing is decided before it runs.
  • A value passed by reference inside an array literal is not tracked. After $app->fire($event, [&$collected]) PHPStan still types $collected as the empty array it started as, and every use of it is reported as unreachable or always false. That is PHPStan's own flow analysis, and nothing here reaches it; declare the variable's type with a docblock after the call.
  • Code built on another add-on's vendored library does not resolve. Only the analysed add-on's vendor/ is scanned, by design, so a class that extends a sibling add-on and calls a library the sibling vendors is class.notFound. Exclude that code from analysis; it runs in the sibling's context, not this add-on's.
  • PHPStan itself refuses a stale generated set only for a XenForo upgrade. A class extension added after generation is reported as an unknown XFCP_ parent, which is loud enough; one removed is simply still offered. generate --check does notice both, and names them, but only when it is run, which is why the Installation section runs generate in front of every analysis instead.
  • A docblock between an attribute and its method is not read. Written under #[DataProvider('rows')] and above the method, a @param array<string, int> is ignored and the parameter is reported as an untyped array, with nothing to say why; put the docblock above the attribute. That is PHPStan's reading of the file, measured with no extension loaded.
  • Mockery's higher-order expectations need the mocked class in the mock's type. With phpstan/phpstan-mockery included, $mock->expects()->save($user) is typed on a mock PHPStan knows as Thing&MockInterface, which is what Mockery::mock(Thing::class) returns. On a bare MockInterface, such as a closure parameter declared with that type alone, it is method.notFound from level 2 and everything chained after it is mixed. Declare the intersection, or write $mock->expects('save')->with($user), the same expectation, which is typed either way.
  • PHPStan resolves symbols from the project that installed it. Run it from the add-on's own directory with the add-on's own vendor/bin/phpstan. A phar borrowed from another project consults that project's autoloader first, and the result quietly describes a different dependency tree.

Version support

PHP 8.3, 8.4 and 8.5, and PHPStan 2.1.22 or later. The add-on being analysed can target any XenForo 2 version; the forum it is analysed against is a 2.3 install, because the alias mapping is asked of the forum.

Licence

MIT. See LICENSE.md.