tweaked twig_to_array

This commit is contained in:
Fabien Potencier
2019-04-10 21:18:04 +02:00
parent 1724e42002
commit 8dd8d0dcb5
2 changed files with 16 additions and 14 deletions
+14 -8
View File
@@ -514,7 +514,9 @@ function twig_replace_filter($str, $from, $to = null)
@trigger_error('Using "replace" with character by character replacement is deprecated since version 1.22 and will be removed in Twig 2.0', E_USER_DEPRECATED);
return strtr($str, $from, $to);
} elseif (!twig_test_iterable($from)) {
}
if (!twig_test_iterable($from)) {
throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', \is_object($from) ? \get_class($from) : \gettype($from)));
}
@@ -739,9 +741,13 @@ function twig_last(Environment $env, $item)
*/
function twig_join_filter($value, $glue = '', $and = null)
{
if (!twig_test_iterable($value)) {
$value = (array) $value;
}
$value = twig_to_array($value, false);
if (!\is_array($value) || 0 === \count($value)) {
if (0 === \count($value)) {
return '';
}
@@ -1465,14 +1471,10 @@ function twig_to_array($seq, $preserveKeys = true)
}
if (!\is_array($seq)) {
return (array) $seq;
return $seq;
}
if (!$preserveKeys) {
return array_values($seq);
}
return $seq;
return $preserveKeys ? $seq : array_values($seq);
}
/**
@@ -1655,6 +1657,10 @@ function twig_constant_is_defined($constant, $object = null)
*/
function twig_array_batch($items, $size, $fill = null, $preserveKeys = true)
{
if (!twig_test_iterable($items)) {
throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($from) ? \get_class($from) : \gettype($from)));
}
$size = ceil($size);
$result = array_chunk(twig_to_array($items, $preserveKeys), $size, $preserveKeys);
+2 -6
View File
@@ -40,16 +40,12 @@ class WithNode extends Node
->write(sprintf('$%s = ', $varsName))
->subcompile($this->getNode('variables'))
->raw(";\n")
->write(sprintf("if (\$%s instanceof \\Traversable) {\n", $varsName))
->indent()
->write(sprintf("\$%s = iterator_to_array(\$%s);\n", $varsName, $varsName))
->outdent()
->write("}\n")
->write(sprintf("if (!is_array(\$%s)) {\n", $varsName))
->write(sprintf("if (!twig_test_iterable(\$%s)) {\n", $varsName))
->indent()
->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.');\n")
->outdent()
->write("}\n")
->write(sprintf("\$%s = twig_to_array(\$%s);\n", $varsName, $varsName))
;
if ($this->getAttribute('only')) {