Skip to content

Commit 4b375cc

Browse files
committedAug 20, 2018
Added middleware support for controller() method. Added main method as handle() for Middlewares. And code optimization.
1 parent 4cc16a1 commit 4b375cc

File tree

4 files changed

+319
-204
lines changed

4 files changed

+319
-204
lines changed
 

Diff for: ‎src/Router.php

+198-104
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,31 @@
1111
*/
1212
namespace Buki;
1313

14+
use ReflectionMethod;
1415
use Buki\Router\RouterRequest;
1516
use Buki\Router\RouterCommand;
1617
use Buki\Router\RouterException;
1718

1819
class Router
1920
{
21+
/**
22+
* @var $baseFolder Pattern definations for parameters of Route
23+
*/
2024
protected $baseFolder;
2125

26+
/**
27+
* @var $routes Routes list
28+
*/
2229
protected $routes = [];
23-
protected $middlewares = [];
30+
31+
/**
32+
* @var $groups List of group routes
33+
*/
2434
protected $groups = [];
2535

36+
/**
37+
* @var $patterns Pattern definations for parameters of Route
38+
*/
2639
protected $patterns = [
2740
'{a}' => '([^/]+)',
2841
'{d}' => '([0-9]+)',
@@ -33,59 +46,88 @@ class Router
3346
'{*}' => '(.*)'
3447
];
3548

49+
/**
50+
* @var $namespaces Namespaces of Controllers and Middlewares files
51+
*/
3652
protected $namespaces = [
3753
'middlewares' => '',
3854
'controllers' => ''
3955
];
4056

57+
/**
58+
* @var $path Paths of Controllers and Middlewares files
59+
*/
4160
protected $paths = [
4261
'controllers' => 'Controllers',
4362
'middlewares' => 'Middlewares'
4463
];
4564

65+
/**
66+
* @var $mainMethod Main method for controller
67+
*/
68+
protected $mainMethod = 'main';
69+
4670
protected $errorCallback;
4771

4872
/**
4973
* Router constructer method.
74+
*
75+
* @param array $params
5076
*
51-
* @return
77+
* @return void
5278
*/
53-
function __construct(Array $params = [])
79+
function __construct(array $params = [])
5480
{
5581
$this->baseFolder = realpath(getcwd());
5682

57-
if(is_null($params) || empty($params)) {
83+
if (empty($params)) {
5884
return;
5985
}
6086

61-
if(isset($params['debug']) && is_bool($params['debug'])) {
87+
if (isset($params['debug']) && is_bool($params['debug'])) {
6288
RouterException::$debug = $params['debug'];
6389
}
6490

65-
if(isset($params['paths']) && $paths = $params['paths']) {
66-
$this->paths['controllers'] = (
67-
isset($paths['controllers']) ? $this->baseFolder . '/' . trim($paths['controllers'], '/') . '/' : $this->paths['controllers']
68-
);
69-
$this->paths['middlewares'] = (
70-
isset($paths['middlewares']) ? $this->baseFolder . '/' . trim($paths['middlewares'], '/') . '/' : $this->paths['middlewares']
71-
);
91+
$this->setPaths($params);
92+
}
93+
94+
/**
95+
* Set paths and namespaces for Controllers and Middlewares.
96+
*
97+
* @return void
98+
*/
99+
protected function setPaths($params)
100+
{
101+
if (isset($params['paths']) && $paths = $params['paths']) {
102+
$this->paths['controllers'] =
103+
isset($paths['controllers'])
104+
? trim($paths['controllers'], '/')
105+
: $this->paths['controllers'];
106+
107+
$this->paths['middlewares'] =
108+
isset($paths['middlewares'])
109+
? trim($paths['middlewares'], '/')
110+
: $this->paths['middlewares'];
72111
}
73112

74-
if(isset($params['namespaces']) && $namespaces = $params['namespaces']) {
75-
$this->namespaces['controllers'] = (
76-
isset($namespaces['controllers']) ? trim($namespaces['controllers'], '\\') . '\\' : ''
77-
);
78-
$this->namespaces['middlewares'] = (
79-
isset($namespaces['middlewares']) ? trim($namespaces['middlewares'], '\\') . '\\' : ''
80-
);
113+
if (isset($params['namespaces']) && $namespaces = $params['namespaces']) {
114+
$this->namespaces['controllers'] =
115+
isset($namespaces['controllers'])
116+
? trim($namespaces['controllers'], '\\') . '\\'
117+
: '';
118+
119+
$this->namespaces['middlewares'] =
120+
isset($namespaces['middlewares'])
121+
? trim($namespaces['middlewares'], '\\') . '\\'
122+
: '';
81123
}
82124
}
83125

84126
/**
85127
* Add route method;
86128
* Get, Post, Put, Delete, Patch, Any, Ajax...
87129
*
88-
* @return
130+
* @return void
89131
*/
90132
public function __call($method, $params)
91133
{
@@ -101,29 +143,30 @@ public function __call($method, $params)
101143
$callback = $params[1];
102144
$settings = null;
103145

104-
if(count($params) > 2) {
146+
if (count($params) > 2) {
105147
$settings = $params[1];
106148
$callback = $params[2];
107149
}
108150

109-
if(strstr($route, '{')) {
151+
if (strstr($route, '{')) {
110152
$route1 = $route2 = '';
111-
foreach(explode('/', $route) as $key => $value) {
112-
if($value != '') {
113-
if(!strpos($value, '?')) {
153+
foreach (explode('/', $route) as $key => $value) {
154+
if ($value != '') {
155+
if (! strpos($value, '?')) {
114156
$route1 .= '/' . $value;
115157
} else {
116-
if($route2 == '') {
158+
if ($route2 == '') {
117159
$this->addRoute($route1, $method, $callback, $settings);
118160
}
161+
119162
$route2 = $route1 . '/' . str_replace('?', '', $value);
120163
$this->addRoute($route2, $method, $callback, $settings);
121164
$route1 = $route2;
122165
}
123166
}
124167
}
125168

126-
if($route2 == '') {
169+
if ($route2 == '') {
127170
$this->addRoute($route1, $method, $callback, $settings);
128171
}
129172
} else {
@@ -135,18 +178,23 @@ public function __call($method, $params)
135178
/**
136179
* Add new route method one or more http methods.
137180
*
138-
* @return null
181+
* @param string $methods
182+
* @param string $route
183+
* @param array|string|closure $settings
184+
* @param string|closure $callback
185+
*
186+
* @return void
139187
*/
140188
public function add($methods, $route, $settings, $callback = null)
141189
{
142-
if(is_null($callback)) {
190+
if (is_null($callback)) {
143191
$callback = $settings;
144192
$settings = null;
145193
}
146194

147-
if(strstr($methods, '|')) {
195+
if (strstr($methods, '|')) {
148196
foreach (array_unique(explode('|', $methods)) as $method) {
149-
if($method != '') {
197+
if ($method != '') {
150198
call_user_func_array([$this, strtolower($method)], [$route, $settings, $callback]);
151199
}
152200
}
@@ -160,20 +208,23 @@ public function add($methods, $route, $settings, $callback = null)
160208
/**
161209
* Add new route rules pattern; String or Array
162210
*
163-
* @return
211+
* @param string|array $pattern
212+
* @param null|string $attr
213+
*
214+
* @return void
164215
*/
165216
public function pattern($pattern, $attr = null)
166217
{
167-
if(is_array($pattern)) {
218+
if (is_array($pattern)) {
168219
foreach ($pattern as $key => $value) {
169-
if(!in_array('{' . $key . '}', array_keys($this->patterns))) {
220+
if (! in_array('{' . $key . '}', array_keys($this->patterns))) {
170221
$this->patterns['{' . $key . '}'] = '(' . $value . ')';
171222
} else {
172223
return $this->exception($key . ' pattern cannot be changed.');
173224
}
174225
}
175226
} else {
176-
if(!in_array('{' . $pattern . '}', array_keys($this->patterns))) {
227+
if (! in_array('{' . $pattern . '}', array_keys($this->patterns))) {
177228
$this->patterns['{' . $pattern . '}'] = '(' . $attr . ')';
178229
} else {
179230
return $this->exception($pattern . ' pattern cannot be changed.');
@@ -183,20 +234,11 @@ public function pattern($pattern, $attr = null)
183234
return;
184235
}
185236

186-
/**
187-
* Add new middleware
188-
*
189-
* @return null
190-
*/
191-
public function middleware($name, $command)
192-
{
193-
$this->middlewares[$name] = $command;
194-
}
195-
196237
/**
197238
* Run Routes
198239
*
199-
* @return true | throw Exception
240+
* @return void
241+
* @throw Exception
200242
*/
201243
public function run()
202244
{
@@ -206,10 +248,11 @@ public function run()
206248
$base = str_replace('\\', '/', str_replace($documentRoot, '', $getCwd) . '/');
207249
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
208250

209-
if(($base != $uri) && (substr($uri, -1) == '/')) {
251+
if (($base != $uri) && (substr($uri, -1) == '/')) {
210252
$uri = substr($uri, 0, (strlen($uri)-1));
211253
}
212-
if($uri === '') {
254+
255+
if ($uri === '') {
213256
$uri = '/';
214257
}
215258

@@ -251,7 +294,7 @@ public function run()
251294
array_shift($matched);
252295
$newMatched = [];
253296
foreach ($matched as $key => $value) {
254-
if(strstr($value, '/')) {
297+
if (strstr($value, '/')) {
255298
foreach (explode('/', $value) as $k => $v) {
256299
$newMatched[] = trim(urldecode($v));
257300
}
@@ -270,12 +313,12 @@ public function run()
270313
}
271314

272315
// If it originally was a HEAD request, clean up after ourselves by emptying the output buffer
273-
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'HEAD') {
316+
if (strtoupper($_SERVER['REQUEST_METHOD']) === 'HEAD') {
274317
ob_end_clean();
275318
}
276319

277320
if ($foundRoute == false) {
278-
if (!$this->errorCallback) {
321+
if (! $this->errorCallback) {
279322
$this->errorCallback = function() {
280323
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
281324
return $this->exception('Route not found. Looks like something went wrong. Please try again.');
@@ -288,7 +331,11 @@ public function run()
288331
/**
289332
* Routes Group
290333
*
291-
* @return null
334+
* @param string $name
335+
* @param closure|array $settings
336+
* @param null|closure $callback
337+
*
338+
* @return void
292339
*/
293340
public function group($name, $settings = null, $callback = null)
294341
{
@@ -297,32 +344,32 @@ public function group($name, $settings = null, $callback = null)
297344
$group['route'] = '/' . $groupName;
298345
$group['before'] = $group['after'] = null;
299346

300-
if(is_null($callback)) {
347+
if (is_null($callback)) {
301348
$callback = $settings;
302349
} else {
303350
$group['before'][] = (!isset($settings['before']) ? null : $settings['before']);
304351
$group['after'][] = (!isset($settings['after']) ? null : $settings['after']);
305352
}
306353

307354
$groupCount = count($this->groups);
308-
if($groupCount > 0) {
355+
if ($groupCount > 0) {
309356
$list = [];
310357
foreach ($this->groups as $key => $value) {
311-
if(is_array($value['before'])) {
312-
foreach($value['before'] as $k => $v) {
358+
if (is_array($value['before'])) {
359+
foreach ($value['before'] as $k => $v) {
313360
$list['before'][] = $v;
314361
}
315-
foreach($value['after'] as $k => $v) {
362+
foreach ($value['after'] as $k => $v) {
316363
$list['after'][] = $v;
317364
}
318365
}
319366
}
320367

321-
if(!is_null($group['before'])) {
368+
if (! is_null($group['before'])) {
322369
$list['before'][] = $group['before'][0];
323370
}
324371

325-
if(!is_null($group['after'])) {
372+
if (! is_null($group['after'])) {
326373
$list['after'][] = $group['after'][0];
327374
}
328375

@@ -335,7 +382,7 @@ public function group($name, $settings = null, $callback = null)
335382

336383
array_push($this->groups, $group);
337384

338-
if(is_object($callback)) {
385+
if (is_object($callback)) {
339386
call_user_func_array($callback, [$this]);
340387
}
341388

@@ -345,54 +392,70 @@ public function group($name, $settings = null, $callback = null)
345392
/**
346393
* Added route from methods of Controller file.
347394
*
348-
* @return null
395+
* @param string $route
396+
* @param string|array $settings
397+
* @param null|string $controller
398+
*
399+
* @return void
349400
*/
350-
public function controller($route, $controller)
401+
public function controller($route, $settings, $controller = null)
351402
{
403+
if (is_null($controller)) {
404+
$controller = $settings;
405+
$settings = [];
406+
}
407+
352408
$controller = str_replace(['\\', '.'], '/', $controller);
353409
$controllerFile = realpath(
354-
$this->paths['controllers'] . $controller . '.php'
410+
rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php'
355411
);
356-
if(file_exists($controllerFile)) {
357-
if(!class_exists($controller)) {
358-
$req = require($controllerFile);
359-
}
360-
} else {
361-
return $this->exception($controller . " controller file is not found! Please, check file.");
412+
413+
if (! file_exists($controllerFile)) {
414+
return $this->exception($controller . ' class is not found!');
415+
}
416+
417+
if (! class_exists($controller)) {
418+
require($controllerFile);
362419
}
363420

364421
$controller = str_replace('/', '\\', $controller);
365422
$classMethods = get_class_methods($this->namespaces['controllers'] . $controller);
366-
if($classMethods) {
423+
if ($classMethods) {
367424
foreach ($classMethods as $methodName) {
368-
if(!strstr($methodName, '__')) {
369-
$method = "any";
370-
foreach(explode('|', RouterRequest::$validMethods) as $m) {
371-
if(stripos($methodName, strtolower($m), 0) === 0) {
425+
if (! strstr($methodName, '__')) {
426+
$method = 'any';
427+
foreach (explode('|', RouterRequest::$validMethods) as $m) {
428+
if (stripos($methodName, strtolower($m), 0) === 0) {
372429
$method = strtolower($m);
373430
break;
374431
}
375432
}
376433

377434
$methodVar = lcfirst(str_replace($method, '', $methodName));
378-
$r = new \ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName);
379-
$paramNum = $r->getNumberOfRequiredParameters();
380-
$paramNum2 = $r->getNumberOfParameters();
381-
382-
$value = ($methodVar == 'main' ? $route : $route . '/' . $methodVar);
383-
$this->{$method}(($value . str_repeat('/{a}', $paramNum) . str_repeat('/{a?}', $paramNum2 - $paramNum)), ($controller . '@' . $methodName));
435+
$r = new ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName);
436+
$requiredParam = $r->getNumberOfRequiredParameters();
437+
$totalParam = $r->getNumberOfParameters();
438+
439+
$value = ($methodVar === 'main' ? $route : $route . '/' . $methodVar);
440+
441+
$this->addRoute(
442+
($value.str_repeat('/{a}', $requiredParam).str_repeat('/{a?}', $totalParam-$requiredParam)),
443+
$method,
444+
($controller.'@'.$methodName),
445+
$settings
446+
);
384447
}
385448
}
386449
unset($r);
387450
}
388-
389-
$req = null;
390451
}
391452

392453
/**
393454
* Routes error function. (Closure)
394455
*
395-
* @return null
456+
* @param $callback
457+
*
458+
* @return void
396459
*/
397460
public function error($callback)
398461
{
@@ -402,38 +465,59 @@ public function error($callback)
402465
/**
403466
* Add new Route and it's settings
404467
*
405-
* @return null
468+
* @param $uri
469+
* @param $method
470+
* @param $callback
471+
* @param $settings
472+
*
473+
* @return void
406474
*/
407475
private function addRoute($uri, $method, $callback, $settings)
408476
{
409477
$groupItem = count($this->groups) - 1;
410478
$group = '';
411-
if($groupItem > -1) {
479+
if ($groupItem > -1) {
412480
foreach ($this->groups as $key => $value) {
413481
$group .= $value['route'];
414482
}
415483
}
416484

417485
$page = dirname($_SERVER['PHP_SELF']);
418486
$page = $page == '/' ? '' : $page;
419-
if(strstr($page, 'index.php')) {
487+
if (strstr($page, 'index.php')) {
420488
$data = implode('/', explode('/', $page));
421489
$page = str_replace($data, '', $page);
422490
}
423491

424492
$route = $page . $group . '/' . trim($uri, '/');
425493
$route = rtrim($route, '/');
426-
if($route == $page) {
494+
if ($route == $page) {
427495
$route .= '/';
428496
}
429497

430498
$data = [
431499
'route' => str_replace('//', '/', $route),
432500
'method' => strtoupper($method),
433-
'callback' => (is_object($callback) ? $callback : $this->namespaces['controllers'] . $callback),
434-
'alias' => (isset($settings['alias']) ? $settings['alias'] : (isset($settings['as']) ? $settings['as'] : null)),
435-
'before' => (isset($settings['before']) ? (!is_array($settings['before']) && !is_object($settings['before']) && strstr($settings['before'], '@') ? $this->namespaces['middlewares'] . $settings['before'] : $settings['before'] ) : null),
436-
'after' => (isset($settings['after']) ? (!is_array($settings['after']) && !is_object($settings['after']) && strstr($settings['after'], '@') ? $this->namespaces['middlewares'] . $settings['after'] : $settings['after'] ) : null),
501+
'callback' => (is_object($callback)
502+
? $callback
503+
: $this->namespaces['controllers'] . $callback
504+
),
505+
'name' => (isset($settings['name'])
506+
? $settings['name']
507+
: null
508+
),
509+
'before' => (isset($settings['before'])
510+
? (is_string($settings['before'])
511+
? $this->namespaces['middlewares'] . $settings['before']
512+
: $settings['before'])
513+
: null
514+
),
515+
'after' => (isset($settings['after'])
516+
? (is_string($settings['after'])
517+
? $this->namespaces['middlewares'] . $settings['after']
518+
: $settings['after'])
519+
: null
520+
),
437521
'group' => ($groupItem === -1) ? null : $this->groups[$groupItem]
438522
];
439523
array_push($this->routes, $data);
@@ -447,33 +531,41 @@ private function addRoute($uri, $method, $callback, $settings)
447531
private function runRouteCommand($command, $params = null)
448532
{
449533
$this->routerCommand()->runRoute(
450-
$command, $params, $this->paths['controllers'], $this->namespaces['controllers']
534+
$command,
535+
$params,
536+
$this->baseFolder . '/' . $this->paths['controllers'],
537+
$this->namespaces['controllers']
451538
);
452539
}
453540

454541
/**
455542
* Detect Routes Middleware; before or after
456543
*
457-
* @return null
544+
* @param $middleware
545+
* @param $type
546+
*
547+
* @return void
458548
*/
459549
public function runRouteMiddleware($middleware, $type)
460550
{
461-
if($type == 'before') {
462-
if(!is_null($middleware['group'])) {
551+
$middlewarePath = $this->baseFolder . '/' . $this->paths['middlewares'];
552+
$middlewareNs = $this->namespaces['middlewares'];
553+
if ($type == 'before') {
554+
if (! is_null($middleware['group'])) {
463555
$this->routerCommand()->beforeAfter(
464-
$middleware['group'][$type], $this->middlewares, $this->paths['middlewares'], $this->namespaces['middlewares']
556+
$middleware['group'][$type], $middlewarePath, $middlewareNs
465557
);
466558
}
467559
$this->routerCommand()->beforeAfter(
468-
$middleware[$type], $this->middlewares, $this->paths['middlewares'], $this->namespaces['middlewares']
560+
$middleware[$type], $middlewarePath, $middlewareNs
469561
);
470562
} else {
471563
$this->routerCommand()->beforeAfter(
472-
$middleware[$type], $this->middlewares, $this->paths['middlewares'], $this->namespaces['middlewares']
564+
$middleware[$type], $middlewarePath, $middlewareNs
473565
);
474-
if(!is_null($middleware['group'])) {
566+
if (! is_null($middleware['group'])) {
475567
$this->routerCommand()->beforeAfter(
476-
$middleware['group'][$type], $this->middlewares, $this->paths['middlewares'], $this->namespaces['middlewares']
568+
$middleware['group'][$type], $middlewarePath, $middlewareNs
477569
);
478570
}
479571
}
@@ -482,7 +574,7 @@ public function runRouteMiddleware($middleware, $type)
482574
/**
483575
* Routes Group endpoint
484576
*
485-
* @return null
577+
* @return void
486578
*/
487579
private function endGroup()
488580
{
@@ -492,11 +584,11 @@ private function endGroup()
492584
/**
493585
* Display all Routes.
494586
*
495-
* @return null
587+
* @return void
496588
*/
497589
public function getList()
498590
{
499-
echo '<pre style="border:1px solid #eee;padding:0 10px;width:960px;max-height:780;margin:20px auto;font-size:17px;overflow:auto;">';
591+
echo '<pre style="font-size:15px;">';
500592
var_dump($this->getRoutes());
501593
echo '</pre>';
502594
die();
@@ -514,6 +606,8 @@ public function getRoutes()
514606

515607
/**
516608
* Throw new Exception for Router Error
609+
*
610+
* @param $message
517611
*
518612
* @return RouterException
519613
*/
@@ -528,7 +622,7 @@ public function exception($message = '')
528622
* @return RouterCommand
529623
*/
530624
public function routerCommand()
531-
{
625+
{
532626
return RouterCommand::getInstance();
533627
}
534628
}

Diff for: ‎src/Router/RouterCommand.php

+68-64
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
<?php
2-
/*
3-
*
4-
* @ Package: Router - simple router class for php
5-
* @ Class: RouterCommand
6-
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
7-
* @ Web: http://burakdemirtas.org
8-
* @ URL: https://github.com/izniburak/php-router
9-
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
10-
*
11-
*/
2+
/**
3+
* @ Package: Router - simple router class for php
4+
* @ Class: RouterCommand
5+
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
6+
* @ Web: http://burakdemirtas.org
7+
* @ URL: https://github.com/izniburak/php-router
8+
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
9+
*/
10+
1211
namespace Buki\Router;
1312

1413
use Buki\Router\RouterException;
1514

1615
class RouterCommand
1716
{
1817
/**
19-
* Class instance variable
18+
* @var Class instance variable
2019
*/
2120
protected static $instance = null;
2221

@@ -36,6 +35,7 @@ public static function getInstance()
3635
/**
3736
* Throw new Exception for Router Error
3837
*
38+
* @param $message
3939
* @return RouterException
4040
*/
4141
public function exception($message = '')
@@ -46,84 +46,88 @@ public function exception($message = '')
4646
/**
4747
* Run Route Middlewares
4848
*
49-
* @return true | false
49+
* @param $command
50+
* @param $path
51+
* @param $namespace
52+
*
53+
* @return void
5054
*/
51-
public function beforeAfter($command, $middleware, $path = '', $namespace = '')
55+
public function beforeAfter($command, $path = '', $namespace = '')
5256
{
53-
if(!is_null($command)) {
54-
if(is_array($command)) {
57+
if (! is_null($command)) {
58+
if (is_array($command)) {
5559
foreach ($command as $key => $value) {
56-
$this->beforeAfter($value, $middleware, $path, $namespace);
60+
$this->beforeAfter($value, $path, $namespace);
5761
}
58-
}
59-
elseif(is_object($command)) {
60-
return call_user_func($command);
61-
}
62-
elseif(strstr($command, '@')) {
63-
$segments = explode('@', $command);
64-
$middlewareClass = str_replace([$namespace, '\\', '.'], ['', '/', '/'], $segments[0]);
65-
$middlewareMethod = $segments[1];
66-
67-
$middlewareFile = realpath($path . $middlewareClass . '.php');
68-
if(!file_exists($middlewareFile)) {
69-
return $this->exception($middlewareClass . ' Middleware File is not found. Please, check file.');
62+
} elseif (is_string($command)) {
63+
$controller = $this->resolveClass($command, $path, $namespace);
64+
if (method_exists($controller, 'handle')) {
65+
return call_user_func([$controller, 'handle']);
7066
}
71-
require_once($middlewareFile);
72-
$middlewareClass = $namespace . str_replace('/', '\\', $middlewareClass);
73-
$controller = new $middlewareClass();
7467

75-
if(in_array($middlewareMethod, get_class_methods($controller))) {
76-
return call_user_func([$controller, $middlewareMethod]);
77-
} else {
78-
return $this->exception($middlewareMethod . ' method is not found in <b>'.$middlewareClass.'</b> middleware. Please, check file.');
79-
}
80-
} else {
81-
if(!is_null($middleware[$command]) && isset($middleware[$command])) {
82-
$this->beforeAfter($middleware[$command], $middleware, $path, $namespace);
83-
} else {
84-
return false;
85-
}
68+
return $this->exception('handle() method is not found in <b>'.$command.'</b> class.');
8669
}
8770
}
88-
else {
89-
return false;
90-
}
71+
72+
return;
9173
}
9274

9375
/**
9476
* Run Route Command; Controller or Closure
9577
*
96-
* @return null
78+
* @param $command
79+
* @param $params
80+
* @param $path
81+
* @param $namespace
82+
*
83+
* @return void
9784
*/
9885
public function runRoute($command, $params = null, $path = '', $namespace = '')
9986
{
100-
if(!is_object($command)) {
87+
if (! is_object($command)) {
10188
$segments = explode('@', $command);
10289
$controllerClass = str_replace([$namespace, '\\', '.'], ['', '/', '/'], $segments[0]);
10390
$controllerMethod = $segments[1];
10491

105-
$controllerFile = realpath($path . $controllerClass . '.php');
106-
if(!file_exists($controllerFile)) {
107-
return $this->exception($controllerClass . ' Controller File is not found. Please, check file.');
108-
}
109-
require_once($controllerFile);
110-
$controllerClass = $namespace . str_replace('/', '\\', $controllerClass);
111-
$controller = new $controllerClass();
112-
113-
if(!is_null($params) && in_array($controllerMethod, get_class_methods($controller))) {
92+
$controller = $this->resolveClass($controllerClass, $path, $namespace);
93+
if (! is_null($params) && method_exists($controller, $controllerMethod)) {
11494
echo call_user_func_array([$controller, $controllerMethod], $params);
115-
}
116-
elseif(is_null($params) && in_array($controllerMethod, get_class_methods($controller))) {
95+
return;
96+
} elseif (is_null($params) && method_exists($controller, $controllerMethod)) {
11797
echo call_user_func([$controller, $controllerMethod]);
118-
} else {
119-
return $this->exception($controllerMethod . ' method is not found in '.$controllerClass.' controller. Please, check file.');
98+
return;
12099
}
100+
101+
return $this->exception($controllerMethod . ' method is not found in '.$controllerClass.' class.');
121102
} else {
122-
if(!is_null($params)) {
103+
if (! is_null($params)) {
123104
echo call_user_func_array($command, $params);
124-
} else {
125-
echo call_user_func($command);
126-
}
105+
return;
106+
}
107+
108+
echo call_user_func($command);
127109
}
128110
}
111+
112+
/**
113+
* Resolve Controller or Middleware class.
114+
*
115+
* @param $class
116+
* @param $path
117+
* @param $namespace
118+
*
119+
* @return object
120+
*/
121+
protected function resolveClass($class, $path, $namespace)
122+
{
123+
$file = realpath(rtrim($path, '/') . '/' . $class . '.php');
124+
if (! file_exists($file)) {
125+
return $this->exception($class . ' class is not found. Please, check file.');
126+
}
127+
128+
require_once($file);
129+
$class = $namespace . str_replace('/', '\\', $class);
130+
131+
return new $class();
132+
}
129133
}

Diff for: ‎src/Router/RouterException.php

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,32 @@
11
<?php
2-
/*
3-
*
4-
* @ Package: Router - simple router class for php
5-
* @ Class: RouterException
6-
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
7-
* @ Web: http://burakdemirtas.org
8-
* @ URL: https://github.com/izniburak/php-router
9-
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
10-
*
11-
*/
2+
/**
3+
* @ Package: Router - simple router class for php
4+
* @ Class: RouterCommand
5+
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
6+
* @ Web: http://burakdemirtas.org
7+
* @ URL: https://github.com/izniburak/php-router
8+
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
9+
*/
10+
1211
namespace Buki\Router;
1312

1413
use Exception;
1514

1615
class RouterException
1716
{
17+
/**
18+
* @var $debug Debug mode
19+
*/
1820
public static $debug = false;
1921

2022
/**
2123
* Create Exception Class.
2224
*
23-
* @return string | Exception
25+
* @return string|Exception
2426
*/
2527
public function __construct($message)
2628
{
27-
if(self::$debug) {
29+
if (self::$debug) {
2830
throw new Exception($message, 1);
2931
} else {
3032
die('<h2>Opps! An error occurred.</h2> ' . $message);

Diff for: ‎src/Router/RouterRequest.php

+39-24
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,41 @@
11
<?php
2-
/*
3-
*
4-
* @ Package: Router - simple router class for php
5-
* @ Class: RouterRequest
6-
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
7-
* @ Web: http://burakdemirtas.org
8-
* @ URL: https://github.com/izniburak/php-router
9-
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
10-
*
11-
*/
2+
/**
3+
* @ Package: Router - simple router class for php
4+
* @ Class: RouterCommand
5+
* @ Author: izni burak demirtas / @izniburak <info@burakdemirtas.org>
6+
* @ Web: http://burakdemirtas.org
7+
* @ URL: https://github.com/izniburak/php-router
8+
* @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT
9+
*/
10+
1211
namespace Buki\Router;
1312

1413
class RouterRequest
1514
{
15+
/**
16+
* @var $validMethods Valid methods for Requests
17+
*/
1618
public static $validMethods = 'GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|ANY|AJAX|AJAXP';
1719

1820
/**
19-
* method status
21+
* Request method validation
2022
*
21-
* @return true|false
23+
* @return bool
2224
*/
2325
public static function validMethod($data, $method)
2426
{
2527
$valid = false;
26-
if(strstr($data, '|')) {
28+
if (strstr($data, '|')) {
2729
foreach (explode('|', $data) as $value) {
2830
$valid = self::checkMethods($value, $method);
29-
if($valid) break;
31+
if ($valid) {
32+
break;
33+
}
3034
}
3135
} else {
3236
$valid = self::checkMethods($data, $method);
3337
}
38+
3439
return $valid;
3540
}
3641

@@ -39,25 +44,36 @@ public static function validMethod($data, $method)
3944
*
4045
* @return true|false
4146
*/
42-
private static function checkMethods($value, $method)
47+
protected static function checkMethods($value, $method)
4348
{
4449
$valid = false;
45-
if($value == 'AJAX' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && $value == $method) {
50+
if ($value == 'AJAX' && self::isAjax && $value == $method) {
4651
$valid = true;
47-
} elseif($value == 'AJAXP' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && $method == 'POST') {
52+
} elseif ($value == 'AJAXP' && self::isAjax && $method == 'POST') {
4853
$valid = true;
49-
} elseif(in_array($value, explode('|', self::$validMethods)) && ($value == $method || $value == 'ANY')) {
54+
} elseif (in_array($value, explode('|', self::$validMethods)) && ($value == $method || $value == 'ANY')) {
5055
$valid = true;
5156
}
57+
5258
return $valid;
5359
}
5460

61+
/**
62+
* Check ajax request
63+
*
64+
* @return array
65+
*/
66+
protected static function isAjax()
67+
{
68+
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
69+
}
70+
5571
/**
5672
* Get all request headers
5773
*
58-
* @return array The request headers
74+
* @return array
5975
*/
60-
private static function getRequestHeaders()
76+
protected static function getRequestHeaders()
6177
{
6278
// If getallheaders() is available, use that
6379
if (function_exists('getallheaders')) {
@@ -78,7 +94,7 @@ private static function getRequestHeaders()
7894
/**
7995
* Get the request method used, taking overrides into account
8096
*
81-
* @return string The Request method to handle
97+
* @return string
8298
*/
8399
public static function getRequestMethod()
84100
{
@@ -89,12 +105,11 @@ public static function getRequestMethod()
89105
if ($method == 'HEAD') {
90106
ob_start();
91107
$method = 'GET';
92-
} // If it's a POST request, check for a method override header
93-
elseif ($method == 'POST') {
108+
} elseif ($method == 'POST') {
94109
$headers = self::getRequestHeaders();
95110
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], ['PUT', 'DELETE', 'PATCH', 'OPTIONS'])) {
96111
$method = $headers['X-HTTP-Method-Override'];
97-
} elseif(!empty($_POST['_method'])) {
112+
} elseif (! empty($_POST['_method'])) {
98113
$method = strtoupper($_POST['_method']);
99114
}
100115
}

0 commit comments

Comments
 (0)
Please sign in to comment.