【问题标题】:Psalm annotation for multiple-type template多类型模板的诗篇注释
【发布时间】:2021-04-11 01:11:27
【问题描述】:

我需要构建一个特征(或与之相关的类),我可以在其上模板化多种类型;我已经尝试过类似以下的方法(也描述了问题;汽车上下文只是为了说明问题,我知道汽车应该是聚合的而不是组合的,但这不是要讨论的问题):

/**
  * @template TyreType of Tyre
  * @template EngineType of Engine
  */
trait Car {
    /**
      * @return TyreType
      */
    public function getTyre(): Tyre {
    }

    /**
      * @return EngineType
      */
    public function getEngine(): Engine{
    }
}

trait SomeCar {
    /**
     * @use Car<AirlessTyre><DieselEngine>
     */
    use Car;

    public function test() {
        $this->getEngine()->dieselSpecificMethod();
    }
}

class Engine{}
class Tyre{}
class DieselEngine extends Engine {
    public function dieselSpecificMethod() {}
}
class AirlessTyre extends Tyre {}

问题是,在 PhpStorm 中,我在 dieselSpecificMethod() 上收到“潜在的多态调用。引擎在其层次结构中没有成员”。

所以我的问题是:

  • psalm 是否支持多种类型的模板,因为我正在尝试实现
  • 我是否遗漏了上面示例中的正确语义?我应该如何注释这个?
  • 还是只是 PhpStorm 的限制

【问题讨论】:

  • 假设类 Engine 为空 - 这是一个正确的警告。您介意将 Engine 和 EngineType 类添加到描述中吗?
  • @Dmitrii - 当然,添加了类结构; EngineType 不是一个类,它是一个类型模板
  • 使用当前设计,我建议暂时禁用此检查。在检查设置中或在突出显示的成员上使用 Alt+Enter > 选择检查快速修复 > 右箭头 > 抑制文件。
  • @Dmitrii 谢谢,但我不是在找那个;如果可能的话,我需要方法自动完成和静态类型检查才能工作
  • 在那种情况下你不应该在 ::getEngine() 中有@return DieselEngine 吗?如果不是 - 我看不出任何分析器如何静态解析它。

标签: php phpstorm psalm-php


【解决方案1】:

Psalm 确实支持多种类型参数。使用它们的正确语法是GenericType&lt;TA, TB&gt;(无法识别您使用的GenericType&lt;TA&gt;&lt;TB&gt;)。解决了这个问题(以及更多抑制,以消除不必要的噪音),这就变成了:

<?php
/**
  * @template TyreType of Tyre
  * @template EngineType of Engine
  */
trait Car {
    /**
      * @return TyreType
      * @psalm-suppress InvalidReturnType
      */
    public function getTyre(): Tyre {
    }

    /**
      * @return EngineType
      * @psalm-suppress InvalidReturnType
      */
    public function getEngine(): Engine{
    }
}

trait SomeCar {
    /**
     * @use Car<AirlessTyre,DieselEngine>
     */
    use Car;

    public function test():void {
        $this->getEngine()->dieselSpecificMethod();
        $this->getEngine()->warp(9);
    }
}

class FordCar { use SomeCar; }

class Engine{}
class Tyre{}
class DieselEngine extends Engine {
    public function dieselSpecificMethod():void {}
}
class WarpEngine extends Engine {
    public function warp(int $speed): void {}
}
class AirlessTyre extends Tyre {}

Psalm 可以告诉你福特当然没有曲速引擎功能:https://psalm.dev/r/31343aafc3。请注意在 @use 注释中引用泛型特征的正确语法。

【讨论】:

  • 谢谢,很好的回复,也让我发笑!我还没有发现关于这方面的 PHPStorm 功能,但至少知道正确的语法是一个很好的起点。 palm在线沙箱也是一个很棒的工具。所以我会扭曲 9 接受这个答案。
猜你喜欢
  • 2021-11-13
  • 2021-11-21
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2011-07-04
  • 2017-10-02
  • 1970-01-01
相关资源
最近更新 更多