From: Fabien Potencier Date: Sat, 17 Mar 2012 11:42:06 +0000 (+0100) Subject: added preserveKeys support for the slice filter (closes #669) X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=c0a9c8bb3e5d13d88fee6bfc2c39045700c55ea5;p=web%2Fkonrad%2Ftwig.git added preserveKeys support for the slice filter (closes #669) --- diff --git a/CHANGELOG b/CHANGELOG index 195f335..735dd68 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.7.0 (2012-XX-XX) + * added preserveKeys support for the slice filter * fixed the date filter when a DateTime instance is passed with a specific timezone * added a trim filter diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index bdf25ff..ad7faaa 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -559,21 +559,22 @@ function twig_array_merge($arr1, $arr2) /** * Slices a variable. * - * @param Twig_Environment $env A Twig_Environment instance - * @param mixed $item A variable - * @param integer $start Start of the slice - * @param integer $length Size of the slice + * @param Twig_Environment $env A Twig_Environment instance + * @param mixed $item A variable + * @param integer $start Start of the slice + * @param integer $length Size of the slice + * @param Boolean $preserveKeys Whether to preserve key or not (when the input is an array) * * @return mixed The sliced variable */ -function twig_slice(Twig_Environment $env, $item, $start, $length = null) +function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false) { if ($item instanceof Traversable) { $item = iterator_to_array($item, false); } if (is_array($item)) { - return array_slice($item, $start, $length); + return array_slice($item, $start, $length, $preserveKeys); } $item = (string) $item; diff --git a/test/Twig/Tests/Fixtures/filters/slice.test b/test/Twig/Tests/Fixtures/filters/slice.test index 0e3a563..bb32dfb 100644 --- a/test/Twig/Tests/Fixtures/filters/slice.test +++ b/test/Twig/Tests/Fixtures/filters/slice.test @@ -5,7 +5,10 @@ {{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }} {{ [1, 2, 3, 4][start:length]|join('') }} {{ [1, 2, 3, 4]|slice(1, 2)|join('') }} +{{ [1, 2, 3, 4]|slice(1, 2)|keys|join('') }} +{{ [1, 2, 3, 4]|slice(1, 2, true)|keys|join('') }} {{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|join('') }} +{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|keys|join('') }} {{ '1234'|slice(1, 2) }} {{ '1234'[1:2] }} {{ arr|slice(1, 2)|join('') }} @@ -22,7 +25,10 @@ return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3 23 23 23 +01 +12 23 +bc 23 23 23