rikta/value-path

Perform get-operations on a string-notated subvalue of an object or array

0.1.1 2021-09-29 16:36 UTC

This package is auto-updated.

Last update: 2024-04-29 04:47:33 UTC


README

packagist name version php version

license GitHub commit activity open issues closed issues

ci dependabot maintainability score tech debt % maintainability issues

Perform get-operations on a string-notated subvalue of an object or array

Installation

composer require rikta/value-path

No config, no dependency-injection, nothing. Plug&Play!

Usage

  1. Create a ValuePath-instance for a path, e.g. $path = new ValuePath('.contact.phone.0');
  2. Invoke the instance on some data, e.g. $phone = $path($data);

Example

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

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

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

Notation

On top of the "usual" dot-notation for arrays this package also support objects.

The following notations are valid:

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)]");

Set Data

It is planned to provide the feature to set data as well, but right now, while having multiple approaches, I don't have a satisfying concept for the chaining of methods. Properties and arrays are a no-brainer, but as soon as methods come into play the whole topic gets a bit more complicated