theodorejb / polycast
安全地将值转换为 int、float 或字符串
v1.0.0
2015-10-25 19:36 UTC
Requires (Dev)
- phpunit/phpunit: ^4.8
README
提供 safe_int
、safe_float
和 safe_string
函数。如果值可以无损地转换为指定的类型,则这些函数返回 true,否则返回 false。
还包括三个辅助函数:to_int
、to_float
和 to_string
。如果相应的 safe_ 函数返回 true,则这些函数将转换并返回一个值;如果返回 false,则抛出 CastException
异常。
此库最初基于 PHP 7 提议但最终被拒绝的 安全转换函数 RFC 构建。有关更多背景信息,请参阅 PolyCast:PHP 中的安全类型转换库。
可接受的类型转换
safe_int
- 整数
- 浮点数,没有余数,介于
PHP_INT_MIN
和PHP_INT_MAX
之间 - 字符串,可带有可选的正负号,没有前导零,包含数字 0-9,且值介于
PHP_INT_MIN
和PHP_INT_MAX
之间。
safe_float
- 浮点数
- 整数
- 符合在 https://php.ac.cn/manual/en/language.types.float.php 中描述的格式的字符串。
safe_string
- 字符串
- 整数
- 浮点数
- 具有
__toString
方法的对象
safe_ 函数在传递 null
、true
或 false
、数组、资源或对象(对于传递给 safe_string
的具有 __toString
方法的对象除外)时始终返回 false。
通过 Composer 安装
composer require theodorejb/polycast
使用示例
输入验证
use function theodorejb\polycast\{ safe_int, safe_float, safe_string }; if (!safe_string($_POST['name'])) { echo 'Name must be a string'; } elseif (!safe_int($_POST['quantity'])) { echo 'Quantity must be an integer'; } elseif (!safe_float($_POST['price'])) { echo 'Price must be a number'; } else { addProduct($_POST['name'], (int)$_POST['quantity'], (float)$_POST['price']); } function addProduct(string $name, int $quantity, float $price) { // ... a database query would go here }
安全类型转换
use theodorejb\polycast; try { $totalRevenue = 0.0; $totalTransactions = 0; foreach ($csvRows as $row) { $totalRevenue += polycast\to_float($row['monthly_revenue']); $totalTransactions += polycast\to_int($row['monthly_transactions']); } // do something with totals } catch (polycast\CastException $e) { echo "Error: " . $e->getMessage(); var_dump($e->getTrace()); }
作者
Theodore Brown
https://theodorejb.me
许可
MIT