0

我已经习惯使用 psalm,但我遇到了一个问题。我已经在 C# 中有这个结构,它对我有用。我真的不明白如何使用 psalm 解决这个问题。

我有一个ContextInterface和另一个实现它。

interface ContextInterface { public function getProductId(): int; }
interface SingleContextInterface extends ContextInterface { public function getWidth(): int; }

此外,我还有他们的策略界面。

/**
 * @template-covariant T as ContextInterface
 * @psalm-immutable
 */
interface CalculatorInterface
{
    /**
     * @psalm-param T $context
     */
    public function getPrice(ContextInterface $context): int;
}

/**
 * @template T as SingleContextInterface
 * @template-extends CalculatorInterface<T>
 * @psalm-immutable
 */
interface SingleDimensionalPriceCalculator extends CalculatorInterface { }

还有一个实现接口的类:

/**
 * @template T as SingleContextInterface
 * @template-implements SingleDimensionalPriceCalculator<T>
 * @psalm-immutable
 */
class SingleDimensionCalculator implements SingleDimensionalPriceCalculator
{
    /**
     * @psalm-param SingleContextInterface $context
     */ 
    public function getPrice(ContextInterface $context): int
    {
        $context->getWidth();
        return 1;
    }
    
}

对于getWidth()方法调用,我收到以下错误:

ERROR: ImpureMethodCall - 37:19 - Cannot call an possibly-mutating method SingleContextInterface::getWidth from a mutation-free context

psalm.dev上的示例

当然真实案例更复杂,包含更多接口。

4

1 回答 1

0

我想,问题在于我将模板标记CalculatorInterface为协变。我可以在没有协变的情况下扩展它。

psalm.dev上的示例

于 2021-06-11T07:46:16.463 回答