Skip to content

Commit 839bc8b

Browse files
committed
Added parameter support for Middlewares. Also, some updates completed.
1 parent dab39f1 commit 839bc8b

File tree

4 files changed

+115
-77
lines changed

4 files changed

+115
-77
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@
44
/vendor/
55
/index.php
66
/.htaccess
7+
.idea
8+

src/Router.php

+33-20
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,28 @@
1818
use Buki\Router\RouterCommand;
1919
use Buki\Router\RouterException;
2020

21+
/**
22+
* Class Router
23+
*
24+
* @method mixed any($route, $settings, $callback = null)
25+
* @method mixed get($route, $settings, $callback = null)
26+
* @method mixed post($route, $settings, $callback = null)
27+
* @method mixed put($route, $settings, $callback = null)
28+
* @method mixed delete($route, $settings, $callback = null)
29+
* @method mixed patch($route, $settings, $callback = null)
30+
* @method mixed head($route, $settings, $callback = null)
31+
* @method mixed options($route, $settings, $callback = null)
32+
* @method mixed xpost($route, $settings, $callback = null)
33+
* @method mixed xput($route, $settings, $callback = null)
34+
* @method mixed xdelete($route, $settings, $callback = null)
35+
* @method mixed xpatch($route, $settings, $callback = null)
36+
*
37+
* @package Buki
38+
*/
2139
class Router
2240
{
2341
/**
24-
* @var string $baseFolder Pattern definations for parameters of Route
42+
* @var string $baseFolder Pattern definitions for parameters of Route
2543
*/
2644
protected $baseFolder;
2745

@@ -36,7 +54,7 @@ class Router
3654
protected $groups = [];
3755

3856
/**
39-
* @var array $patterns Pattern definations for parameters of Route
57+
* @var array $patterns Pattern definitions for parameters of Route
4058
*/
4159
protected $patterns = [
4260
'{a}' => '([^/]+)',
@@ -122,27 +140,23 @@ function __construct(array $params = [])
122140
protected function setPaths($params)
123141
{
124142
if (isset($params['paths']) && $paths = $params['paths']) {
125-
$this->paths['controllers'] =
126-
isset($paths['controllers'])
127-
? trim($paths['controllers'], '/')
128-
: $this->paths['controllers'];
143+
$this->paths['controllers'] = isset($paths['controllers'])
144+
? trim($paths['controllers'], '/')
145+
: $this->paths['controllers'];
129146

130-
$this->paths['middlewares'] =
131-
isset($paths['middlewares'])
132-
? trim($paths['middlewares'], '/')
133-
: $this->paths['middlewares'];
147+
$this->paths['middlewares'] = isset($paths['middlewares'])
148+
? trim($paths['middlewares'], '/')
149+
: $this->paths['middlewares'];
134150
}
135151

136152
if (isset($params['namespaces']) && $namespaces = $params['namespaces']) {
137-
$this->namespaces['controllers'] =
138-
isset($namespaces['controllers'])
139-
? trim($namespaces['controllers'], '\\') . '\\'
140-
: '';
153+
$this->namespaces['controllers'] = isset($namespaces['controllers'])
154+
? trim($namespaces['controllers'], '\\') . '\\'
155+
: '';
141156

142-
$this->namespaces['middlewares'] =
143-
isset($namespaces['middlewares'])
144-
? trim($namespaces['middlewares'], '\\') . '\\'
145-
: '';
157+
$this->namespaces['middlewares'] = isset($namespaces['middlewares'])
158+
? trim($namespaces['middlewares'], '\\') . '\\'
159+
: '';
146160
}
147161

148162
if (isset($params['base_folder'])) {
@@ -331,7 +345,6 @@ public function run()
331345
} else {
332346
foreach ($this->routes as $data) {
333347
$route = $data['route'];
334-
335348
if (strstr($route, ':') !== false || strpos($route, '{') !== false) {
336349
$route = str_replace($searches, $replaces, $route);
337350
}
@@ -615,7 +628,7 @@ private function addRoute($uri, $method, $callback, $settings)
615628
*
616629
* @param $command
617630
* @param $params
618-
* @return null
631+
* @return void
619632
*/
620633
private function runRouteCommand($command, $params = null)
621634
{

src/Router/RouterCommand.php

+33-21
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@ class RouterCommand
2222
protected $namespaces;
2323

2424
/**
25+
* RouterCommand constructor.
2526
*
27+
* @param $baseFolder
28+
* @param $paths
29+
* @param $namespaces
2630
*/
2731
public function __construct($baseFolder, $paths, $namespaces)
2832
{
@@ -48,9 +52,11 @@ public function getControllerInfo()
4852
}
4953

5054
/**
51-
* Get class instance
55+
* @param $baseFolder
56+
* @param $paths
57+
* @param $namespaces
5258
*
53-
* @return RouterCommand
59+
* @return RouterCommand|static
5460
*/
5561
public static function getInstance($baseFolder, $paths, $namespaces)
5662
{
@@ -77,8 +83,6 @@ public function exception($message = '')
7783
* Run Route Middlewares
7884
*
7985
* @param $command
80-
* @param $path
81-
* @param $namespace
8286
*
8387
* @return mixed|void
8488
* @throws
@@ -88,13 +92,18 @@ public function beforeAfter($command)
8892
if (! is_null($command)) {
8993
$info = $this->getMiddlewareInfo();
9094
if (is_array($command)) {
91-
foreach ($command as $key => $value) {
92-
$this->beforeAfter($value, $info['path'], $info['namespace']);
95+
foreach ($command as $value) {
96+
$this->beforeAfter($value);
9397
}
9498
} elseif (is_string($command)) {
95-
$controller = $this->resolveClass($command, $info['path'], $info['namespace']);
99+
$middleware = explode(':', $command);
100+
$params = [];
101+
if (count($middleware) > 1) {
102+
$params = explode(',', $middleware[1]);
103+
}
104+
$controller = $this->resolveClass($middleware[0], $info['path'], $info['namespace']);
96105
if (method_exists($controller, 'handle')) {
97-
$response = call_user_func([$controller, 'handle']);
106+
$response = call_user_func_array([$controller, 'handle'], $params);
98107
if ($response !== true) {
99108
echo $response;
100109
exit;
@@ -115,10 +124,8 @@ public function beforeAfter($command)
115124
*
116125
* @param $command
117126
* @param $params
118-
* @param $path
119-
* @param $namespace
120127
*
121-
* @return void
128+
* @return mixed|void
122129
* @throws
123130
*/
124131
public function runRoute($command, $params = null)
@@ -131,22 +138,16 @@ public function runRoute($command, $params = null)
131138

132139
$controller = $this->resolveClass($controllerClass, $info['path'], $info['namespace']);
133140
if (method_exists($controller, $controllerMethod)) {
134-
echo call_user_func_array(
135-
[$controller, $controllerMethod],
136-
(!is_null($params) ? $params : [])
137-
);
141+
echo $this->runMethodWithParams([$controller, $controllerMethod], $params);
138142
return;
139143
}
140144

141145
return $this->exception($controllerMethod . ' method is not found in '.$controllerClass.' class.');
142146
} else {
143-
if (! is_null($params)) {
144-
echo call_user_func_array($command, $params);
145-
return;
146-
}
147-
148-
echo call_user_func($command);
147+
echo $this->runMethodWithParams($command, $params);
149148
}
149+
150+
return;
150151
}
151152

152153
/**
@@ -173,4 +174,15 @@ protected function resolveClass($class, $path, $namespace)
173174

174175
return new $class();
175176
}
177+
178+
/**
179+
* @param $function
180+
* @param $params
181+
*
182+
* @return mixed
183+
*/
184+
protected function runMethodWithParams($function, $params)
185+
{
186+
return call_user_func_array($function, (!is_null($params) ? $params : []));
187+
}
176188
}

src/Router/RouterRequest.php

+47-36
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class RouterRequest
1515
/**
1616
* @var string $validMethods Valid methods for Requests
1717
*/
18-
public static $validMethods = 'GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|ANY|AJAX|AJAXP';
18+
public static $validMethods = 'GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|ANY|AJAX|XPOST|XPUT|XDELETE|XPATCH';
1919

2020
/**
2121
* Request method validation
@@ -42,6 +42,33 @@ public static function validMethod($data, $method)
4242
return $valid;
4343
}
4444

45+
/**
46+
* Get the request method used, taking overrides into account
47+
*
48+
* @return string
49+
*/
50+
public static function getRequestMethod()
51+
{
52+
// Take the method as found in $_SERVER
53+
$method = $_SERVER['REQUEST_METHOD'];
54+
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
55+
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
56+
if ($method === 'HEAD') {
57+
ob_start();
58+
$method = 'GET';
59+
} elseif ($method === 'POST') {
60+
$headers = self::getRequestHeaders();
61+
if (isset($headers['X-HTTP-Method-Override']) &&
62+
in_array($headers['X-HTTP-Method-Override'], ['PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'])) {
63+
$method = $headers['X-HTTP-Method-Override'];
64+
} elseif (! empty($_POST['_method'])) {
65+
$method = strtoupper($_POST['_method']);
66+
}
67+
}
68+
69+
return $method;
70+
}
71+
4572
/**
4673
* check method valid
4774
*
@@ -52,16 +79,21 @@ public static function validMethod($data, $method)
5279
*/
5380
protected static function checkMethods($value, $method)
5481
{
55-
$valid = false;
56-
if ($value === 'AJAX' && self::isAjax() && $value === $method) {
57-
$valid = true;
58-
} elseif ($value === 'AJAXP' && self::isAjax() && $method === 'POST') {
59-
$valid = true;
60-
} elseif (in_array($value, explode('|', self::$validMethods)) && ($value === $method || $value === 'ANY')) {
61-
$valid = true;
82+
if (in_array($value, explode('|', self::$validMethods))) {
83+
if (self::isAjax() && $value === 'AJAX') {
84+
return true;
85+
}
86+
87+
if (self::isAjax() && strpos($value, 'X') === 0 && $method === ltrim($value, 'X')) {
88+
return true;
89+
}
90+
91+
if (in_array($value, [$method, 'ANY'])) {
92+
return true;
93+
}
6294
}
6395

64-
return $valid;
96+
return false;
6597
}
6698

6799
/**
@@ -90,36 +122,15 @@ protected static function getRequestHeaders()
90122
$headers = [];
91123
foreach ($_SERVER as $name => $value) {
92124
if (substr($name, 0, 5) == 'HTTP_' || $name === 'CONTENT_TYPE' || $name === 'CONTENT_LENGTH') {
93-
$headers[str_replace([' ', 'Http'], ['-', 'HTTP'], ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
125+
$headerKey = str_replace(
126+
[' ', 'Http'],
127+
['-', 'HTTP'],
128+
ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))
129+
);
130+
$headers[$headerKey] = $value;
94131
}
95132
}
96133

97134
return $headers;
98135
}
99-
100-
/**
101-
* Get the request method used, taking overrides into account
102-
*
103-
* @return string
104-
*/
105-
public static function getRequestMethod()
106-
{
107-
// Take the method as found in $_SERVER
108-
$method = $_SERVER['REQUEST_METHOD'];
109-
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
110-
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
111-
if ($method === 'HEAD') {
112-
ob_start();
113-
$method = 'GET';
114-
} elseif ($method === 'POST') {
115-
$headers = self::getRequestHeaders();
116-
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], ['PUT', 'DELETE', 'PATCH', 'OPTIONS'])) {
117-
$method = $headers['X-HTTP-Method-Override'];
118-
} elseif (! empty($_POST['_method'])) {
119-
$method = strtoupper($_POST['_method']);
120-
}
121-
}
122-
123-
return $method;
124-
}
125136
}

0 commit comments

Comments
 (0)