twigphp / twigphp/Twig

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

Open
#3,323 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
8.4k
Forks
1.3k
Avg merge
1d 13h
Merged PRs (30d)
37

Description

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?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the behavior with index.html.twig, partial.twig, and index.php from the report. Trace Twig's method-invocation handling for array values and callable functions, then determine the intended behavior and verify it with a focused regression test before resolving the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.