Last active
November 26, 2021 16:32
-
-
Save john555/ef2cbaa017e6bebf9ea0ee46343964d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Router | |
{ | |
private $request; | |
private $supportedHttpMethods = array( | |
"GET", | |
"POST" | |
); | |
function __construct(IRequest $request) | |
{ | |
$this->request = $request; | |
} | |
function __call($name, $args) | |
{ | |
list($route, $method) = $args; | |
if(!in_array(strtoupper($name), $this->supportedHttpMethods)) | |
{ | |
$this->invalidMethodHandler(); | |
} | |
$this->{strtolower($name)}[$this->formatRoute($route)] = $method; | |
} | |
/** | |
* Removes trailing forward slashes from the right of the route. | |
* @param route (string) | |
*/ | |
private function formatRoute($route) | |
{ | |
$result = rtrim($route, '/'); | |
if ($result === '') | |
{ | |
return '/'; | |
} | |
return $result; | |
} | |
private function invalidMethodHandler() | |
{ | |
header("{$this->request->serverProtocol} 405 Method Not Allowed"); | |
} | |
private function defaultRequestHandler() | |
{ | |
header("{$this->request->serverProtocol} 404 Not Found"); | |
} | |
/** | |
* Resolves a route | |
*/ | |
function resolve() | |
{ | |
$methodDictionary = $this->{strtolower($this->request->requestMethod)}; | |
$formatedRoute = $this->formatRoute($this->request->requestUri); | |
$method = $methodDictionary[$formatedRoute]; | |
if(is_null($method)) | |
{ | |
$this->defaultRequestHandler(); | |
return; | |
} | |
echo call_user_func_array($method, array($this->request)); | |
} | |
function __destruct() | |
{ | |
$this->resolve(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The destructor and therefor
Router::resolve()
is called when the user script (e.g. index.php) ends.This is OK to execute the closure which is defined for a request method in the user script.
However when trying to bind a closure to an unsupported method (e.g. PUT), a 405 header is set as expected, but at the end of the user script, the destructor will still being executed, resulting in a 'Undefined property' notice at line 57 and the
Router::defaultRequestHandler()
method being called. The previously header (405) is overruled by a 404 header now.IMHO it think after it's decided the request method isn't supported,
Router::resolve()
shouldn't be called by the destructor.