adds support for invoking closures

This commit is contained in:
Faizan Akram
2024-12-12 14:42:49 +01:00
committed by Fabien Potencier
parent 77376c9302
commit 0a61801d9a
3 changed files with 12 additions and 0 deletions
+1
View File
@@ -2,6 +2,7 @@
* Fix the null coalescing operator when the test returns null
* Fix the Elvis operator when used as '? :' instead of '?:'
* Support for invoking closures
# 3.17.0 (2024-12-10)
+7
View File
@@ -1740,6 +1740,10 @@ final class CoreExtension extends AbstractExtension
static $propertyCheckers = [];
if ($object instanceof \Closure && '__invoke' === $item) {
return $isDefinedTest ? true : $object();
}
if (isset($object->$item)
|| ($propertyCheckers[$object::class][$item] ??= self::getPropertyChecker($object::class, $item))($object, $item)
) {
@@ -1777,6 +1781,9 @@ final class CoreExtension extends AbstractExtension
// 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 = [];
+4
View File
@@ -394,6 +394,10 @@ class TemplateTest extends TestCase
[true, ['foo' => 'bar'], $arrayAccess, 'vars', [], $anyType],
]);
// test for Closure::__invoke()
$tests[] = [true, 'closure called', fn (): string => 'closure called', '__invoke', [], $anyType];
$tests[] = [true, 'closure called', fn (): string => 'closure called', '__invoke', [], $methodType];
// 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".'],