rikta/value-path

对一个对象或数组字符串表示的子值的get操作

0.1.1 2021-09-29 16:36 UTC

This package is auto-updated.

Last update: 2024-09-29 05:56:55 UTC


README

packagist name version php version

license GitHub commit activity open issues closed issues

ci dependabot maintainability score tech debt % maintainability issues

对一个对象或数组字符串表示的子值的get操作

安装

composer require rikta/value-path

无配置,无依赖注入,什么都没有。即插即用!

用法

  1. 为路径创建一个ValuePath实例,例如 $path = new ValuePath('.contact.phone.0');
  2. 在数据上调用实例,例如 $phone = $path($data);

示例

$data = [
    [
        'name' => 'John Doe',
        'contact' => [
            'phone' => [
                '+49301234567'
            ]
        ]
    ]
];

$path = new Rikta\ValuePath\ValuePath('.contact.phone.0');
$phone = $path($data);

\PHPUnit\Framework\assertEquals('+49301234567', $phone);

表示法

除了“常规”的数组点表示法之外,这个包还支持对象。

以下表示法是有效的

new Rikta\ValuePath\ValuePath('.something'); // = $value['something']
new Rikta\ValuePath\ValuePath('.0'); // = $value[0]
new Rikta\ValuePath\ValuePath('["something"]'); // = $value['something']
new Rikta\ValuePath\ValuePath('->something'); // = $value->something
new Rikta\ValuePath\ValuePath('->something("a", "b", 1)]'); // = $value->something("a", "b", 1)

// it's also possible to chain the notations to get some deeply nested data
new Rikta\ValuePath\ValuePath('.something["somethingElse"]->someOtherThing->sth("a", "b")]');

// ' and " are interchangeable
new Rikta\ValuePath\ValuePath(".something['somethingElse']->someOtherThing->sth('a', 'b', 1)]");

设置数据

计划提供设置数据的功能,但现在,尽管有多种方法,但我还没有一个令人满意的链式方法的概念。属性和数组是显而易见的,但一旦涉及到方法,整个话题就变得更加复杂。