diff options
| author | Sam Light <sam@lightscale.co.uk> | 2026-06-10 19:00:32 +0100 |
|---|---|---|
| committer | Sam Light <sam@lightscale.co.uk> | 2026-06-10 19:00:32 +0100 |
| commit | dc03419384af6def0b3adb3b976b1f5a3a46cca2 (patch) | |
| tree | 24a829bcd9423d7299e1dcd0e2e762440cf4e351 | |
| parent | 18669556d3f5e20bd92fd7731c774038d8b50e7e (diff) | |
Make route from route string
| -rw-r--r-- | src/PathSegment.php | 16 | ||||
| -rw-r--r-- | tests/Unit/PathSegmentTest.php | 14 |
2 files changed, 29 insertions, 1 deletions
diff --git a/src/PathSegment.php b/src/PathSegment.php index 9337fa1..c2231da 100644 --- a/src/PathSegment.php +++ b/src/PathSegment.php @@ -6,6 +6,7 @@ namespace Lightscale\Router; use Lightscale\Router\Enums\HttpMethod; use Lightscale\Router\Enums\PathSegmentType; +use Lightscale\Router\Exceptions\MissingParameterException; class PathSegment { @@ -19,7 +20,7 @@ class PathSegment protected ?self $parent = null; - public function __construct( + final public function __construct( protected ?string $value = null, protected PathSegmentType $type = PathSegmentType::Raw, ) { @@ -28,6 +29,19 @@ class PathSegment } } + public static function makeFromRouteString(string $value): static + { + $type = PathSegmentType::Parameter; + $regex = $type->routeMatchRegex(); + if (preg_match($regex, $value, $matches) === 1) { + $value = $matches[1]; + } + else { + $type = PathSegmentType::Raw; + } + return new static($value, $type); + } + public function getContent(): string { return match ($this->type) { diff --git a/tests/Unit/PathSegmentTest.php b/tests/Unit/PathSegmentTest.php index 29abb8c..0606b75 100644 --- a/tests/Unit/PathSegmentTest.php +++ b/tests/Unit/PathSegmentTest.php @@ -56,6 +56,20 @@ it('gets type :dataset', function (PathSegmentType $type) { } }); +it('is made from route string :dataset', function (string $v, PathSegmentType $type) { + $seg = PathSegment::makeFromRouteString($v); + expect($seg->getType())->toBe($type); +})->with([ + $v = '{test-test}' => [$v, PathSegmentType::Parameter], + $v = '{test_test}' => [$v, PathSegmentType::Parameter], + $v = '{testTest}' => [$v, PathSegmentType::Parameter], + $v = '{TestTest}' => [$v, PathSegmentType::Parameter], + $v = '{testTest912}' => [$v, PathSegmentType::Parameter], + $v = 'hello-hello' => [$v, PathSegmentType::Raw], + $v = 'hellohello123' => [$v, PathSegmentType::Raw], + $v = 'hello_hello' => [$v, PathSegmentType::Raw], +]); + it('defaults type to Raw') ->expect(fn () => (new PathSegment('testing'))->getType()) ->toBe(PathSegmentType::Raw); |
