使用类常量定义 phpstan 数组形状

问题描述 投票:0回答:1

有没有办法在 phpstan 中使用类常量来定义数组形状?

目的是使定义能够被 PHP 代码使用,否则我们必须重复定义(一次用于 phpstan,一次用于 PHP),这感觉是错误的!

例如,我们有:

/**
 * @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) {
            ...
        }
    }
}

我们曾经使用 PHP Storm ArrayShape 属性(效果很好),但尝试迁移到 phpstan。

例如曾经能够做这样的事情:

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

有没有办法在 phpstan 中做同样的事情?

我尝试过:

@phpstan-type BarArrayShape = self::ARRAY_SHAPE_BAR。它适用于数组键,但语法错误,因此它认为“int”是一个表示“int”的文字字符串,而不是整数类型定义。

有解决办法吗?

php phpdoc phpstan
1个回答
0
投票

创建一个文件,例如 ArrayShapes.php,来定义数组形状:

<?php

class ArrayShapes
{
    public const BAR = [
        'abc' => 'string',
        'def' => 'string',
        'ghi' => 'int',
        'jkl' => '\DateTime',
    ];
}

在 PHP 代码中,您可以使用这些数组形状:

require_once 'ArrayShapes.php';

class Foo
{
    /**
     * @param array<ArrayShapes::BAR> $barArray
     * @return void
     */
    public function doSomething(array $barArray): void
    {
        $expectedKeys = array_keys(ArrayShapes::BAR);
        foreach ($expectedKeys as $key) {
            // ...
        }
    }
}

在 PHPStan 配置(通常是 phpstan.neon 或 phpstan.neon.dist 文件)中,确保包含具有数组形状定义的文件:

includes:
- ArrayShapes.php
© www.soinside.com 2019 - 2024. All rights reserved.