Issue #2540870 by joelpittet, lauriii: Improve the |safe_join Twig to be inline with twig_join_filter()

8.0.x
Alex Pott 2015-10-30 19:33:18 +00:00
parent 5dc2bd0613
commit a53d5aaf8f
2 changed files with 20 additions and 2 deletions

View File

@ -534,7 +534,7 @@ class TwigExtension extends \Twig_Extension {
* *
* @param \Twig_Environment $env * @param \Twig_Environment $env
* A Twig_Environment instance. * A Twig_Environment instance.
* @param mixed[]|\Traversable $value * @param mixed[]|\Traversable|NULL $value
* The pieces to join. * The pieces to join.
* @param string $glue * @param string $glue
* The delimiter with which to join the string. Defaults to an empty string. * The delimiter with which to join the string. Defaults to an empty string.
@ -545,10 +545,14 @@ class TwigExtension extends \Twig_Extension {
* The strings joined together. * The strings joined together.
*/ */
public function safeJoin(\Twig_Environment $env, $value, $glue = '') { public function safeJoin(\Twig_Environment $env, $value, $glue = '') {
if ($value instanceof \Traversable) {
$value = iterator_to_array($value, false);
}
return implode($glue, array_map(function($item) use ($env) { return implode($glue, array_map(function($item) use ($env) {
// If $item is not marked safe then it will be escaped. // If $item is not marked safe then it will be escaped.
return $this->escapeFilter($env, $item, 'html', NULL, TRUE); return $this->escapeFilter($env, $item, 'html', NULL, TRUE);
}, $value)); }, (array) $value));
} }
} }

View File

@ -200,6 +200,20 @@ class TwigExtensionTest extends UnitTestCase {
]; ];
$result = $twig_extension->safeJoin($twig_environment, $items, '<br/>'); $result = $twig_extension->safeJoin($twig_environment, $items, '<br/>');
$this->assertEquals('&lt;em&gt;will be escaped&lt;/em&gt;<br/><em>will be markup</em><br/><strong>will be rendered</strong>', $result); $this->assertEquals('&lt;em&gt;will be escaped&lt;/em&gt;<br/><em>will be markup</em><br/><strong>will be rendered</strong>', $result);
// Ensure safe_join Twig filter supports Traversable variables.
$items = new \ArrayObject([
'<em>will be escaped</em>',
$markup,
['#markup' => '<strong>will be rendered</strong>'],
]);
$result = $twig_extension->safeJoin($twig_environment, $items, ', ');
$this->assertEquals('&lt;em&gt;will be escaped&lt;/em&gt;, <em>will be markup</em>, <strong>will be rendered</strong>', $result);
// Ensure safe_join Twig filter supports empty variables.
$items = NULL;
$result = $twig_extension->safeJoin($twig_environment, $items, '<br>');
$this->assertEmpty($result);
} }
/** /**