smoren / nested-accessor
Accessor for getting and setting values of nested data structures (arrays or objects)
Installs: 1 013
Dependents: 2
Suggesters: 0
Security: 0
Stars: 10
Watchers: 2
Forks: 3
Open Issues: 0
Requires
- php: >=7.4.0
- smoren/extended-exceptions: ^1.0.0
- smoren/type-tools: ^2.0.0
Requires (Dev)
- codeception/codeception: ^4.2.1
- codeception/module-asserts: ^2.0
- php-coveralls/php-coveralls: ^2.0
- phpstan/phpstan: ^1.8
- squizlabs/php_codesniffer: 3.*
README
Accessor for getting and setting values of nested data structures (arrays or objects).
How to install to your project
composer require smoren/nested-accessor
Unit testing
composer install
composer test-init
composer test
Usage
NestedAccessor
use Smoren\NestedAccessor\Components\NestedAccessor; $source = [ 'data' => [ 'id' => 1, 'name' => 'Countries classifier', 'extra' => null, 'country_names' => ['Russia', 'Belarus'], ], 'countries' => [ [ 'name' => 'Russia', 'cities' => [ [ 'name' => 'Moscow', 'extra' => [ 'codes' => [ ['value' => 7495], ['value' => 7499], ], ], ], [ 'name' => 'Petersburg', 'extra' => [ 'codes' => [ ['value' => 7812], ], ], ], ], ], [ 'name' => 'Belarus', 'cities' => [ [ 'name' => 'Minsk', 'extra' => [ 'codes' => [ ['value' => 375017], ], ], ], ], ], ] ]; $accessor = new NestedAccessor($input); echo $accessor->get('data.name'); // 'Countries classifier' print_r($accessor->get('countries.name')); // ['Russia', 'Belarus'] print_r($accessor->get('countries.cities.name')); // ['Moscow', 'Petersburg', 'Minsk'] print_r($accessor->get('countries.cities.extra.codes.value')); // [7495, 7499, 7812, 375017] var_dump($accessor->isset('data.name')); // true var_dump($accessor->isset('data.extra')); // false var_dump($accessor->isset('this.path.not.exist')); // false var_dump($accessor->exist('data.name')); // true var_dump($accessor->exist('data.extra')); // true var_dump($accessor->exist('this.path.not.exist')); // false $accessor->set('data.name', 'New name'); echo $accessor->get('data.name'); // 'New name' $accessor->append('data.country_names', 'Mexico'); echo $accessor->get('data.country_names'); // ['Russia', 'Belarus', 'Mexico'] $accessor->delete('data.name'); var_dump($accessor->exist('data.name')); // false