1

鉴于我的课

<?php
declare(strict_types=1);

use Illuminate\Support\Collection;
use stdClass;

class PhpstanIssue
{
    /**
     * @param Collection<Collection<stdClass>> $collection
     *
     * @return Collection<Foo>
     */
    public function whyDoesThisFail(Collection $collection): Collection
    {
        return $collection
            ->flatten() // Collection<stdClass>
            ->map(static function (\stdClass $std): ?Foo {
                return Foo::get($std);
            }) // should now be Collection<?Foo>
            ->filter(); // should now be Collection<Foo>
    }
}

我很困惑为什么 phpstan (0.12.64) 会失败:

18: [ERROR] Method PhpstanIssue::whyDoesThisFail() should return
Illuminate\Support\Collection&iterable<Foo> but returns 
Illuminate\Support\Collection&iterable<Illuminate\Support\Collection&iterable<stdClass>>. (phpstan)

为什么 phpstan 不能推断出这个管道的正确结果类型?如何让 phpstan 理解管道?


我可以验证我的代码在 phpunit 测试用例中是否有效:

class MyCodeWorks extends TestCase
{
    public function testPipeline()
    {
        $result = (new PhpstanIssue())->whyDoesThisFail(
            new Collection(
                [
                    new Collection([new \stdClass(), new \stdClass()]),
                    new Collection([new \stdClass()]),
                ]
            )
        );

        self::assertCount(3, $result);
        foreach ($result as $item) {
            self::assertInstanceOf(Foo::class, $item);
        }
    }
}

将通过。


为了这个问题,我Foo只是一个虚拟班级。唯一相关的是它需要一个stdClass实例并将其转换为一个实例?Foo

class Foo
{
    public static function get(\stdClass $std): ?Foo
    {
        // @phpstan-ignore-next-line
        return (bool) $std ? new static() : null;
    }
}

4

1 回答 1

2

Illuminate\Support\Collection类本身不是通用的。所以Collection<Foo>写错了。这会导致错误消息,例如Illuminate\Support\Collection&iterable<Illuminate\Support\Collection&iterable<stdClass>>

你有两个选择:

  1. 安装拉拉斯坦。这是 Laravel 的 PHPStan 扩展。它有使类通用的存根文件。Illuminate\Support\Collection

  2. 或者,如果您只是使用illuminate/collections没有完整 Laravel 应用程序的独立包,您可以编写自己的存根文件。来自PHPStan 文档

...您可以使用正确的 PHPDoc 编写存根文件。它就像源代码,但 PHPStan 只从中读取 PHPDocs。因此命名空间和类/接口/特征/方法/函数名称必须与您描述的原始源匹配。但是方法体可以留空,PHPStan 只对 PHPDocs 感兴趣。

对于您的示例,以下存根文件应该足够了:

<?php

namespace Illuminate\Support;

/**
 * @template TKey
 * @template TValue
 * @implements \ArrayAccess<TKey, TValue>
 * @implements Enumerable<TKey, TValue>
 */
class Collection implements \ArrayAccess, Enumerable
{
    /**
     * @template TReturn
     * @param callable(TValue, TKey): TReturn $callable
     * @return static<TKey, TReturn>
     */
    public function map($callable) {}
}
于 2021-07-27T18:33:57.183 回答