PHPStan type aliases

45 Views Asked by At

I have a PHP project which is a library for trees / nodes. It has several generic objects, all of which work in parallel - they are either ordered or unordered, depending on whether the children of a node need to be ordered using an integer index.

The children of nodes are represented in a collection. And each node has a generic type for its "payload". So in my code base there are a ton of objects that are typehinted in the php docs as (for example):

TreenodeAbstract<PayloadType, NodeType, TreeType, CollectionType>

It is a lot of typing (pun intended).

I feel that I should be able to use a global alias in PHPStan to represent the generic qualifications of (in the example above) "Treenode" but the type alias documentation in PHPStan is as little thin. Any thoughts?

1

There are 1 best solutions below

3
Ruslan Osmanov On

PHPStan supports both local and global type aliases.

In your case, a global type alias might be declared in the phpstan.neon configuration file as follows:

parameters:
    typeAliases:
        AbstractTreeNode: 'TreenodeAbstract<PayloadType, NodeType, TreeType, CollectionType>'

Then, you can use the AbstractTreeNode type alias in your code:

/**
 * @param AbstractTreeNode $node
 */

Note that you might need to provide the fully qualified names (see PHP name resolution rules) of the types in the type alias declaration in order to avoid ambiguity, e.g.:

parameters:
    typeAliases:
        AbstractTreeNode: '\Acme\TreenodeAbstract<\Acme\PayloadType, \Acme\NodeType, \Acme\TreeType, \Acme\CollectionType>'