Fabien Potencier 2a2f058f70 feature #4823 Skip the sandbox __toString check on arguments whose PHP parameter type cannot implicitly coerce to string (fabpot)
This PR was squashed before being merged into the 3.x branch.

Discussion
----------

Skip the sandbox `__toString` check on arguments whose PHP parameter type cannot implicitly coerce to string

The sandbox visitor currently wraps every argument of every Twig callable with `CheckToStringNode.

As an optimization, we are now only wrapping when needed (based on the callable type hints). This is a conservative approach (untyped, mixed, string, array, iterable, object, Stringable, Traversable, self/static/parent and unknown class names all keep wrapping).

Here is a concrete before/after for template `{{ demo(a, b) }}` under the sandbox, with the following signature on the PHP side `demo(int $a, string $b)`:

**Before**:

```php
    yield $this->sandbox->ensureToStringAllowed(
       $this->env->getFunction('demo')->getCallable()(
           $this->sandbox->ensureToStringAllowed(($context["a"] ?? null), 1, $this->source),
           $this->sandbox->ensureToStringAllowed(($context["b"] ?? null), 1, $this->source),
       ),
       1, $this->source,
   );
```

**After**

```php
   yield $this->sandbox->ensureToStringAllowed(
       $this->env->getFunction('demo')->getCallable()(
           ($context["a"] ?? null),                                                            // int: bare, skipped
           $this->sandbox->ensureToStringAllowed(($context["b"] ?? null), 1, $this->source),   // string: still wrapped
       ),
       1, $this->source,
   );
```

Commits
-------

6d5ef30436 Skip the sandbox `__toString` check on arguments whose PHP parameter type cannot implicitly coerce to string
2026-06-02 13:58:28 +02:00
2026-02-07 09:07:38 +01:00
2026-05-23 09:03:34 +02:00
2026-02-07 09:12:49 +01:00

Twig, the flexible, fast, and secure template language for PHP
==============================================================

Twig is a template language for PHP.

Twig uses a syntax similar to the Django and Jinja template languages which
inspired the Twig runtime environment.

Sponsors
--------

.. raw:: html

    <a href="https://docs.blackfire.io/introduction?utm_source=twig&utm_medium=github_readme&utm_campaign=logo">
        <img src="https://static.blackfire.io/assets/intemporals/logo/png/blackfire-io_secondary_horizontal_transparent.png?1" width="255px" alt="Blackfire.io">
    </a>

More Information
----------------

Read the `documentation`_ for more information.

.. _documentation: https://twig.symfony.com/documentation
Languages
PHP 99.9%