Skip to content

Commit

Permalink
Format array data without errors.
Browse files Browse the repository at this point in the history
If an array ends up in a string template, we should attempt to format
the data gracefully instead of triggering an error. Imploding on ''
seemed like the safest option at hand.

This is necessary to fix issues like #7361
  • Loading branch information
markstory committed Sep 8, 2015
1 parent 5921b2f commit 0049cf6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/View/StringTemplate.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -233,7 +233,11 @@ public function format($name, array $data)
} }
$replace = []; $replace = [];
foreach ($placeholders as $placeholder) { foreach ($placeholders as $placeholder) {
$replace[] = isset($data[$placeholder]) ? $data[$placeholder] : null; $replacement = isset($data[$placeholder]) ? $data[$placeholder] : null;
if (is_array($replacement)) {
$replacement = implode('', $replacement);
}
$replace[] = $replacement;
} }
return vsprintf($template, $replace); return vsprintf($template, $replace);
} }
Expand Down
25 changes: 25 additions & 0 deletions tests/TestCase/View/StringTemplateTest.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -103,6 +103,31 @@ public function testFormat()
$this->assertEquals('<a href="/">example</a>', $result); $this->assertEquals('<a href="/">example</a>', $result);
} }


/**
* Formatting array data should not trigger errors.
*
* @return void
*/
public function testFormatArrayData()
{
$templates = [
'link' => '<a href="{{url}}">{{text}}</a>'
];
$this->template->add($templates);

$result = $this->template->format('link', [
'url' => '/',
'text' => ['example', 'text']
]);
$this->assertEquals('<a href="/">exampletext</a>', $result);

$result = $this->template->format('link', [
'url' => '/',
'text' => ['key' => 'example', 'text']
]);
$this->assertEquals('<a href="/">exampletext</a>', $result);
}

/** /**
* Test loading templates files in the app. * Test loading templates files in the app.
* *
Expand Down

0 comments on commit 0049cf6

Please sign in to comment.