方便的数组相关例程和更好的类型转换

0.8.5 2024-09-10 06:08 UTC

This package is auto-updated.

Last update: 2024-09-10 09:33:11 UTC


README

GitHub Build Status Psalm coverage PHP from Packagist Latest Stable Version GitHub commits Software License

我们在PHP项目中遇到了一些问题

  • 不合理的类型转换(PHP的本地实现太"聪明"了)
  • 无意义的转换,如 array => float允许的
  • 与数组一起工作的样板代码(检查 isset(),抛出异常,转换类型等。)

考虑一个例子

$userId = $queryParams['userId'] ?? null;
if ($userId === null) {
    throw ...
}
$userId = (int)$userId;

过于冗长。有什么想法吗?

$userId = (new Mess($queryParams))['userId']->getAsInt();

你可以与API响应/配置等"玩耍"

$mess = new Mess($response);
$book = new Book(
    $mess['title']->getString(),
    $mess['isBestseller']->getBool(),
    $mess['stats']['rating']->getInt(),
    $mess['tags']->getListOfString()
);

泛型支持(与Psalm兼容)

  • getListOfString()
  • getListOfInt()
  • getArrayOfStringToString()
  • getArrayOfStringToBool()
  • 等等。

安装

$ composer require zakirullin/mess

处理混乱

$queryParams = new Mess(['isDeleted' => 'true']);
$queryParams['isDeleted']->getBool(); // UnexpectedTypeException
$queryParams['isDeleted']->getAsBool(); // true

$value = new Mess('25');
$value->getInt(); // UnexpectedTypeException
$value->getAsInt(); // 25
$value->getString(); // '25'

$value = new Mess('25a');
$value->getInt(); // UnexpectedTypeException
$value->getAsInt(); // UncastableValueException

$config = new Mess(['param' => '1']);
$config['a']['b']->getInt(); // MissingKeyException: "MissingKeyException: a.b"
$config['a']['b']->findInt(); // null
$config['param']->getInt(); // UnexpectedTypeException 
$config['param']->getAsInt(); // 1
$config['param']->findInt(); // UnexpectedTypeException
$config['param']->findAsInt(); // 1

正如你可能注意到的,类型转换是在使用 (find|get)As* 方法时执行的。是否难以理解 get*()/find*()?查看Ocramius的精彩幻灯片 Ocramius

Mess中的类型转换相当可预测

'\d+' => int // OK
'buzz12' => int // UncastableValueException
bool => int // UncastableValueException
array => int // UncastableValueException
object => int // UncastableValueException
resource => int // UncastableValueException

相当简单,不是吗?让我们快速失败!

为什么需要那种简单的类型转换?

让我们想象一个这样配置的库

$config = [
    'retries' => 5, // int
    'delay' => 20, // int
]

// Initialization 
$retries = $config['retries'] ?? null;
if ($retries === null) {
    throw new MissingConfigKeyException(...);
}
...
$retries = (int)$retries;
$delay = (int)$delay;

客户端代码

$config => [
    'retries' => [5, 10, 30], // (int)array => 1
    'delay' => true, // (int)bool => 1
]

无论这是误用还是主要更新的结果:系统将继续工作。这是最糟糕的事情。虽然它将继续工作,但不是它应该工作的方式。PHP正尽力让它至少以某种方式工作。

该库在各种场景下都很有用 🚀

  • 反序列化数据
  • 请求 body/query
  • API 响应
  • 配置
  • 等等。