From f29494dea02967e021aaca059195dc1d22825b97 Mon Sep 17 00:00:00 2001 From: Malte Wunsch Date: Wed, 30 Oct 2024 11:08:07 +0100 Subject: [PATCH] Allow usage of invokable controllers --- src/Handler/EmbeddedShortcodeHandler.php | 23 +++++++++++++++---- .../EmbeddedShortcodeHandlerTest.php | 1 + 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Handler/EmbeddedShortcodeHandler.php b/src/Handler/EmbeddedShortcodeHandler.php index 56179fc..d42fbd2 100644 --- a/src/Handler/EmbeddedShortcodeHandler.php +++ b/src/Handler/EmbeddedShortcodeHandler.php @@ -41,10 +41,7 @@ public function __construct( RequestStack $requestStack, ?LoggerInterface $logger = null ) { - $callableFragments = explode('::', $controllerName); - if (!\is_array($callableFragments) || !isset($callableFragments[1]) || !method_exists($callableFragments[0], $callableFragments[1])) { - throw new InvalidArgumentException('The controller method: "'.$controllerName.'" does not exist.'); - } + $this->validateControllerName($controllerName); $this->fragmentHandler = $fragmentHandler; $this->controllerName = $controllerName; @@ -92,4 +89,22 @@ public function getControllerName(): string { return $this->controllerName; } + + private function validateControllerName(string $controllerName): void + { + if (class_exists($controllerName)) { + // Check with method_exists instead of is_callable, because is_callable would need an object instance to + // positively test an invokable classes + if (method_exists($controllerName, '__invoke')) { + return; + } + + throw new InvalidArgumentException('The configured controller "'.$controllerName.'" does not refer a method. Although a class "'.$controllerName.'" exists, but has no __invoke method.'); + } + + $callableFragments = explode('::', $controllerName); + if (!\is_array($callableFragments) || !isset($callableFragments[1]) || !method_exists($callableFragments[0], $callableFragments[1])) { + throw new InvalidArgumentException('The controller method: "'.$controllerName.'" does not exist.'); + } + } } diff --git a/tests/Functional/EmbeddedShortcodeHandlerTest.php b/tests/Functional/EmbeddedShortcodeHandlerTest.php index 763b5cf..b814d63 100644 --- a/tests/Functional/EmbeddedShortcodeHandlerTest.php +++ b/tests/Functional/EmbeddedShortcodeHandlerTest.php @@ -92,6 +92,7 @@ public static function provideControllerNames(): Generator yield 'Not existing controller' => ['Foo\Bar::baz']; yield 'Missing method name' => [ShortcodeTestController::class]; yield 'Not existing method' => [ShortcodeTestController::class.'_notExistingMethod']; + yield 'Missing class' => ['ThisClassDoesNotExist']; } private function processShortcodes(string $content, ?Request $request = null): string