Skip to content

Commit

Permalink
Fix length bounds check in Name::slice()
Browse files Browse the repository at this point in the history
The length check did not take into account that there may be a
non-zero offset at this point.

Fixes #875.

(cherry picked from commit 53b907d)
  • Loading branch information
nikic committed Sep 3, 2022
1 parent e55f8c6 commit ff24d1d
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/PhpParser/Node/Name.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public function slice(int $offset, int $length = null) {
$realLength = $numParts - $realOffset;
} else {
$realLength = $length < 0 ? $length + $numParts - $realOffset : $length;
if ($realLength < 0 || $realLength > $numParts) {
if ($realLength < 0 || $realLength > $numParts - $realOffset) {
throw new \OutOfBoundsException(sprintf('Length %d is out of bounds', $length));
}
}
Expand Down
6 changes: 6 additions & 0 deletions test/PhpParser/Node/NameTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@ public function testSliceLengthTooSmall() {
(new Name('foo\bar\baz'))->slice(0, -4);
}

public function testSliceLengthTooLargeWithOffset() {
$this->expectException(\OutOfBoundsException::class);
$this->expectExceptionMessage('Length 3 is out of bounds');
(new Name('foo\bar\baz'))->slice(1, 3);
}

public function testConcat() {
$this->assertEquals(new Name('foo\bar\baz'), Name::concat('foo', 'bar\baz'));
$this->assertEquals(
Expand Down

0 comments on commit ff24d1d

Please sign in to comment.