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

Support HTTP 405 response code #174

Open
wants to merge 4 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
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,15 @@ $router->get('/cars/(\d+)', 'Car@showProfile');

### Custom 404

The default 404 handler sets a 404 status code and exits. You can override this default 404 handler by using `$router->set404(callable);`
The default 404 handler sets a 404 or 405 status code and exits. You can override this default 404 handler by using `$router->set404(callable);`

```php
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
$router->set404(function($handledByOtherMethod) {
if ($handledByOtherMethod) {
header('HTTP/1.1 405 Method Not Allowed');
} else {
header('HTTP/1.1 404 Not Found');
}
// ... do something special here
});
```
Expand Down
58 changes: 40 additions & 18 deletions src/Bramus/Router/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
*/
class Router
{
/**
* List of all HTTP methods.
*/
const ALL_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'];

/**
* @var array The route patterns and their handling functions
*/
Expand Down Expand Up @@ -70,7 +75,7 @@ public function before($methods, $pattern, $fn)
/**
* Store a route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string|string[] $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
Expand All @@ -79,10 +84,11 @@ public function match($methods, $pattern, $fn)
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;

foreach (explode('|', $methods) as $method) {
$handledMethods = is_array($methods) ? $methods : explode('|', $methods);
foreach (self::ALL_METHODS as $method) {
$this->afterRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
'fn' => in_array($method, $handledMethods, true) ? $fn : null,
);
}
}
Expand All @@ -95,7 +101,7 @@ public function match($methods, $pattern, $fn)
*/
public function all($pattern, $fn)
{
$this->match('GET|POST|PUT|DELETE|OPTIONS|PATCH|HEAD', $pattern, $fn);
$this->match(self::ALL_METHODS, $pattern, $fn);
}

/**
Expand All @@ -106,7 +112,7 @@ public function all($pattern, $fn)
*/
public function get($pattern, $fn)
{
$this->match('GET', $pattern, $fn);
$this->match(['GET'], $pattern, $fn);
}

/**
Expand All @@ -117,7 +123,7 @@ public function get($pattern, $fn)
*/
public function post($pattern, $fn)
{
$this->match('POST', $pattern, $fn);
$this->match(['POST'], $pattern, $fn);
}

/**
Expand All @@ -128,7 +134,7 @@ public function post($pattern, $fn)
*/
public function patch($pattern, $fn)
{
$this->match('PATCH', $pattern, $fn);
$this->match(['PATCH'], $pattern, $fn);
}

/**
Expand All @@ -139,7 +145,7 @@ public function patch($pattern, $fn)
*/
public function delete($pattern, $fn)
{
$this->match('DELETE', $pattern, $fn);
$this->match(['DELETE'], $pattern, $fn);
}

/**
Expand All @@ -150,7 +156,7 @@ public function delete($pattern, $fn)
*/
public function put($pattern, $fn)
{
$this->match('PUT', $pattern, $fn);
$this->match(['PUT'], $pattern, $fn);
}

/**
Expand All @@ -161,7 +167,7 @@ public function put($pattern, $fn)
*/
public function options($pattern, $fn)
{
$this->match('OPTIONS', $pattern, $fn);
$this->match(['OPTIONS'], $pattern, $fn);
}

/**
Expand Down Expand Up @@ -283,13 +289,16 @@ public function run($callback = null)

// Handle all routes
$numHandled = 0;
$numHandledByOtherMethods = 0;
if (isset($this->afterRoutes[$this->requestedMethod])) {
$numHandled = $this->handle($this->afterRoutes[$this->requestedMethod], true);
$handled = $this->handle($this->afterRoutes[$this->requestedMethod], true);
$numHandled = $handled->numHandled;
$numHandledByOtherMethods = $handled->numHandledByOtherMethods;
}

// If no route was handled, trigger the 404 (if any)
if ($numHandled === 0) {
$this->trigger404($this->afterRoutes[$this->requestedMethod]);
$this->trigger404($numHandledByOtherMethods > 0);
} // If a route was handled, perform the finish callback (if any)
else {
if ($callback && is_callable($callback)) {
Expand Down Expand Up @@ -324,9 +333,9 @@ public function set404($match_fn, $fn = null)
/**
* Triggers 404 response
*
* @param string $pattern A route pattern such as /about/system
* @param bool $handledByOtherMethod Whether the match is handled by other method.
*/
public function trigger404($match = null){
public function trigger404($handledByOtherMethod = false){

// Counter to keep track of the number of routes we've handled
$numHandled = 0;
Expand Down Expand Up @@ -362,16 +371,20 @@ public function trigger404($match = null){
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));

$this->invoke($route_callable);
$this->invoke($route_callable, [$handledByOtherMethod]);

++$numHandled;
}
}
}
if (($numHandled == 0) && (isset($this->notFoundCallback['/']))) {
$this->invoke($this->notFoundCallback['/']);
$this->invoke($this->notFoundCallback['/'], [$handledByOtherMethod]);
} elseif ($numHandled == 0) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
if ($handledByOtherMethod) {
header($_SERVER['SERVER_PROTOCOL'] . ' 405 Method Not Allowed');
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
}
}
}

Expand Down Expand Up @@ -407,6 +420,7 @@ private function handle($routes, $quitAfterRun = false)
{
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
$numHandledByOtherMethods = 0;

// The current page URL
$uri = $this->getCurrentUri();
Expand All @@ -419,6 +433,11 @@ private function handle($routes, $quitAfterRun = false)

// is there a valid match?
if ($is_match) {
if ($route['fn'] === null) {
++$numHandledByOtherMethods;

continue;
}

// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
Expand Down Expand Up @@ -449,7 +468,10 @@ private function handle($routes, $quitAfterRun = false)
}

// Return the number of routes handled
return $numHandled;
return (object) [
'numHandled' => $numHandled,
'numHandledByOtherMethods' => $numHandledByOtherMethods,
];
}

private function invoke($fn, $params = array())
Expand Down
Loading