From 53b907d40533c27535a0cf60cc9c38305700ff0e Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Sun, 28 Aug 2022 14:55:57 +0200 Subject: [PATCH] Fix length bounds check in Name::slice() The length check did not take into account that there may be a non-zero offset at this point. Fixes #875. --- lib/PhpParser/Node/Name.php | 2 +- test/PhpParser/Node/NameTest.php | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/PhpParser/Node/Name.php b/lib/PhpParser/Node/Name.php index 6f23b12e00..cec304eb0d 100644 --- a/lib/PhpParser/Node/Name.php +++ b/lib/PhpParser/Node/Name.php @@ -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)); } } diff --git a/test/PhpParser/Node/NameTest.php b/test/PhpParser/Node/NameTest.php index 5e69ebba3c..5329e2fb1a 100644 --- a/test/PhpParser/Node/NameTest.php +++ b/test/PhpParser/Node/NameTest.php @@ -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(