Skip to content

Commit

Permalink
fix: URI::setSegment() accepts the last +2 segment without Exception
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Feb 14, 2023
1 parent c53aef0 commit 5a3ac57
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
10 changes: 7 additions & 3 deletions system/HTTP/URI.php
Original file line number Diff line number Diff line change
Expand Up @@ -562,9 +562,9 @@ public function getSegment(int $number, string $default = ''): string
*/
public function setSegment(int $number, $value)
{
// The segment should treat the array as 1-based for the user
// but we still have to deal with a zero-based array.
$number--;
if ($number < 1) {
throw HTTPException::forURISegmentOutOfRange($number);
}

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

// The segment should treat the array as 1-based for the user
// but we still have to deal with a zero-based array.
$number--;

$this->segments[$number] = $value;
$this->refreshPath();

Expand Down
19 changes: 12 additions & 7 deletions tests/system/HTTP/URITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -808,32 +808,37 @@ public function testSetSegment()
$this->assertSame('foo/banana/baz', $uri->getPath());
}

public function testSetSegmentFallback()
public function testSetSegmentNewOne()
{
$base = 'http://example.com';
$uri = new URI($base);

$uri = new URI($base);
// Can set the next segment.
$uri->setSegment(1, 'first');
$uri->setSegment(3, 'third');
// Can set the next segment.
$uri->setSegment(2, 'third');

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

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

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

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

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

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

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

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

$uri->setSegment(8, 'eighth');
$uri->setSegment(6, 'six');
}

public function testSetBadSegment()
Expand Down

0 comments on commit 5a3ac57

Please sign in to comment.