orklah/psalm-strict-numeric-cast

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

Installs: 1 808

Dependents: 0

Suggesters: 0

Security: 0

Stars: 4

Watchers: 2

Forks: 1

Open Issues: 0

Type:psalm-plugin

v1.0.1 2021-09-13 10:47 UTC

This package is auto-updated.

Last update: 2021-09-13 10:48:00 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;
    //...
}