Skip to content

Commit 167443a

Browse files
marcioAlmadaMarcio Almada de Toledo
authored andcommitted
add Ast::tokens and Ast::flatten + tests
Ast::tokens is yet another casting method and returns an array of all tokens within the ast. Nested Ast still produces a flat array of tokens. Ast::flatten behaves the same as Ast::tokens except it returns an Ast instance
1 parent a2329f8 commit 167443a

2 files changed

Lines changed: 39 additions & 2 deletions

File tree

src/Ast.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,14 @@ function token() {
7171
$this->failCasting(Token::class);
7272
}
7373

74+
function tokens() {
75+
$tokens = [];
76+
$exposed = $this->array();
77+
array_walk_recursive($exposed, function($t) use(&$tokens){ if($t instanceof Token) $tokens[] = $t; });
78+
79+
return $tokens;
80+
}
81+
7482
function null() {
7583
if (\is_null($this->ast)) return $this->ast;
7684

@@ -104,7 +112,11 @@ function list() {
104112
$isAssociative = \count(array_filter(array_keys($array), 'is_string')) > 0;
105113

106114
foreach ($array as $label => $value)
107-
yield new Ast(($isAssociative ? $label : null), $value);
115+
yield new self(($isAssociative ? $label : null), $value);
116+
}
117+
118+
function flatten() : self {
119+
return new self($this->label, $this->tokens());
108120
}
109121

110122
function append(self $ast) : self {

tests/AstTest.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ function providerForTestAstCast() {
5757
['* some string', 'string', 'foo'],
5858
['* some array', 'array', ['foo', 'bar']],
5959
['* some token', 'token', new Token(';')],
60+
['* some tokens', 'tokens', []],
6061
];
6162
}
6263

@@ -70,7 +71,8 @@ function testAstCast(string $path, string $castMethod, $expected) {
7071
'boolean' => true,
7172
'string' => 'foo',
7273
'array' => ['foo', 'bar'],
73-
'token' => new Token(';')
74+
'token' => new Token(';'),
75+
'tokens' => ['deep' => ['inside' => []]],
7476
]
7577
]);
7678

@@ -79,4 +81,27 @@ function testAstCast(string $path, string $castMethod, $expected) {
7981
else
8082
$this->assertEquals($expected, $ast->{$path}->$castMethod());
8183
}
84+
85+
function testAstFlattenning() {
86+
$ast = new Ast(null, [
87+
'deep' => [
88+
'token' => $token1 = new Token(T_STRING, 'foo'),
89+
'deeper' => [
90+
'token' => $token2 = new Token(T_STRING, 'bar'),
91+
],
92+
]
93+
]);
94+
95+
$this->assertEquals([$token1, $token2], $ast->tokens());
96+
97+
$flattened = $ast->flatten();
98+
99+
$this->assertInstanceOf(Ast::class, $flattened);
100+
101+
$this->assertEquals([$token1, $token2], $flattened->tokens());
102+
103+
$this->assertEquals([$token1, $token2], $flattened->unwrap());
104+
105+
$this->assertEquals([$token1, $token2], $flattened->array());
106+
}
82107
}

0 commit comments

Comments
 (0)