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

Exception "Impossible to invoke a method ("...") on an array" when passing a function to an included template #3323

Open
ericmorand opened this issue May 8, 2020 · 1 comment

Comments

@ericmorand
Copy link
Contributor

Consider the following Twig templates:

index.html.twig

{{ obj.foo() }}
{% include "partial.twig" with {
    obj2: {
        foo: obj.foo
    }
} %}

partial.twig

{{ obj2.foo() }}

And the following PHP script:

index.php

<?php

require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('.');
$twig = new \Twig\Environment($loader, [
    'strict_variables' => true
]);

class Foo {
    function foo() {
        return 'foo';
    }
}

echo $twig->render('index.html.twig', ['obj' => new Foo()]);

Running this script throws the exception "Impossible to invoke a method ("foo") on an array.".

It makes impossible to pass functions to included templates because Twig accepts function calls from class instances but not from its internal array representation.

We can narrow the issue to this:

echo $twig->render('index.html.twig', ['obj' => ['foo' => function() {
    return 'foo';
}]]);

I'm sure this is deliberate from Twig contributors. But, what is the rational against allowing calling functions that are part of the items contained into an array?

@stof
Copy link
Member

stof commented Jul 9, 2020

Allowing to call methods on object is there to allow using getters (forcing to make all properties public to be able to use them would be a no-go). It can indeed be abused to do something else if you want to call another kind of method (if you don't trust the author of the templates, that's what the SandboxExtension is for)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants