phpstan: Template type only for return type

258 Views Asked by At

I think I am misunderstanding something about phpstan.

I have the following method in my interface:

    /**
     * @phpstan-template T of Searchable
     *
     * @param string                $indexName
     * @param ?array<string, mixed> $config
     *
     * @phpstan-return IndexResponse<T>
     *
     * @throws SearchEngineException
     */
    public function createIndex(string $indexName, ?array $config): IndexResponse;

But I get following notice from phpstan: phpstan: Template type T of method App\Service\Common\Search\SearchEngine::createIndex() is not referenced in a parameter.

Okay...T is not in any parameter definition. But why is that necessary? I actually only wanted it for the return type definition. I don't understand why this is not "enough"?

1

There are 1 best solutions below

0
On

Your method signature:

    /**
     * @phpstan-template T of Searchable
     *
     * @param string                $indexName
     * @param ?array<string, mixed> $config
     *
     * @phpstan-return IndexResponse<T>
     *
     * @throws SearchEngineException
     */

is equivalent to:

    /**
     * @param string                $indexName
     * @param ?array<string, mixed> $config
     *
     * @phpstan-return IndexResponse<Searchable>
     *
     * @throws SearchEngineException
     */

Because without referencing T in a parameter type, there's no way for a caller to influence what T is.

Please refer to these article to learn about basics of generics in PHPDocs, and to learn some example of most common problems solved by generics in PHPDocs: