twigphp / twigphp/Twig

Using __call in RuntimeExtensionInterface

Open
#3,631 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hi!

I'm facing an issue related to #3451

Consider the following example:

class SomeExtension extends AbstractExtension
{
    private array $filters = [
         'filter1',
         'filter2',
         'filter3',
         // and so on...
    ];

    public function getFilters(): array
    {
        $filters = [];
        foreach ($this->filters as $filter) {
            $filters[] = new TwigFilter(
                $filter,
                [SomeRuntime::class, $filter], // Don't work
                // ["SomeRuntime::$filter"], // Don't work either
                ['is_variadic' => true]
            );
        }

        return $filters;
    }
}

class SomeRuntime implements RuntimeExtensionInterface
{
    private Service $service;

    public function __construct(Service $service)
    {
        $this->service = $service;
    }

    public function __call($name, array $arguments = [])
    {
        $object = $this->service->create($arguments[0]);
        return $object->$name(...$arguments)
    }
}

Note that in my real world example, I make use of the ContainerRuntimeLoader to inject Service in my runtime but I don't think it's relevant here.

Sadly you can't use __call in a RuntimeExtensionInterface because of https://github.com/twigphp/Twig/blob/871747851f17892de24dda275060ad88369baba4/src/Node/Expression/CallExpression.php#L296-L299

Whereas this approach works fine if I use a regular AbstractExtension, not a RuntimeExtensionInterface extension.

It would be great that runtime extension handles this use case too.

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 with src/Node/Expression/CallExpression.php at lines 296-299, then compare how calls from a regular AbstractExtension differ from calls through RuntimeExtensionInterface. Define the runtime behavior needed for __call-based filters and verify that runtime-registered filters can be invoked consistently with regular extensions.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.