Skip to content

Commit 732d1e9

Browse files
committed
Bug fixed about sub-directory routing path. Also, some refactoring has been applied.
1 parent 2df4ef6 commit 732d1e9

File tree

1 file changed

+57
-64
lines changed

1 file changed

+57
-64
lines changed

src/Router.php

Lines changed: 57 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
<?php
2-
/*
3-
*
4-
* @ Package: Router - simple router class for php
5-
* @ Class: Router
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: Router
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+
*/
1210
namespace Buki;
1311

1412
use Closure;
@@ -38,6 +36,16 @@
3836
*/
3937
class Router
4038
{
39+
/**
40+
* @var string
41+
*/
42+
protected $documentRoot = '';
43+
44+
/**
45+
* @var string
46+
*/
47+
protected $runningPath = '';
48+
4149
/**
4250
* @var string $baseFolder Pattern definitions for parameters of Route
4351
*/
@@ -116,11 +124,9 @@ class Router
116124
*/
117125
function __construct(array $params = [])
118126
{
119-
$this->baseFolder = realpath(getcwd());
120-
121-
if (empty($params)) {
122-
return;
123-
}
127+
$this->documentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
128+
$this->runningPath = realpath(getcwd());
129+
$this->baseFolder = $this->runningPath;
124130

125131
if (isset($params['debug']) && is_bool($params['debug'])) {
126132
RouterException::$debug = $params['debug'];
@@ -139,6 +145,10 @@ function __construct(array $params = [])
139145
*/
140146
protected function setPaths($params)
141147
{
148+
if (empty($params)) {
149+
return;
150+
}
151+
142152
if (isset($params['paths']) && $paths = $params['paths']) {
143153
$this->paths['controllers'] = isset($paths['controllers'])
144154
? trim($paths['controllers'], '/')
@@ -167,11 +177,7 @@ protected function setPaths($params)
167177
$this->mainMethod = $params['main_method'];
168178
}
169179

170-
if (isset($params['cache'])) {
171-
$this->cacheFile = $params['cache'];
172-
} else {
173-
$this->cacheFile = realpath(__DIR__ . '/../cache.php');
174-
}
180+
$this->cacheFile = isset($params['cache']) ? $params['cache'] : realpath(__DIR__ . '/../cache.php');
175181
}
176182

177183
/**
@@ -258,7 +264,7 @@ public function add($methods, $route, $settings, $callback = null)
258264

259265
if (strstr($methods, '|')) {
260266
foreach (array_unique(explode('|', $methods)) as $method) {
261-
if ($method != '') {
267+
if (!empty($method)) {
262268
call_user_func_array([$this, strtolower($method)], [$route, $settings, $callback]);
263269
}
264270
}
@@ -282,18 +288,16 @@ public function pattern($pattern, $attr = null)
282288
{
283289
if (is_array($pattern)) {
284290
foreach ($pattern as $key => $value) {
285-
if (! in_array($key, array_keys($this->patterns))) {
286-
$this->patterns[$key] = '(' . $value . ')';
287-
} else {
291+
if (in_array($key, array_keys($this->patterns))) {
288292
return $this->exception($key . ' pattern cannot be changed.');
289293
}
294+
$this->patterns[$key] = '(' . $value . ')';
290295
}
291296
} else {
292-
if (! in_array($pattern, array_keys($this->patterns))) {
293-
$this->patterns[$pattern] = '(' . $attr . ')';
294-
} else {
297+
if (in_array($pattern, array_keys($this->patterns))) {
295298
return $this->exception($pattern . ' pattern cannot be changed.');
296299
}
300+
$this->patterns[$pattern] = '(' . $attr . ')';
297301
}
298302

299303
return true;
@@ -307,11 +311,9 @@ public function pattern($pattern, $attr = null)
307311
*/
308312
public function run()
309313
{
310-
$documentRoot = realpath($_SERVER['DOCUMENT_ROOT']);
311-
$getCwd = realpath(getcwd());
312-
313-
$base = str_replace('\\', '/', str_replace($documentRoot, '', $getCwd) . '/');
314+
$base = str_replace('\\', '/', str_replace($this->documentRoot, '', $this->runningPath) . '/');
314315
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
316+
$uri = str_replace(dirname($_SERVER['PHP_SELF']), '', $uri);
315317

316318
if (($base !== $uri) && (substr($uri, -1) === '/')) {
317319
$uri = substr($uri, 0, (strlen($uri)-1));
@@ -326,21 +328,19 @@ public function run()
326328
$replaces = array_values($this->patterns);
327329
$foundRoute = false;
328330

329-
$routes = [];
330-
foreach ($this->routes as $data) {
331-
array_push($routes, $data['route']);
332-
}
331+
$routes = array_column($this->routes, 'route');
333332

334333
// check if route is defined without regex
335-
if (in_array($uri, array_values($routes))) {
336-
foreach ($this->routes as $data) {
337-
if (RouterRequest::validMethod($data['method'], $method) && ($data['route'] === $uri)) {
338-
$foundRoute = true;
339-
$this->runRouteMiddleware($data, 'before');
340-
$this->runRouteCommand($data['callback']);
341-
$this->runRouteMiddleware($data, 'after');
342-
break;
343-
}
334+
if (in_array($uri, $routes)) {
335+
$currentRoute = array_filter($this->routes, function($r) use ($method, $uri) {
336+
return RouterRequest::validMethod($r['method'], $method) && $r['route'] === $uri;
337+
});
338+
if (!empty($currentRoute)) {
339+
$currentRoute = current($currentRoute);
340+
$foundRoute = true;
341+
$this->runRouteMiddleware($currentRoute, 'before');
342+
$this->runRouteCommand($currentRoute['callback']);
343+
$this->runRouteMiddleware($currentRoute, 'after');
344344
}
345345
} else {
346346
foreach ($this->routes as $data) {
@@ -356,17 +356,9 @@ public function run()
356356
$this->runRouteMiddleware($data, 'before');
357357

358358
array_shift($matched);
359-
$newMatched = [];
360-
foreach ($matched as $key => $value) {
361-
if (strstr($value, '/')) {
362-
foreach (explode('/', $value) as $k => $v) {
363-
$newMatched[] = trim(urldecode($v));
364-
}
365-
} else {
366-
$newMatched[] = trim(urldecode($value));
367-
}
368-
}
369-
$matched = $newMatched;
359+
$matched = array_map(function($value) {
360+
return trim(urldecode($value));
361+
}, $matched);
370362

371363
$this->runRouteCommand($data['callback'], $matched);
372364
$this->runRouteMiddleware($data, 'after');
@@ -384,7 +376,7 @@ public function run()
384376
if ($foundRoute === false) {
385377
if (! $this->errorCallback) {
386378
$this->errorCallback = function() {
387-
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
379+
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
388380
return $this->exception('Route not found. Looks like something went wrong. Please try again.');
389381
};
390382
}
@@ -588,23 +580,24 @@ private function addRoute($uri, $method, $callback, $settings)
588580
}
589581
}
590582

591-
$page = dirname($_SERVER['PHP_SELF']);
592-
$page = $page === '/' ? '' : $page;
593-
if (strstr($page, 'index.php')) {
594-
$data = implode('/', explode('/', $page));
595-
$page = str_replace($data, '', $page);
583+
$path = dirname($_SERVER['PHP_SELF']);
584+
$path = $path === '/' || strpos($this->runningPath, $path) !== 0 ? '' : $path;
585+
586+
if (strstr($path, 'index.php')) {
587+
$data = implode('/', explode('/', $path));
588+
$path = str_replace($data, '', $path);
596589
}
597590

598-
$route = $page . $group . '/' . trim($uri, '/');
591+
$route = $path . $group . '/' . trim($uri, '/');
599592
$route = rtrim($route, '/');
600-
if ($route === $page) {
593+
if ($route === $path) {
601594
$route .= '/';
602595
}
603596

604597
$routeName = is_string($callback)
605598
? strtolower(preg_replace(
606599
'/[^\w]/i', '.', str_replace($this->namespaces['controllers'], '', $callback)
607-
))
600+
))
608601
: null;
609602
$data = [
610603
'route' => str_replace('//', '/', $route),

0 commit comments

Comments
 (0)