php-standard-library / phpstan-extension

14 stars 4 forks source link

Infer phpdoc return type based on shape #15

Closed simPod closed 1 year ago

simPod commented 1 year ago

I wonder if there's any way to infer a type for phpdoc from shape().

I often define a complex type using shape(). Then I want to put it into a method to allow it's reuse.
However, there's no way to somehow make phpstan infer the method's return type so you have to redefine the shape again in your @return phpdoc.

/**
 * @return IHaveToWriteThisComplexShapeAgainForPhpdocWhichIsVeryTedious
 */
function coerce(mixed $v): array {
   return shape(...)->coerce($v);
}

Any ideas how this could be improved?

ondrejmirtes commented 1 year ago

Any ideas how this could be improved?

It can't without making PHPStan much slower.

Your best option is to repeat the array shape in @return as you're doing now.

You could also write a custom script (with the help of custom PHPStan collectors) that would sync the PHPDoc array shape with the actually returned array shape by your function.

simPod commented 1 year ago

Aight, thanks for input.

github-actions[bot] commented 2 months ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.