Skip to content

feat: add has method in route collector #103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/router/src/RouteCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,19 @@ public function getNamedRoutes(): array
return $this->namedRoutes;
}

/**
* Check if the given route name exists.
*/
public function has(array|string $name): bool
{
return empty(
array_diff_key(
array_flip(Arr::wrap($name)),
$this->getNamedRoutes()
)
);
}

protected function mergeOptions(array $origin, array $options): array
{
if (isset($origin['as'])) {
Expand Down
6 changes: 6 additions & 0 deletions src/support/src/Facades/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@
* @method static void head(string $route, null|array|callable|string $handler, array $options = [])
* @method static array getData()
* @method static \FastRoute\RouteParser getRouteParser()
* @method static void options(string $route, array|string $handler, array $options = [])
* @method static void match(array $methods, string $route, array|string $handler, array $options = [])
* @method static void any(string $route, array|string $handler, array $options = [])
* @method static array getNamedRoutes()
* @method static bool has(array|string $name)
*
* @see \Hypervel\Router\Router
* @see \Hypervel\Router\RouteCollector
*/
class Route extends Facade
{
Expand Down
15 changes: 15 additions & 0 deletions tests/Router/RouteCollectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,4 +283,19 @@ public function testCallableHandler()
$data = $collector->getData()[0];
$this->assertSame(['class', 'method'], $data['GET']['/']->callback);
}

public function testHasNamedRoute()
{
$parser = new Std();
$generator = new DataGenerator();
$collector = new RouteCollector($parser, $generator);

$collector->get('/', 'Handler::Get', ['as' => 'foo']);
$collector->post('/', 'Handler::Post', ['as' => 'bar']);

$this->assertTrue($collector->has('foo'));
$this->assertTrue($collector->has(['foo', 'bar']));
$this->assertFalse($collector->has(['foo', 'baz']));
$this->assertFalse($collector->has('nonexistent'));
}
}