diff --git a/src/Route.php b/src/Route.php index 5941421..c37e3e9 100644 --- a/src/Route.php +++ b/src/Route.php @@ -23,6 +23,8 @@ class Route private $invoker = null; private $middleware = []; private $paramConstraints = []; + private $controllerName = null; + private $controllerMethod = null; public function __construct(array $methods, string $uri, $action, Invoker $invoker = null) { @@ -50,6 +52,9 @@ private function setAction($action) private function convertClassStringToClosure($string) { + $this->controllerName = null; + $this->controllerMethod = null; + @list($className, $method) = explode('@', $string); if (!isset($className) || !isset($method)) { @@ -68,6 +73,9 @@ private function convertClassStringToClosure($string) throw new RouteClassStringMethodNotFoundException('Route controller class: `' . $className . '` does not have a `' . $method . '` method'); } + $this->controllerName = $className; + $this->controllerMethod = $method; + return function ($params = null) use ($className, $method) { $controller = new $className; return $controller->$method($params); @@ -170,4 +178,19 @@ public function getName() { return $this->name; } + + public function getActionName() + { + $callableName = null; + + if (isset($this->controllerName)) { + return $this->controllerName; + } + + if (is_callable($this->action, false, $callableName)) { + list($controller, $method) = explode('::', $callableName); + + return $controller; + } + } } diff --git a/tests/RouteTest.php b/tests/RouteTest.php index b4851ac..88d7097 100644 --- a/tests/RouteTest.php +++ b/tests/RouteTest.php @@ -63,4 +63,47 @@ public function where_function_throws_exception_when_no_params_provided() $this->assertInstanceOf(Route::class, $router->get('test/{id}', function () {})->where()); } + + /** @test */ + public function can_get_route_action_name_when_closure() + { + $router = new Router; + $route = $router->get('test/123', function () {}); + + $this->assertSame('Closure', $route->getActionName()); + } + + /** @test */ + public function can_get_route_action_name_when_callable() + { + $router = new Router; + $route = $router->get('test/123', [TestCallableController::class, 'testStatic']); + + $this->assertSame(TestCallableController::class, $route->getActionName()); + } + + /** @test */ + public function can_get_route_action_name_when_callable_instance() + { + $router = new Router; + $controller = new TestCallableController; + $route = $router->get('test/123', [$controller, 'test']); + + $this->assertSame(TestCallableController::class, $route->getActionName()); + } + + /** @test */ + public function can_get_route_action_name_when_controller_string() + { + $router = new Router; + $route = $router->get('test/123', TestCallableController::class.'@test'); + + $this->assertSame(TestCallableController::class, $route->getActionName()); + } +} + +class TestCallableController +{ + public static function testStatic() {} + public function test() {} }