Skip to content

Commit 6adee70

Browse files
author
Daniyal Hamid
committed
ControllerFactory::fromArray() allows non-static methods to be called with string classname
1 parent 09b6cfe commit 6adee70

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

src/ControllerFactory.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
use function array_shift;
2222
use function sprintf;
2323
use function is_object;
24-
use function get_class;
24+
use function is_string;
2525

2626
/**
2727
* Creates a new Controller with specified arguments.
@@ -61,12 +61,13 @@ public static function fromArray(array $controller): callable
6161
if (! method_exists($classOrObj, $method)) {
6262
throw new RuntimeException(sprintf(
6363
'"%s::%s()" does not exist',
64-
(is_object($classOrObj)) ? get_class($classOrObj) : (string) $classOrObj,
64+
(is_object($classOrObj)) ? $classOrObj::class : (string) $classOrObj,
6565
$method
6666
));
6767
}
6868

69-
return self::fromCallable([$classOrObj, $method], $controller);
69+
$callable = (is_string($classOrObj)) ? new $classOrObj() : $classOrObj;
70+
return self::fromCallable([$callable, $method], $controller);
7071
}
7172

7273
public static function fromCallable(callable $controller, array $args = []): callable
@@ -75,7 +76,7 @@ public static function fromCallable(callable $controller, array $args = []): cal
7576
return $controller;
7677
}
7778

78-
return fn (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface => (
79+
return static fn (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface => (
7980
$controller($request, $handler, ...$args)
8081
);
8182
}

test/ControllerFactoryTest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ public function callableWithArgsProvider(): array
6060
'DI to instantiated object method' => [
6161
[new Controller(), 'methodAction']
6262
],
63+
'DI to instantiated object method given string class' => [
64+
[Controller::class, 'methodAction']
65+
],
6366
'DI to static method' => [
6467
[Controller::class, 'staticAction']
6568
],

0 commit comments

Comments
 (0)