Last active
October 8, 2024 16:52
-
-
Save BenMorel/fdbf9bf882870a39300fa4b1b75af626 to your computer and use it in GitHub Desktop.
Safe casting to int (WIP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(mixed $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) | |
)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class SafeCastException extends Exception | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment