Skip to content

Commit dab39f1

Browse files
committed
Added resolveClass methods for RouteCommands and made some code fixes.
1 parent e5e809e commit dab39f1

File tree

2 files changed

+103
-61
lines changed

2 files changed

+103
-61
lines changed

src/Router.php

Lines changed: 58 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -467,29 +467,8 @@ public function controller($route, $settings, $controller = null)
467467
$settings = [];
468468
}
469469

470-
$controller = str_replace(['\\', '.'], '/', $controller);
471-
$controller = trim(
472-
preg_replace(
473-
'/'.str_replace('/', '\\/', $this->paths['controllers']).'/i',
474-
'', $controller,
475-
1
476-
),
477-
'/'
478-
);
479-
$controllerFile = realpath(
480-
rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php'
481-
);
482-
483-
if (! file_exists($controllerFile)) {
484-
return $this->exception($controller . ' class is not found!');
485-
}
486-
487-
if (! class_exists($controller)) {
488-
require $controllerFile;
489-
}
490-
491-
$controller = str_replace('/', '\\', $controller);
492-
$classMethods = get_class_methods($this->namespaces['controllers'] . $controller);
470+
$controller = $this->resolveClass($controller);
471+
$classMethods = get_class_methods($controller);
493472
if ($classMethods) {
494473
foreach ($classMethods as $methodName) {
495474
if(!strstr($methodName, '__')) {
@@ -503,13 +482,22 @@ public function controller($route, $settings, $controller = null)
503482

504483
$methodVar = lcfirst(preg_replace('/'.$method.'/i', '', $methodName, 1));
505484
$methodVar = strtolower(preg_replace('%([a-z]|[0-9])([A-Z])%', '\1-\2', $methodVar));
506-
$r = new ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName);
507-
$reqiredParam = $r->getNumberOfRequiredParameters();
508-
$totalParam = $r->getNumberOfParameters();
485+
$r = new ReflectionMethod($controller, $methodName);
486+
$endpoints = [];
487+
foreach ($r->getParameters() as $param) {
488+
$pattern = ':any';
489+
$typeHint = $param->hasType() ? $param->getType()->getName() : null;
490+
if ($typeHint === 'int') {
491+
$pattern = ':id';
492+
} elseif ($typeHint === 'string') {
493+
$pattern = ':slug';
494+
}
495+
$endpoints[] = $param->isOptional() ? $pattern . '?' : $pattern;
496+
}
509497

510498
$value = ($methodVar === $this->mainMethod ? $route : $route.'/'.$methodVar);
511499
$this->{$method}(
512-
($value.str_repeat('/:any', $reqiredParam).str_repeat('/:any?', $totalParam-$reqiredParam)),
500+
($value.'/'.implode('/', $endpoints)),
513501
$settings,
514502
($controller . '@' . $methodName)
515503
);
@@ -521,6 +509,36 @@ public function controller($route, $settings, $controller = null)
521509
return true;
522510
}
523511

512+
/**
513+
* @param $controller
514+
*
515+
* @return RouterException|mixed
516+
*/
517+
protected function resolveClass($controller)
518+
{
519+
$controller = str_replace(['\\', '.'], '/', $controller);
520+
$controller = trim(
521+
preg_replace(
522+
'/'.str_replace('/', '\\/', $this->paths['controllers']).'/i',
523+
'', $controller,
524+
1
525+
),
526+
'/'
527+
);
528+
$file = realpath(rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php');
529+
530+
if (! file_exists($file)) {
531+
return $this->exception($controller . ' class is not found!');
532+
}
533+
534+
$controller = $this->namespaces['controllers'] . str_replace('/', '\\', $controller);
535+
if (! class_exists($controller)) {
536+
require $file;
537+
}
538+
539+
return $controller;
540+
}
541+
524542
/**
525543
* Routes error function. (Closure)
526544
*
@@ -566,13 +584,18 @@ private function addRoute($uri, $method, $callback, $settings)
566584
$route .= '/';
567585
}
568586

587+
$routeName = is_string($callback)
588+
? strtolower(preg_replace(
589+
'/[^\w]/i', '.', str_replace($this->namespaces['controllers'], '', $callback)
590+
))
591+
: null;
569592
$data = [
570593
'route' => str_replace('//', '/', $route),
571594
'method' => strtoupper($method),
572595
'callback' => $callback,
573596
'name' => (isset($settings['name'])
574597
? $settings['name']
575-
: null
598+
: $routeName
576599
),
577600
'before' => (isset($settings['before'])
578601
? $settings['before']
@@ -596,12 +619,7 @@ private function addRoute($uri, $method, $callback, $settings)
596619
*/
597620
private function runRouteCommand($command, $params = null)
598621
{
599-
$this->routerCommand()->runRoute(
600-
$command,
601-
$params,
602-
$this->baseFolder . '/' . $this->paths['controllers'],
603-
$this->namespaces['controllers']
604-
);
622+
$this->routerCommand()->runRoute($command, $params);
605623
}
606624

607625
/**
@@ -614,25 +632,15 @@ private function runRouteCommand($command, $params = null)
614632
*/
615633
public function runRouteMiddleware($middleware, $type)
616634
{
617-
$middlewarePath = $this->baseFolder . '/' . $this->paths['middlewares'];
618-
$middlewareNs = $this->namespaces['middlewares'];
619-
if ($type == 'before') {
635+
if ($type === 'before') {
620636
if (! is_null($middleware['group'])) {
621-
$this->routerCommand()->beforeAfter(
622-
$middleware['group'][$type], $middlewarePath, $middlewareNs
623-
);
637+
$this->routerCommand()->beforeAfter($middleware['group'][$type]);
624638
}
625-
$this->routerCommand()->beforeAfter(
626-
$middleware[$type], $middlewarePath, $middlewareNs
627-
);
639+
$this->routerCommand()->beforeAfter($middleware[$type]);
628640
} else {
629-
$this->routerCommand()->beforeAfter(
630-
$middleware[$type], $middlewarePath, $middlewareNs
631-
);
641+
$this->routerCommand()->beforeAfter($middleware[$type]);
632642
if (! is_null($middleware['group'])) {
633-
$this->routerCommand()->beforeAfter(
634-
$middleware['group'][$type], $middlewarePath, $middlewareNs
635-
);
643+
$this->routerCommand()->beforeAfter($middleware['group'][$type]);
636644
}
637645
}
638646
}
@@ -690,7 +698,7 @@ public function exception($message = '')
690698
*/
691699
public function routerCommand()
692700
{
693-
return RouterCommand::getInstance();
701+
return RouterCommand::getInstance($this->baseFolder, $this->paths, $this->namespaces);
694702
}
695703

696704
/**

src/Router/RouterCommand.php

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,45 @@ class RouterCommand
1717
*/
1818
protected static $instance = null;
1919

20+
protected $baseFolder;
21+
protected $paths;
22+
protected $namespaces;
23+
24+
/**
25+
*
26+
*/
27+
public function __construct($baseFolder, $paths, $namespaces)
28+
{
29+
$this->baseFolder = $baseFolder;
30+
$this->paths = $paths;
31+
$this->namespaces = $namespaces;
32+
}
33+
34+
public function getMiddlewareInfo()
35+
{
36+
return [
37+
'path' => $this->baseFolder . '/' . $this->paths['middlewares'],
38+
'namespace' => $this->namespaces['middlewares'],
39+
];
40+
}
41+
42+
public function getControllerInfo()
43+
{
44+
return [
45+
'path' => $this->baseFolder . '/' . $this->paths['controllers'],
46+
'namespace' => $this->namespaces['controllers'],
47+
];
48+
}
49+
2050
/**
2151
* Get class instance
2252
*
2353
* @return RouterCommand
2454
*/
25-
public static function getInstance()
55+
public static function getInstance($baseFolder, $paths, $namespaces)
2656
{
2757
if (null === self::$instance) {
28-
self::$instance = new static();
58+
self::$instance = new static($baseFolder, $paths, $namespaces);
2959
}
3060
return self::$instance;
3161
}
@@ -53,15 +83,16 @@ public function exception($message = '')
5383
* @return mixed|void
5484
* @throws
5585
*/
56-
public function beforeAfter($command, $path = '', $namespace = '')
86+
public function beforeAfter($command)
5787
{
5888
if (! is_null($command)) {
89+
$info = $this->getMiddlewareInfo();
5990
if (is_array($command)) {
6091
foreach ($command as $key => $value) {
61-
$this->beforeAfter($value, $path, $namespace);
92+
$this->beforeAfter($value, $info['path'], $info['namespace']);
6293
}
6394
} elseif (is_string($command)) {
64-
$controller = $this->resolveClass($command, $path, $namespace);
95+
$controller = $this->resolveClass($command, $info['path'], $info['namespace']);
6596
if (method_exists($controller, 'handle')) {
6697
$response = call_user_func([$controller, 'handle']);
6798
if ($response !== true) {
@@ -90,14 +121,15 @@ public function beforeAfter($command, $path = '', $namespace = '')
90121
* @return void
91122
* @throws
92123
*/
93-
public function runRoute($command, $params = null, $path = '', $namespace = '')
124+
public function runRoute($command, $params = null)
94125
{
126+
$info = $this->getControllerInfo();
95127
if (! is_object($command)) {
96-
$segments = explode('@', $command);
97-
$controllerClass = str_replace([$namespace, '\\', '.'], ['', '/', '/'], $segments[0]);
98-
$controllerMethod = $segments[1];
128+
$segments = explode('@', $command);
129+
$controllerClass = str_replace([$info['namespace'], '\\', '.'], ['', '/', '/'], $segments[0]);
130+
$controllerMethod = $segments[1];
99131

100-
$controller = $this->resolveClass($controllerClass, $path, $namespace);
132+
$controller = $this->resolveClass($controllerClass, $info['path'], $info['namespace']);
101133
if (method_exists($controller, $controllerMethod)) {
102134
echo call_user_func_array(
103135
[$controller, $controllerMethod],
@@ -134,8 +166,10 @@ protected function resolveClass($class, $path, $namespace)
134166
return $this->exception($class . ' class is not found. Please, check file.');
135167
}
136168

137-
require_once($file);
138169
$class = $namespace . str_replace('/', '\\', $class);
170+
if (!class_exists($class)) {
171+
require_once($file);
172+
}
139173

140174
return new $class();
141175
}

0 commit comments

Comments
 (0)