From 12c41d3daf0cef9a3ff9232f6eb9203d1dbbaa74 Mon Sep 17 00:00:00 2001 From: Faizan Akram Date: Thu, 12 Dec 2024 14:42:49 +0100 Subject: [PATCH] adds support for invoking closures - fixes #3848 --- src/Extension/CoreExtension.php | 3 +++ tests/TemplateTest.php | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/src/Extension/CoreExtension.php b/src/Extension/CoreExtension.php index b60944c4a4e..d3d637c05e4 100644 --- a/src/Extension/CoreExtension.php +++ b/src/Extension/CoreExtension.php @@ -1777,6 +1777,9 @@ public static function getAttribute(Environment $env, Source $source, $object, $ // precedence: getXxx() > isXxx() > hasXxx() if (!isset($cache[$class])) { $methods = get_class_methods($object); + if ($object instanceof \Closure) { + $methods[] = '__invoke'; + } sort($methods); $lcMethods = array_map('strtolower', $methods); $classCache = []; diff --git a/tests/TemplateTest.php b/tests/TemplateTest.php index 4d2489962f7..3f1656e52c3 100644 --- a/tests/TemplateTest.php +++ b/tests/TemplateTest.php @@ -394,6 +394,13 @@ public static function getGetAttributeTests() [true, ['foo' => 'bar'], $arrayAccess, 'vars', [], $anyType], ]); + // test for Closure::__invoke() + $closure = function (): string { + return 'closure called'; + }; + + $tests[] = [true, 'closure called', $closure, '__invoke', [], $anyType]; + // tests when input is not an array or object $tests = array_merge($tests, [ [false, null, 42, 'a', [], $anyType, 'Impossible to access an attribute ("a") on a int variable ("42") in "index.twig".'],