选择性 / 数组读取器
严格类型的数组读取器
2.1.0
2023-09-09 12:35 UTC
Requires
- php: ^8.1
- cakephp/chronos: ^2 || ^3
Requires (Dev)
README
PHP的严格类型数组读取器。
需求
- PHP 8.1+
安装
composer require selective/array-reader
使用
您可以使用 ArrayReader
通过传递路径到 get{type}()
和 find{type}()
方法之一来从多维数组中读取单个值。
每个 get*() / find*()
方法接受一个默认值作为第二个参数。如果路径在原始数组中找不到,则使用默认值作为返回值。
get*()
方法仅返回声明的返回类型。如果没有给出默认值且元素找不到,则抛出异常。
find*()
方法仅返回声明的返回类型或 null
。如果元素找不到,则不会抛出异常。
<?php use Selective\ArrayReader\ArrayReader; $arrayReader = new ArrayReader([ 'key1' => [ 'key2' => [ 'key3' => 'value1', ] ] ]); // Output: value1 echo $arrayReader->getString('key1.key2.key3');
更好的代码质量
使用简单的PHP转换复杂数据时,会使用大量的类型转换和 if
条件等。这会导致非常高的循环复杂度和嵌套深度,从而代码质量低下。
之前:条件:10,路径:512,CRAP分数:10
之后:条件:1,路径:1,CRAP分数:1
类似库
- https://github.com/michaelpetri/typed-input
- https://github.com/codeliner/array-reader
- https://github.com/adbario/php-dot-notation
- https://symfony.ac.cn/doc/current/components/property_access.html
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。