From 6adee70c6b113e79c2d343d071d1340a2b609519 Mon Sep 17 00:00:00 2001 From: Daniyal Hamid Date: Fri, 23 Jul 2021 01:27:00 +0200 Subject: [PATCH] ControllerFactory::fromArray() allows non-static methods to be called with string classname --- src/ControllerFactory.php | 9 +++++---- test/ControllerFactoryTest.php | 3 +++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/ControllerFactory.php b/src/ControllerFactory.php index cd19a8b..42d59b6 100644 --- a/src/ControllerFactory.php +++ b/src/ControllerFactory.php @@ -21,7 +21,7 @@ use function array_shift; use function sprintf; use function is_object; -use function get_class; +use function is_string; /** * Creates a new Controller with specified arguments. @@ -61,12 +61,13 @@ public static function fromArray(array $controller): callable if (! method_exists($classOrObj, $method)) { throw new RuntimeException(sprintf( '"%s::%s()" does not exist', - (is_object($classOrObj)) ? get_class($classOrObj) : (string) $classOrObj, + (is_object($classOrObj)) ? $classOrObj::class : (string) $classOrObj, $method )); } - return self::fromCallable([$classOrObj, $method], $controller); + $callable = (is_string($classOrObj)) ? new $classOrObj() : $classOrObj; + return self::fromCallable([$callable, $method], $controller); } public static function fromCallable(callable $controller, array $args = []): callable @@ -75,7 +76,7 @@ public static function fromCallable(callable $controller, array $args = []): cal return $controller; } - return fn (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface => ( + return static fn (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface => ( $controller($request, $handler, ...$args) ); } diff --git a/test/ControllerFactoryTest.php b/test/ControllerFactoryTest.php index 58c2444..2379902 100644 --- a/test/ControllerFactoryTest.php +++ b/test/ControllerFactoryTest.php @@ -60,6 +60,9 @@ public function callableWithArgsProvider(): array 'DI to instantiated object method' => [ [new Controller(), 'methodAction'] ], + 'DI to instantiated object method given string class' => [ + [Controller::class, 'methodAction'] + ], 'DI to static method' => [ [Controller::class, 'staticAction'] ],