Skip to content
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

Adding filter() method to Klein to use for middleware such as Auth #317

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
composer.lock
vendor/

# Mac OS
.DS_Store

# Auto-generated documentation directory (phpDocumentor)
docs/

Expand Down
38 changes: 38 additions & 0 deletions src/Klein/Klein.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,44 @@ public function respond($method, $path = '*', $callback = null)
return $route;
}

/**
* Middleware alternative for respond() that doesn't count as a
* matched route.
*
* <code>
* $router = new Klein();
*
* $router->filter( function() {
* echo 'this works';
* });
* $router->filter( '/endpoint', function() {
* echo 'this also works';
* });
* $router->filter( 'POST', '/endpoint', function() {
* echo 'this also works!!!!';
* });
* </code>
*
* @param string $method
* @param string $path
* @param callable $callback
* @return Route
*/
public function filter($method, $path = '*', $callback = null)
{
// Get the arguments in a very loose format
extract(
$this->parseLooseArgumentOrder(func_get_args()),
EXTR_OVERWRITE
);

$route = $this->route_factory->build($callback, $path, $method, false);

$this->routes->add($route);

return $route;
}

/**
* Collect a set of routes under a common namespace
*
Expand Down
2 changes: 1 addition & 1 deletion src/Klein/RouteFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public function build($callback, $path = null, $method = null, $count_match = tr
$callback,
$this->preprocessPathString($path),
$method,
$this->shouldPathStringCauseRouteMatch($path) // Ignore the $count_match boolean that they passed
($this->shouldPathStringCauseRouteMatch($path) && $count_match) // actually pass in the count_match flag
);
}
}