5

If, for example, I have a class like this:

class Foo
{
   /**
    * @var array<string, array{name: string, age: int}>
    */
   private array $things;

   /**
    * @return array
    */
   public function getThings(): array
   {
      return $this->things;
   }
}

Then phpstan will give me something along the lines of Method Foo::getThings() return type has no value type specified in iterable type array.

Of course, I can resolve this by adding the array shape definition to the @return, but given that I've already defined this on the property, is there a way to avoid duplication here that I'm missing?

Mark G
  • 85
  • 1
  • 5

1 Answers1

6

No. PHPStan does not read the method body like that to understand what it returns.

You can use local type aliases to reduce the duplication:

/** @phpstan-type Things array<string, array{name: string, age: int}> */
class Foo
{
   /**
    * @var Things
    */
   private array $things;

   /**
    * @return Things
    */
   public function getThings(): array
   {
      return $this->things;
   }
}
Can Vural
  • 2,222
  • 1
  • 28
  • 43
  • 1
    awesome, thank you! As an aside question/opinion (for better understanding): do you think it would be a reasonable addition to phpstan? Or, could you foresee any problems with handling this sort of thing automatically? – Mark G Oct 08 '22 at 22:04
  • @MarkG Funny enough, someone asked the same question recently. And the answer is no: https://github.com/phpstan/phpstan/discussions/8137#discussioncomment-3830570 As it's mentioned, maybe Rector already can handle this automatically. – Can Vural Oct 08 '22 at 22:24