Skip to content

Commit be9262a

Browse files
committed
fix: URI::setSegment() accepts the last +2 segment without Exception
1 parent c53aef0 commit be9262a

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

system/HTTP/URI.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -562,9 +562,9 @@ public function getSegment(int $number, string $default = ''): string
562562
*/
563563
public function setSegment(int $number, $value)
564564
{
565-
// The segment should treat the array as 1-based for the user
566-
// but we still have to deal with a zero-based array.
567-
$number--;
565+
if ($number < 1) {
566+
throw HTTPException::forURISegmentOutOfRange($number);
567+
}
568568

569569
if ($number > count($this->segments) + 1) {
570570
if ($this->silent) {
@@ -574,6 +574,10 @@ public function setSegment(int $number, $value)
574574
throw HTTPException::forURISegmentOutOfRange($number);
575575
}
576576

577+
// The segment should treat the array as 1-based for the user
578+
// but we still have to deal with a zero-based array.
579+
$number--;
580+
577581
$this->segments[$number] = $value;
578582
$this->refreshPath();
579583

tests/system/HTTP/URITest.php

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -808,32 +808,37 @@ public function testSetSegment()
808808
$this->assertSame('foo/banana/baz', $uri->getPath());
809809
}
810810

811-
public function testSetSegmentFallback()
811+
public function testSetSegmentNewOne()
812812
{
813813
$base = 'http://example.com';
814+
$uri = new URI($base);
814815

815-
$uri = new URI($base);
816+
// Can set the next segment.
816817
$uri->setSegment(1, 'first');
817-
$uri->setSegment(3, 'third');
818+
// Can set the next segment.
819+
$uri->setSegment(2, 'third');
818820

819821
$this->assertSame('first/third', $uri->getPath());
820822

823+
// Can replace the existing segment.
821824
$uri->setSegment(2, 'second');
822825

823826
$this->assertSame('first/second', $uri->getPath());
824827

828+
// Can set the next segment.
825829
$uri->setSegment(3, 'third');
826830

827831
$this->assertSame('first/second/third', $uri->getPath());
828832

829-
$uri->setSegment(5, 'fifth');
833+
// Can set the next segment.
834+
$uri->setSegment(4, 'fourth');
830835

831-
$this->assertSame('first/second/third/fifth', $uri->getPath());
836+
$this->assertSame('first/second/third/fourth', $uri->getPath());
832837

833-
// sixth or seventh was not set
838+
// Cannot set the next next segment.
834839
$this->expectException(HTTPException::class);
835840

836-
$uri->setSegment(8, 'eighth');
841+
$uri->setSegment(6, 'eighth');
837842
}
838843

839844
public function testSetBadSegment()

0 commit comments

Comments
 (0)