How can I avoid repetition of array shape declaration for method return value?
Asked Answered
C

1

6

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?

Crine answered 8/10, 2022 at 19:25 Comment(0)
H
8

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;
   }
}
Hatter answered 8/10, 2022 at 21:36 Comment(2)
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?Crine
@MarkG Funny enough, someone asked the same question recently. And the answer is no: github.com/phpstan/phpstan/discussions/… As it's mentioned, maybe Rector already can handle this automatically.Hatter

© 2022 - 2024 — McMap. All rights reserved.