Skip to content

Commit

Permalink
Allow Ast to set nested values
Browse files Browse the repository at this point in the history
```
$ast->{'some deep token'} = new Token(T_STRING, 'patch');
```

Ref: github.com//pull/59
  • Loading branch information
marcioAlmada committed Apr 18, 2019
1 parent 08c6490 commit 58556cc
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Ast.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ function __construct(string $label = '', $ast = []) {
$this->label = $label;
}

function __set($path, $value) {
return $this->set($path, $value);
}

function set($strPath, $value) {
$keys = preg_split('/\s+/', $strPath);

if ([] === $keys) return;

$current = &$this->ast;
foreach ($keys as $key) {
if (!is_array($current)) $current = [];
$current = &$current[$key];
}
$current = $value;
}

function __get($path) {
return $this->get($path);
}
Expand Down
28 changes: 28 additions & 0 deletions tests/AstTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,32 @@ function testAstFlattenning() {

$this->assertEquals([$token1, $token2], $flattened->array());
}

function testAstSet() {
$ast = new Ast('label', [
'deep' => [
'token' => new Token(T_STRING, 'foo'),
'deeper' => [
'tokens' => [0 => new Token(T_STRING, 'bar'), 1 => new Token(T_STRING, 'baz')],
],
],
]);

$ast->set('deep token', $patchedFooToken = new Token(T_STRING, 'patched_foo'));

$ast->{'deep deeper tokens 0'} = $patchedBarToken = new Token(T_STRING, 'patched_bar');
$ast->{'deep deeper tokens 1'} = $patchedBazToken = new Token(T_STRING, 'patched_baz');

$expected = [
'deep' => [
'token' => $patchedFooToken,
'deeper' => [
'tokens' => [0 => $patchedBarToken, 1 => $patchedBazToken],
],
],
];

$this->assertSame($expected, $ast->unwrap());
$this->assertSame($expected, $ast->array());
}
}

0 comments on commit 58556cc

Please sign in to comment.