Skip to content

Commit 15ea7cf

Browse files
New: Uri pathSegments() helper method (#55250)
* Added `pathSegments` helper function on the `Uri` class * Added doc block * pint * Refactored to return the segments as a collection instead of just an array * add more tests * dont use helper --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent f8c4d57 commit 15ea7cf

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/Illuminate/Support/Uri.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,18 @@ public function path(): ?string
152152
return $path === '' ? '/' : $path;
153153
}
154154

155+
/**
156+
* Get the URI's path segments.
157+
*
158+
* Empty or missing paths are returned as an empty collection.
159+
*/
160+
public function pathSegments(): Collection
161+
{
162+
$path = $this->path();
163+
164+
return $path === '/' ? new Collection : new Collection(explode('/', $path));
165+
}
166+
155167
/**
156168
* Get the URI's query string.
157169
*/

tests/Support/SupportUriTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,28 @@ public function test_with_query_prevents_empty_query_string()
196196
$this->assertEquals('https://laravel.com', (string) $uri);
197197
$this->assertEquals('https://laravel.com', (string) $uri->withQuery([]));
198198
}
199+
200+
public function test_path_segments()
201+
{
202+
$uri = Uri::of('https://laravel.com');
203+
204+
$this->assertEquals([], $uri->pathSegments()->toArray());
205+
206+
$uri = Uri::of('https://laravel.com/one/two/three');
207+
208+
$this->assertEquals(['one', 'two', 'three'], $uri->pathSegments()->toArray());
209+
$this->assertEquals('one', $uri->pathSegments()->first());
210+
211+
$uri = Uri::of('https://laravel.com/one/two/three?foo=bar');
212+
213+
$this->assertEquals(3, $uri->pathSegments()->count());
214+
215+
$uri = Uri::of('https://laravel.com/one/two/three/?foo=bar');
216+
217+
$this->assertEquals(3, $uri->pathSegments()->count());
218+
219+
$uri = Uri::of('https://laravel.com/one/two/three/#foo=bar');
220+
221+
$this->assertEquals(3, $uri->pathSegments()->count());
222+
}
199223
}

0 commit comments

Comments
 (0)