Skip to content

orklah/psalm-strict-numeric-cast

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

psalm-strict-numeric-cast

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;
    //...
}

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages