Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds support for invoking closures #4501

Open
wants to merge 2 commits into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
7 changes: 7 additions & 0 deletions src/Extension/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -1740,6 +1740,10 @@ public static function getAttribute(Environment $env, Source $source, $object, $

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)
) {
Expand Down Expand Up @@ -1777,6 +1781,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 = [];
Expand Down
4 changes: 4 additions & 0 deletions tests/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ public static function getGetAttributeTests()
[true, ['foo' => 'bar'], $arrayAccess, 'vars', [], $anyType],
]);

// test for Closure::__invoke()
$tests[] = [true, 'closure called', fn (): string => 'closure called', '__invoke', [], $anyType];
faizanakram99 marked this conversation as resolved.
Show resolved Hide resolved
$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".'],
Expand Down