Skip to content

Commit

Permalink
Fix optimizing non-public named closures
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed May 16, 2022
1 parent 137b370 commit dd34e9f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Node/Expression/CallExpression.php
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ private function reflectCallable($callable)
return $this->reflector = [$r, $callable, $r->class.'::'.$r->name];
}

$checkVisibility = $callable instanceof \Closure;
$r = new \ReflectionFunction(\Closure::fromCallable($callable));

if (false !== strpos($r->name, '{closure}')) {
Expand All @@ -305,6 +306,10 @@ private function reflectCallable($callable)
$callable = $callableName = $r->name;
}

if ($checkVisibility && \is_array($callable) && method_exists(...$callable) && !(new \ReflectionMethod(...$callable))->isPublic()) {
$callable = $r->getClosure();
}

return $this->reflector = [$r, $callable, $callableName];
}
}
Expand Down
8 changes: 8 additions & 0 deletions tests/Node/Expression/FilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,17 @@ public function getFilters(): array
{
return [
new TwigFilter('foo', \Closure::fromCallable([$this, 'foo'])),
new TwigFilter('foobar', \Closure::fromCallable([$this, 'foobar'])),
];
}

public function foo()
{
}

protected function foobar()
{
}
};
$environment->addExtension($extension);

Expand Down Expand Up @@ -127,6 +132,9 @@ public function foo()
$node = $this->createFilter($string, 'foo');
$tests[] = [$node, sprintf('$this->extensions[\'%s\']->foo("abc")', \get_class($extension)), $environment];

$node = $this->createFilter($string, 'foobar');
$tests[] = [$node, '$this->env->getFilter(\'foobar\')->getCallable()("abc")', $environment];

return $tests;
}

Expand Down

0 comments on commit dd34e9f

Please sign in to comment.