zakirullin / typed-accessor
便捷的数组相关例程和更好的类型转换
0.8.5
2024-09-10 06:08 UTC
Requires
- php: ^7.2|^8.0
Requires (Dev)
- composer/xdebug-handler: ^1.4|2.0
- infection/infection: ^0.15|^0.20|^0.27
- phpunit/phpunit: ^8.0|^9.0
- sanmai/pipeline: 5.2.1
- symfony/string: ^5.4.43
- vimeo/psalm: 4.16.1|5.*
README
在我们的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's slides。
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
响应- 配置
- 等等。