Skip to content

Commit

Permalink
Added resolveClass methods for RouteCommands and made some code fixes.
Browse files Browse the repository at this point in the history
  • Loading branch information
izniburak committed Aug 4, 2019
1 parent e5e809e commit dab39f1
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 61 deletions.
108 changes: 58 additions & 50 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -467,29 +467,8 @@ public function controller($route, $settings, $controller = null)
$settings = [];
}

$controller = str_replace(['\\', '.'], '/', $controller);
$controller = trim(
preg_replace(
'/'.str_replace('/', '\\/', $this->paths['controllers']).'/i',
'', $controller,
1
),
'/'
);
$controllerFile = realpath(
rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php'
);

if (! file_exists($controllerFile)) {
return $this->exception($controller . ' class is not found!');
}

if (! class_exists($controller)) {
require $controllerFile;
}

$controller = str_replace('/', '\\', $controller);
$classMethods = get_class_methods($this->namespaces['controllers'] . $controller);
$controller = $this->resolveClass($controller);
$classMethods = get_class_methods($controller);
if ($classMethods) {
foreach ($classMethods as $methodName) {
if(!strstr($methodName, '__')) {
Expand All @@ -503,13 +482,22 @@ public function controller($route, $settings, $controller = null)

$methodVar = lcfirst(preg_replace('/'.$method.'/i', '', $methodName, 1));
$methodVar = strtolower(preg_replace('%([a-z]|[0-9])([A-Z])%', '\1-\2', $methodVar));
$r = new ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName);
$reqiredParam = $r->getNumberOfRequiredParameters();
$totalParam = $r->getNumberOfParameters();
$r = new ReflectionMethod($controller, $methodName);
$endpoints = [];
foreach ($r->getParameters() as $param) {
$pattern = ':any';
$typeHint = $param->hasType() ? $param->getType()->getName() : null;
if ($typeHint === 'int') {
$pattern = ':id';
} elseif ($typeHint === 'string') {
$pattern = ':slug';
}
$endpoints[] = $param->isOptional() ? $pattern . '?' : $pattern;
}

$value = ($methodVar === $this->mainMethod ? $route : $route.'/'.$methodVar);
$this->{$method}(
($value.str_repeat('/:any', $reqiredParam).str_repeat('/:any?', $totalParam-$reqiredParam)),
($value.'/'.implode('/', $endpoints)),
$settings,
($controller . '@' . $methodName)
);
Expand All @@ -521,6 +509,36 @@ public function controller($route, $settings, $controller = null)
return true;
}

/**
* @param $controller
*
* @return RouterException|mixed
*/
protected function resolveClass($controller)
{
$controller = str_replace(['\\', '.'], '/', $controller);
$controller = trim(
preg_replace(
'/'.str_replace('/', '\\/', $this->paths['controllers']).'/i',
'', $controller,
1
),
'/'
);
$file = realpath(rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php');

if (! file_exists($file)) {
return $this->exception($controller . ' class is not found!');
}

$controller = $this->namespaces['controllers'] . str_replace('/', '\\', $controller);
if (! class_exists($controller)) {
require $file;
}

return $controller;
}

/**
* Routes error function. (Closure)
*
Expand Down Expand Up @@ -566,13 +584,18 @@ private function addRoute($uri, $method, $callback, $settings)
$route .= '/';
}

$routeName = is_string($callback)
? strtolower(preg_replace(
'/[^\w]/i', '.', str_replace($this->namespaces['controllers'], '', $callback)
))
: null;
$data = [
'route' => str_replace('//', '/', $route),
'method' => strtoupper($method),
'callback' => $callback,
'name' => (isset($settings['name'])
? $settings['name']
: null
: $routeName
),
'before' => (isset($settings['before'])
? $settings['before']
Expand All @@ -596,12 +619,7 @@ private function addRoute($uri, $method, $callback, $settings)
*/
private function runRouteCommand($command, $params = null)
{
$this->routerCommand()->runRoute(
$command,
$params,
$this->baseFolder . '/' . $this->paths['controllers'],
$this->namespaces['controllers']
);
$this->routerCommand()->runRoute($command, $params);
}

/**
Expand All @@ -614,25 +632,15 @@ private function runRouteCommand($command, $params = null)
*/
public function runRouteMiddleware($middleware, $type)
{
$middlewarePath = $this->baseFolder . '/' . $this->paths['middlewares'];
$middlewareNs = $this->namespaces['middlewares'];
if ($type == 'before') {
if ($type === 'before') {
if (! is_null($middleware['group'])) {
$this->routerCommand()->beforeAfter(
$middleware['group'][$type], $middlewarePath, $middlewareNs
);
$this->routerCommand()->beforeAfter($middleware['group'][$type]);
}
$this->routerCommand()->beforeAfter(
$middleware[$type], $middlewarePath, $middlewareNs
);
$this->routerCommand()->beforeAfter($middleware[$type]);
} else {
$this->routerCommand()->beforeAfter(
$middleware[$type], $middlewarePath, $middlewareNs
);
$this->routerCommand()->beforeAfter($middleware[$type]);
if (! is_null($middleware['group'])) {
$this->routerCommand()->beforeAfter(
$middleware['group'][$type], $middlewarePath, $middlewareNs
);
$this->routerCommand()->beforeAfter($middleware['group'][$type]);
}
}
}
Expand Down Expand Up @@ -690,7 +698,7 @@ public function exception($message = '')
*/
public function routerCommand()
{
return RouterCommand::getInstance();
return RouterCommand::getInstance($this->baseFolder, $this->paths, $this->namespaces);
}

/**
Expand Down
56 changes: 45 additions & 11 deletions src/Router/RouterCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,45 @@ class RouterCommand
*/
protected static $instance = null;

protected $baseFolder;
protected $paths;
protected $namespaces;

/**
*
*/
public function __construct($baseFolder, $paths, $namespaces)
{
$this->baseFolder = $baseFolder;
$this->paths = $paths;
$this->namespaces = $namespaces;
}

public function getMiddlewareInfo()
{
return [
'path' => $this->baseFolder . '/' . $this->paths['middlewares'],
'namespace' => $this->namespaces['middlewares'],
];
}

public function getControllerInfo()
{
return [
'path' => $this->baseFolder . '/' . $this->paths['controllers'],
'namespace' => $this->namespaces['controllers'],
];
}

/**
* Get class instance
*
* @return RouterCommand
*/
public static function getInstance()
public static function getInstance($baseFolder, $paths, $namespaces)
{
if (null === self::$instance) {
self::$instance = new static();
self::$instance = new static($baseFolder, $paths, $namespaces);
}
return self::$instance;
}
Expand Down Expand Up @@ -53,15 +83,16 @@ public function exception($message = '')
* @return mixed|void
* @throws
*/
public function beforeAfter($command, $path = '', $namespace = '')
public function beforeAfter($command)
{
if (! is_null($command)) {
$info = $this->getMiddlewareInfo();
if (is_array($command)) {
foreach ($command as $key => $value) {
$this->beforeAfter($value, $path, $namespace);
$this->beforeAfter($value, $info['path'], $info['namespace']);
}
} elseif (is_string($command)) {
$controller = $this->resolveClass($command, $path, $namespace);
$controller = $this->resolveClass($command, $info['path'], $info['namespace']);
if (method_exists($controller, 'handle')) {
$response = call_user_func([$controller, 'handle']);
if ($response !== true) {
Expand Down Expand Up @@ -90,14 +121,15 @@ public function beforeAfter($command, $path = '', $namespace = '')
* @return void
* @throws
*/
public function runRoute($command, $params = null, $path = '', $namespace = '')
public function runRoute($command, $params = null)
{
$info = $this->getControllerInfo();
if (! is_object($command)) {
$segments = explode('@', $command);
$controllerClass = str_replace([$namespace, '\\', '.'], ['', '/', '/'], $segments[0]);
$controllerMethod = $segments[1];
$segments = explode('@', $command);
$controllerClass = str_replace([$info['namespace'], '\\', '.'], ['', '/', '/'], $segments[0]);
$controllerMethod = $segments[1];

$controller = $this->resolveClass($controllerClass, $path, $namespace);
$controller = $this->resolveClass($controllerClass, $info['path'], $info['namespace']);
if (method_exists($controller, $controllerMethod)) {
echo call_user_func_array(
[$controller, $controllerMethod],
Expand Down Expand Up @@ -134,8 +166,10 @@ protected function resolveClass($class, $path, $namespace)
return $this->exception($class . ' class is not found. Please, check file.');
}

require_once($file);
$class = $namespace . str_replace('/', '\\', $class);
if (!class_exists($class)) {
require_once($file);
}

return new $class();
}
Expand Down

0 comments on commit dab39f1

Please sign in to comment.