Skip to content

Commit 1b1f91c

Browse files
authored
[TASK] Add ParserState::consumeIfComes method (#1422)
This, when used (in various places), will be more efficient than doing a `peek()` followed by a `consume()`.
1 parent 42502fd commit 1b1f91c

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/Parsing/ParserState.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,27 @@ public function consume($value = 1): string
279279
return $result;
280280
}
281281

282+
/**
283+
* If the possibly-expected next content is next, consume it.
284+
*
285+
* @param non-empty-string $nextContent
286+
*
287+
* @return bool whether the possibly-expected content was found and consumed
288+
*/
289+
public function consumeIfComes(string $nextContent): bool
290+
{
291+
$length = $this->strlen($nextContent);
292+
if (!$this->streql($this->substr($this->currentPosition, $length), $nextContent)) {
293+
return false;
294+
}
295+
296+
$numberOfLines = \substr_count($nextContent, "\n");
297+
$this->lineNumber += $numberOfLines;
298+
$this->currentPosition += $this->strlen($nextContent);
299+
300+
return true;
301+
}
302+
282303
/**
283304
* @param string $expression
284305
* @param int<1, max>|null $maximumLength

tests/Unit/Parsing/ParserStateTest.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,64 @@ static function (Comment $comment): string {
9797
);
9898
self::assertSame($expectedComments, $commentsAsText);
9999
}
100+
101+
/**
102+
* @test
103+
*/
104+
public function consumeIfComesComsumesMatchingContent(): void
105+
{
106+
$subject = new ParserState('abc', Settings::create());
107+
108+
$subject->consumeIfComes('ab');
109+
110+
self::assertSame('c', $subject->peek());
111+
}
112+
113+
/**
114+
* @test
115+
*/
116+
public function consumeIfComesDoesNotComsumeNonMatchingContent(): void
117+
{
118+
$subject = new ParserState('a', Settings::create());
119+
120+
$subject->consumeIfComes('x');
121+
122+
self::assertSame('a', $subject->peek());
123+
}
124+
125+
/**
126+
* @test
127+
*/
128+
public function consumeIfComesReturnsTrueIfContentConsumed(): void
129+
{
130+
$subject = new ParserState('abc', Settings::create());
131+
132+
$result = $subject->consumeIfComes('ab');
133+
134+
self::assertTrue($result);
135+
}
136+
137+
/**
138+
* @test
139+
*/
140+
public function consumeIfComesReturnsFalseIfContentNotConsumed(): void
141+
{
142+
$subject = new ParserState('a', Settings::create());
143+
144+
$result = $subject->consumeIfComes('x');
145+
146+
self::assertFalse($result);
147+
}
148+
149+
/**
150+
* @test
151+
*/
152+
public function consumeIfComesUpdatesLineNumber(): void
153+
{
154+
$subject = new ParserState("\n", Settings::create());
155+
156+
$subject->consumeIfComes("\n");
157+
158+
self::assertSame(2, $subject->currentLine());
159+
}
100160
}

0 commit comments

Comments
 (0)