orklah/psalm-strict-numeric-cast

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

Installs: 46 686

Dependents: 1

Suggesters: 0

Security: 0

Stars: 8

Watchers: 3

Forks: 2

Open Issues: 0

Type:psalm-plugin

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

This package is auto-updated.

Last update: 2024-12-11 20:49:46 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;
    //...
}