PhpStorm:有没有办法使用内联 PHPDoc 注释在 return 语句上强制执行类型?

PhpStorm: Is there a way to enforce a type on the return statement using an inline PHPDoc annotation?

考虑以下代码:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Car extends Model
{
    public static function getTheFirstCar(string $color): ?self
    {
        /** @var ?self */ // <-- Doesn't apply! Is there any alternative?
        return (new self())->newQuery()->firstWhere('color', '=', $color);
    }
}

代码运行正常;然而 PhpStorm 抱怨:

Return value is expected to be 'Car|null',
'\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model' returned

将表达式的结果赋给带注释的变量解决了警告,但引入了“冗余”变量!

/** @var ?self $redundant */
$redundant = (new self())->newQuery()->firstWhere('color', '=', $color);
return $redundant;

那么,在 PhpStorm 中有没有一种方法可以在不引入冗余变量或指定所有预期 return 类型?

您需要将文档块添加到您的 class:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
 * Class Car
 * @package App\Models
 *
 * @method self|Builder newQuery()
 * @method ?self firstWhere($column, $operator = null, $value = null, $boolean = 'and')
 */
class Car extends Model
{
    public static function getTheFirstCar(string $color): ?self
    {
        return (new self())->newQuery()->firstWhere('color', '=', $color);
    }
}

您可以通过在语句前添加 @noinspection PhpIncompatibleReturnTypeInspection 注释来抑制此警告。
我个人不会这样做,但这是对您有关如何“强制执行”return 类型并禁止警告 afaik 的问题的唯一答案。

    /** @noinspection PhpIncompatibleReturnTypeInspection */
    return (new self())->newQuery()->where('color', '=', $color)->first();

如果您决定尊重警告,那么这可能是它的原因和解决方案: newQuery() 将在模型 table(最有可能:cars)上创建一个新查询,而不设置适当的模型(Car)。
在内部,您现在 运行 是 cars 上的一个简单查询。因此,您将收到适当的记录,但不会是 Car 的实例,而是 Model 的实例。因此 PhpStorm 期望这里有多个额外的 return 类型,并在您的语句中打印此警告,因为它不同于方法 return 类型 ?self.

快速解决方案是将 newQuery() 更改为 newModelQuery()。这将创建一个新查询并在创建的查询上设置模型 Car 和 return 适当的实例或 null

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    public static function getTheFirstCar(string $color): ?self
    {
        return (new self())->newModelQuery()->firstWhere('color', '=', $color);
        // I'd use this statement though:
        // return self::where('color', '=', $color)->first();
    }
}