zakirullin / mess
方便的数组相关例程和更好的类型转换
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。
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
响应- 配置
- 等等。