From d2b7a01a181efa9ff081df1e43226605e33bed8d Mon Sep 17 00:00:00 2001 From: Hidde Boomsma Date: Fri, 31 Mar 2017 12:05:13 +0200 Subject: [PATCH] Prepare for php 7.2 * allow `|length` of `null` * allow `|length` of objects not implementing `\Countable` * To get no errors when running with PHP 7.2 You need to use phpunit ^6.1, otherwise the `each` function, used by phpunit, triggers errors. You can do so by running phpunit like: `SYMFONY_PHPUNIT_VERSION=6.1 phpnightly vendor/bin/simple-phpunit` * --- lib/Twig/Extension/Core.php | 10 +++++++++- .../Tests/Fixtures/filters/length.legacy.test | 16 ++++++++++++++++ test/Twig/Tests/Fixtures/filters/length.test | 3 --- 3 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 test/Twig/Tests/Fixtures/filters/length.legacy.test diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index 58f82c682..62ea64d91 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -1264,6 +1264,10 @@ if (function_exists('mb_get_info')) { */ function twig_length_filter(Twig_Environment $env, $thing) { + if (null === $thing) { + return 0; + } + if (is_scalar($thing)) { return mb_strlen($thing, $env->getCharset()); } @@ -1272,7 +1276,11 @@ if (function_exists('mb_get_info')) { return mb_strlen((string) $thing, $env->getCharset()); } - return count($thing); + if ($thing instanceof \Countable || is_array($thing)) { + return count($thing); + } + + return 1; } /** diff --git a/test/Twig/Tests/Fixtures/filters/length.legacy.test b/test/Twig/Tests/Fixtures/filters/length.legacy.test new file mode 100644 index 000000000..31fc1d915 --- /dev/null +++ b/test/Twig/Tests/Fixtures/filters/length.legacy.test @@ -0,0 +1,16 @@ +--TEST-- +"length" filter +--TEMPLATE-- +{{ null|length }} +{{ magic|length }} +{{ non_countable|length }} +--DATA-- +return array( + 'null' => null, /* triggers deprecation error */ + 'magic' => new MagicCallStub(), /* used to assert we do *not* call __call, also triggers deprecation */ + 'non_countable' => new \StdClass(), /* triggers deprecation error */ +); +--EXPECT-- +0 +1 +1 diff --git a/test/Twig/Tests/Fixtures/filters/length.test b/test/Twig/Tests/Fixtures/filters/length.test index 599c3fd52..5a4c4d5da 100644 --- a/test/Twig/Tests/Fixtures/filters/length.test +++ b/test/Twig/Tests/Fixtures/filters/length.test @@ -6,7 +6,6 @@ {{ number|length }} {{ to_string_able|length }} {{ countable|length }} -{{ magic|length }} --DATA-- return array( 'array' => array(1, 4), @@ -14,7 +13,6 @@ return array( 'number' => 1000, 'to_string_able' => new ToStringStub('foobar'), 'countable' => new CountableStub(42), /* also asserts we do *not* call __toString() */ - 'magic' => new MagicCallStub(), /* used to assert we do *not* call __call */ ); --EXPECT-- 2 @@ -22,4 +20,3 @@ return array( 4 6 42 -1