Reputation: 737
Does anyone know any way to specify @return
type based on the input parameter?
My project has a lot of method calls such as
...->getComponent('name')->someMethod()
where getComponent
is a service locator and IDE doesn't understand which value it returns.
Upvotes: 2
Views: 3020
Reputation: 6688
The only way would be to have getComponent()
's @return
tag actually list out all possible data types that could return. This kind of dynamic, loose typing behavior that PHP allows for is not conducive to such static resolution as done by an IDE autocomplete. It has always been a tough case to try to document, because your API doc is just as "static" as the "object tree" that an IDE has to construct in order to provide autocompletion.
If IDE autocompletion is urgent enough to warrant adjusting the code to make it happen, then aside from my earlier
@return ClassOne|ClassTwo|...|ClassInfinitum
option,
you could split the two calls rather than chaining them, and use an @var
"local docblock" that some IDEs know how to recognize:
// this litte docblock establishes the data type for the local variable $nameComponent
// note however that some IDEs want "datatype varname",
// some want "varname datatype",
// and some don't recognize the docblock at all
/** @var \NameClass $myComponent */
$nameComponent = $service->getComponent('name');
// here, the known methods of NameClass should pop up after typing ->
$nameComponent->
Upvotes: 1
Reputation: 1222
For the PhpStorm IDE, you can create one or more files called .phpstorm.meta.php
in your project. Here is an example content of such a file:
<?php
namespace PHPSTORM_META {
override(\Factory::getComponent(), map([
"name" => \some\namespace\Name::class,
"exception" => \Exception::class,
]));
}
You can find the documentation here: https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html#map
I recommend committing this file to make auto-completion available to other PhpStorm users.
Upvotes: 2