Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Created February 26, 2021 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMorel/fdbf9bf882870a39300fa4b1b75af626 to your computer and use it in GitHub Desktop.
Save BenMorel/fdbf9bf882870a39300fa4b1b75af626 to your computer and use it in GitHub Desktop.
Safe casting to int (WIP)
<?php
final class SafeCast
{
/**
* Converts the given variable to an integer.
*
* Allowed types are int, float and string.
*
* - int values are returned as is;
* - floats must have an exact int equivalent;
* - strings must have digits only, and an optional minus sign, and must not overflow an integer.
*
* All other types throw an exception.
*
* @param mixed $value
*
* @return int
*
* @throws SafeCastException
*/
public static function toInt($value): int
{
if (is_int($value)) {
return $value;
}
if (is_float($value)) {
$int = (int) $value;
if ($value !== (float) $int) {
throw new SafeCastException(sprintf(
'The given floating-point value (%s) does not have an exact integer equivalent.',
(string) $value
));
}
return $int;
}
if (is_string($value)) {
if (preg_match('/^-?[0-9]+$/', $value) !== 1) {
throw new SafeCastException(sprintf(
'The given string %s does not represent a valid integer value.',
var_export($value, true)
));
}
$int = (int) $value;
if ($value !== (string) $int) {
throw new SafeCastException(sprintf(
'The given string %s overflows an integer.',
var_export($value, true)
));
}
return $int;
}
throw new SafeCastException(sprintf(
'The type %s cannot be converted to an integer.',
gettype($value)
));
}
}
<?php
final class SafeCastException extends Exception
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment