Skip to content

Commit

Permalink
ControllerFactory::fromArray() allows non-static methods to be called…
Browse files Browse the repository at this point in the history
… with string classname
  • Loading branch information
Daniyal Hamid committed Jul 22, 2021
1 parent 09b6cfe commit 6adee70
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/ControllerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
);
}
Expand Down
3 changes: 3 additions & 0 deletions test/ControllerFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']
],
Expand Down

0 comments on commit 6adee70

Please sign in to comment.