Fabien Potencier f8d4c096ae feature #2420 Make "length" filter and "empty" test consider __toString [Twig 1.x] (mpdude)
This PR was squashed before being merged into the 1.x branch (closes #2420).

Discussion
----------

Make "length" filter and "empty" test consider __toString [Twig 1.x]

Use case: When you have variables in your views that are actually objects but implement `__toString`, they feel like strings: For example, `{{ something }}` will make use of that to-string-conversion.

What does *not* work is

**a)** `{{ something | length }}`, because that will only have a meaningful return value for objects implementing `\Countable`. This interface, however, may have a totally different semantic/purpose for the object in question.

**b)** `{% if something is empty %}`, because

> empty checks if a variable is an empty string, an empty array, an empty hash, exactly false, or exactly null  `[http://twig.sensiolabs.org/doc/2.x/tests/empty.html]`

... and obviously `something !== null` in this case.

For template designers, this may be surprising if they don't actually care about the object-or-string difference, they just "use" the variable.

This change tries to address this as it changes the behavior for  such objects that have a `__toString` method and are *not* `\Countable`.

*Yes*, it's a BC break in edge cases:

For a), objects that implement a `__toString` but not `\Countable` would previously yield `1` for `{{ object | length }}`, and now would return the length of the string returned by `__toString`.

For b), testing (defined) variables that are objects implementing  `__toString` and that return `''`,  the test now is `false`.

Commits
-------

f5193e92 Make "length" filter and "empty" test consider __toString [Twig 1.x]
2017-03-22 07:45:54 -07:00
2017-02-26 16:07:56 -08:00
2017-01-04 14:05:59 -08:00
2017-03-11 20:03:13 +01:00
2017-03-11 20:03:13 +01:00
2017-03-11 20:03:13 +01:00

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

Twig is a template language for PHP, released under the new BSD license (code
and documentation).

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

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

Read the `documentation`_ for more information.

.. _documentation: http://twig.sensiolabs.org/documentation
Languages
PHP 99.9%