gsteel/dot

从嵌套数组中检索类型化值的实用工具

1.7.0 2023-09-18 22:36 UTC

README

Continuous Integration codecov psalm coverage psalm level

从深度嵌套数组中检索强类型值。

此库不会设置任何值或以任何方式操作数据结构。它仅用于检索信息。

用法

提供一个类型化值或抛出异常

use GSteel\Dot;
use GSteel\MissingKey;
use GSteel\InvalidValue;
use stdClass;

$data = [
    'data' => [
        'float' => 1.23,
        'integer' => 42,
        'bool' => true,
        'string' => 'Goats',
        'callable' => static fn (): string => 'Hey!',
        'instance' => new stdClass(),
        'mixed' => null,
        'array' => ['a' => 'b'],
    ],
];

$value = Dot::float('data.float', $data); // 1.23
$value = Dot::integer('data.integer', $data); // 42
$value = Dot::bool('data.bool', $data); // true
$value = Dot::string('data.string', $data); // Goats
$value = Dot::callable('data.callable', $data); // function
$value = Dot::instanceOf('data.instance', $data, stdClass::class); // object<stdClass>
$value = Dot::valueAt('data.mixed'); // mixed
$value = Dot::array('data.array'); // ['a' => 'b']

$value = Dot::string('nope.not-there', $data); // Exception: MissingKey
$value = Dot::string('data.float', $data); // Exception: InvalidValue

检索一个类型化值或null

所有方法都有一致的名字,例如 floatOrNullboolOrNull 等。

use GSteel\Dot;

$data = ['a' => ['b' => ['c' => 'foo']]];

$value = Dot::stringOrNull('a.b.c', $data); // "foo"
$value = Dot::stringOrNull('a.b.nope', $data); // null
$value = Dot::integerOrNull('a.b.c', $data); // null

检索类型化存在值或回退到给定默认值

use GSteel\Dot;

$data = ['a' => ['b' => ['c' => 'foo']]];

$value = Dot::stringDefault('a.b.c', $data, 'bar'); // "foo"
$value = Dot::stringDefault('a.b.nope', $data, 'bar'); // "bar"
$value = Dot::integerDefault('a.b.c', $data, 42); // 42

数组键中的点符号?

use GSteel\Dot;

$data = [
    'data' => [
        'dot.here' => 'value',
        'slash/dot.' => 'value',
        'array/' => [
            'd.o.t.s' => [
                'p|pes' => 'value',
            ],      
        ],
    ],
];

$value = Dot::string('data/dot.here', $data, '/'); // "value"
$value = Dot::string('data|slash/dot.', $data, '|'); // "value"
$value = Dot::string('data*array/*d.o.t.s*p|pes', $data, '*'); // "value"

为什么?

作为一个大多数时候都很满意的 psalm 用户,当你从你的依赖注入容器中检索到配置数组,并告诉 Psalm 其中某个可能的字符串值为 null 时,这真的很无聊。例如

use GSteel\Dot;

$config = $container->get('config');

$connectionParams = $config['doctrine']['connection']['params'] ?? [];
// 👆 Psalm has no idea what that is.

// Alternatively…

$params = [
    'host' => Dot::stringDefault('doctrine.connection.params.host', $config, 'localhost'),
    'port' => Dot::integerDefault('doctrine.connection.params.port', $config, 1234),
];

这不是以前已经做过的事情吗?

是的。这里有几个