orklah/psalm-strict-numeric-cast

限制 (int) 和 (float) 的使用,仅限于数字字符串

v2.1.0 2023-12-17 19:22 UTC

This package is auto-updated.

Last update: 2024-09-11 20:21:50 UTC


README

这是一个 Psalm 插件,用于限制 (int) 和 (float) 的使用,仅限于数字字符串

安装

$ composer require --dev orklah/psalm-strict-numeric-cast
$ vendor/bin/psalm-plugin enable orklah/psalm-strict-numeric-cast

用法

运行您通常的 Psalm 命令

$ vendor/bin/psalm

说明

此插件旨在避免以下代码

function a(string $potential_int){
    $int = (int) $potential_int;
    //...
}

这种转换是在可能具有任何值的字符串上执行的,从静态分析的角度来看。

可以通过几种方式解决这个问题,这将迫使您对自己的变量类型有更大的信心。

  • 您可以检查变量确实为数字
function a(string $potential_int){
    if(is_numeric($potential_int)){
        $int = (int) $potential_int;
    }
    else{
        //throw
    }
    //...
}
function a(string $potential_int){
    Assert::numeric($potential_int);
    $int = (int) $potential_int;
    //...
}
  • 您可以让 psalm 理解该函数期望一个数字(这将迫使您正确地为该函数的任何输入类型化)
/** @psalm-param numeric-string $potential_int */
function a(string $potential_int){
    $int = (int) $potential_int;
    //...
}