1

Is there a way to use class constants to define array shapes in phpstan?

The purpose is to enable the definition to be used by PHP code, otherwise we have to repeat the definition (once for phpstan and once for PHP) and that feels wrong!

For example, we have:

/**
 * @phpstan-type BarArrayShape = array{
 *     abc => string,
 *     def => string,
 *     ghi => int,
 *     jkl => \DateTime,
 * }
 */
class Foo
{
    private const ARRAY_SHAPE_BAR = [
        'abc' => 'string',
        'def' => 'string',
        'ghi' => 'int',
        'jkl' => '\DateTime',
    ];

    /**
     * @param BarArrayShape $dataArray
     * @return void
     */
    public function doSomething(array $bar): void
    {
        $expectedKeys = array_keys(self::ARRAY_SHAPE_BAR);
        foreach ($expectedKeys as $key) {
            ...
        }
    }
}

We used to use PHP Storm ArrayShape attributes (which worked fine) but trying to migrate to phpstan instead.

E.g. used to be able to do something like this:

    public function doSomething(#[ArrayShape(self::ARRAY_SHAPE_BAR)] array $bar) {}

Is there a way to do the same in phpstan?

I've tried doing:

@phpstan-type BarArrayShape = self::ARRAY_SHAPE_BAR. It works for the array keys, but the syntax is wrong, so it thinks that 'int' is a literal string which says 'int', and not an integer type definition.

Is there a solution?

1
  • Did you get an answer? Commented Mar 27 at 20:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.