Этот коммит содержится в:
2019-11-05 21:21:54 +03:00
родитель 499374305a
Коммит 2fbd0c43c4
2 изменённых файлов: 89 добавлений и 9 удалений

Просмотреть файл

@@ -3,6 +3,8 @@
namespace MyApp\Core;
use ReflectionMethod;
use ReflectionClass;
use ReflectionException;
/**
* Class Router.
@@ -17,8 +19,10 @@ class Router
public function __construct()
{
$this->getRoutesFromControllers();
$this->addRoute('/^.*$/', 'MyApp\\Controller\\ErrorsController', 'get404', ['GET']);
$this->addRoute('/^.*$/', 'MyApp\\Controller\\ErrorsController', 'post404', ['POST', 'PUT', 'DELETE']);
$this->addRoute('/^.*$/', 'MyApp\\Controller\\ErrorsController',
'get404', ['GET']);
$this->addRoute('/^.*$/', 'MyApp\\Controller\\ErrorsController',
'post404', ['POST', 'PUT', 'DELETE']);
$this->run();
}
@@ -43,7 +47,7 @@ class Router
$fileName = $controllersDir.$file;
if (is_file($fileName) && false !== $className) {
try {
$refClass = new \ReflectionClass($controllersNamespace.$className);
$refClass = new ReflectionClass($controllersNamespace.$className);
$methods = $refClass->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$tags = $app->parseTagsFromComment($method->getDocComment());
@@ -53,11 +57,13 @@ class Router
$tags['HttpMethod'] = ['GET'];
}
$this->addRoute($tags['RouteRegExp'], $method->class, $method->name, $tags['HttpMethod']);
$this->addRoute($tags['RouteRegExp'],
$method->class, $method->name,
$tags['HttpMethod']);
}
}
}
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
var_dump($e);
}
}
@@ -72,10 +78,18 @@ class Router
* @param string $classMethod
* @param array $httpMethods
*/
private function addRoute(string $regExp, string $className, string $classMethod, array $httpMethods)
{
private function addRoute(
string $regExp,
string $className,
string $classMethod,
array $httpMethods
) {
foreach ($httpMethods as $httpMethod) {
$this->routes[strtoupper($httpMethod)][] = [$regExp, $className, $classMethod];
$this->routes[strtoupper($httpMethod)][] = [
$regExp,
$className,
$classMethod,
];
}
}
@@ -86,7 +100,8 @@ class Router
{
if (array_key_exists($_SERVER['REQUEST_METHOD'], $this->routes)) {
foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route_array) {
if (preg_match($route_array[0], $_SERVER['REQUEST_URI'], $matches)) {
if (preg_match($route_array[0], $_SERVER['REQUEST_URI'],
$matches)) {
$obj = new $route_array[1]();
$param_arr = [];
foreach ($matches as $key => $value) {