Skip to content

Bug: URI class - working with segments is really strange #2962

@michalsn

Description

@michalsn

Describe the bug
I think there is a problem in the way that some methods are handling segments right now.
Here is an example:

$uri = new \CodeIgniter\HTTP\URI('http://something.com/hello/there');

// will return ['hello', 'there']
d($uri->getSegments());
// will return 'hello' - ok
d($uri->getSegment(1));
// will return 'there' - ok
d($uri->getSegment(2));
// will return '' - why? it's not there
d($uri->getSegment(3));
// will throw an exception - ok
// not really easy to work with but this is a different story
d($uri->getSegment(4));

Here we go with a really strange part:

$uri = new \CodeIgniter\HTTP\URI('http://something.com/hello/there');

// will return '' - why? it's not there
d($uri->getSegment(3));
// will NOT throw an exception (even if segment 3 is not set)
d($uri->setSegment(4, 'honey'));
// will return '' - that's surprising considering no error when
// we set it a line before
d($uri->getSegment(4));
// will return 'honey'
d($uri->getSegment(3));

Actually I don't think it's very complicated to fix, but the main problem are BC changes. People can already rely on the empty string that is returned in some cases. So the question is how should it be handled.

Also working with getSegment() and throwing an exception when segment is not there is not very easy to work with. So it would be good to have something to surpass this without the need of catching the exception every time. One idea was proposed here: #2952#3005

CodeIgniter 4 version
All versions

Affected module(s)
URI class

Expected behavior

$uri = new \CodeIgniter\HTTP\URI('http://something.com/hello/there');

// should throw an exception
d($uri->getSegment(3));
$uri = new \CodeIgniter\HTTP\URI('http://something.com/hello/there');

// should throw an exception
d($uri->getSegment(3));
// should throw an exception
d($uri->setSegment(4, 'honey'));
// should throw an exception
d($uri->getSegment(4));

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugVerified issues on the current code behavior or pull requests that will fix them

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions