orklah/psalm-strict-numeric-cast

Restrict the use of (int) and (float) to numeric-string only

v1.0.0 2020-12-05 09:02 UTC

This package is auto-updated.

Last update: 2021-01-05 21:35:03 UTC


README

A Psalm plugin to restrict the use of (int) and (float) to numeric-string only

Installation:

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

Usage:

Run your usual Psalm command:

$ vendor/bin/psalm

Explanation:

This plugin aims to avoid code like this:

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

This cast is performed on a string that could have any value from a static analysis point of view.

The issue can be resolved in a few ways that will force you to have a better confidence in your variables types.

  • You can check that the variable is indeed numeric:
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;
    //...
}
  • You can make psalm understand that the function expects a numeric (this will force you to correctly type any input to this function):
/** @psalm-param numeric-string $potential_int */
function a(string $potential_int){
    $int = (int) $potential_int;
    //...
}