8

考虑以下代码:

<?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 抱怨道:

返回值预计为' Car|null',返回
' '\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model

返回语句上的 PhpStorm PHPDoc 类型注释

将表达式的结果分配给带注释的变量可以解决警告,但会引入“冗余”变量!

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

那么,PhpStorm 中是否有一种方法可以为return语句表达式的值显式地强制执行内联类型注释Car|null,而不引入冗余变量或指定所有预期的返回类型?

4

2 回答 2

8

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

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

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

快速的解决方案是更改newQuery()newModelQuery(). 这将创建一个新查询并Car在创建的查询上设置模型并返回适当的实例或 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();
    }
}
于 2021-03-10T13:17:26.050 回答
0

您需要将 doc 块添加到您的课程中:

<?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);
    }
}
于 2021-03-09T12:23:16.760 回答