Skip to content

Commit 5c35996

Browse files
committed
Non static methosds should be fired by Reflection.
Added posibility to pass arguments to class constructor.
1 parent 90cfa4f commit 5c35996

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/Route.php

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
namespace PhpRouter;
33

44
use Exception;
5+
use ReflectionClass;
56

67
/**
78
* Class Router
@@ -27,6 +28,10 @@ class Route
2728
* @var callable|string
2829
*/
2930
private $callback;
31+
/**
32+
* @var array
33+
*/
34+
private $callbackArgs = [];
3035
/**
3136
* @var string
3237
*/
@@ -65,15 +70,18 @@ class Route
6570
* @param string $route
6671
* @param array|callable $rules
6772
* @param callable|null $callback
73+
* @param array $callbackArgs
6874
* @throws Exception
6975
*/
70-
public function __construct($route, $rules, $callback = null)
76+
public function __construct($route, $rules, $callback = null, $callbackArgs = [])
7177
{
7278
if (is_callable($rules) || is_string($rules)) {
7379
$this->callback = $rules;
80+
$this->callbackArgs = (array)$callback;
7481
} else {
7582
$this->paramRules = $rules;
7683
$this->callback = $callback;
84+
$this->callbackArgs = (array)$callbackArgs;
7785
}
7886

7987
$this->parseRoute($route);
@@ -188,7 +196,7 @@ public function dispatch()
188196
if (is_callable($this->callback)) {
189197
return call_user_func_array($this->callback, [$this->namedParams]);
190198
} else if (preg_match($this->patterns['callback'], $this->callback, $result)) {
191-
return $this->call($result['class'], $result['method'], [$this->namedParams]);
199+
return $this->call($result['class'], $result['method'], $result['type'], [$this->namedParams]);
192200
}
193201
throw new Exception('Wrong callback');
194202
}
@@ -198,16 +206,22 @@ public function dispatch()
198206
*
199207
* @param string $class
200208
* @param string $method
209+
* @param string $type
201210
* @param array $params
202211
* @return mixed
203212
* @throws Exception
204213
*/
205-
private function call($class, $method, array $params = [])
214+
private function call($class, $method, $type, array $params = [])
206215
{
207-
if (class_exists($class) && method_exists($class, $method)) {
208-
return call_user_func_array([$class, $method], $params);
209-
} else {
216+
if (!class_exists($class) || !method_exists($class, $method)) {
210217
throw new Exception('No class or method found!');
211218
}
219+
220+
if ('->' == $type) {
221+
$reflection = new ReflectionClass($class);
222+
$class = !empty($this->callbackArgs) ? $reflection->newInstanceArgs($this->callbackArgs) : $reflection->newInstance();
223+
}
224+
225+
return call_user_func_array([$class, $method], $params);
212226
}
213227
}

0 commit comments

Comments
 (0)