From 389f745d169df0e421bd24bdad8f6d4995ffcb27 Mon Sep 17 00:00:00 2001 From: euromark Date: Tue, 6 Jan 2015 13:13:33 +0100 Subject: [PATCH] Stop goofy formatting when newlines are present already. --- lib/Cake/Test/Case/Utility/StringTest.php | 17 +++++++++++++++++ lib/Cake/Utility/String.php | 19 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/Cake/Test/Case/Utility/StringTest.php b/lib/Cake/Test/Case/Utility/StringTest.php index 775f02832..52af3ca2c 100644 --- a/lib/Cake/Test/Case/Utility/StringTest.php +++ b/lib/Cake/Test/Case/Utility/StringTest.php @@ -377,6 +377,23 @@ TEXT; $this->assertTextEquals($expected, $result, 'Text not wrapped.'); } +/** + * test that wordWrap() properly handle newline characters. + * + * @return void + */ + public function testWordWrapNewlineAware() { + $text = 'This is a line that is almost the 55 chars long. +This is a new sentence which is manually newlined, but is so long it needs two lines.'; + $result = String::wordWrap($text, 55); + $expected = <<assertTextEquals($expected, $result, 'Text not wrapped.'); + } + /** * test wrap method. * diff --git a/lib/Cake/Utility/String.php b/lib/Cake/Utility/String.php index 4e0130b58..42b8aab6d 100644 --- a/lib/Cake/Utility/String.php +++ b/lib/Cake/Utility/String.php @@ -346,7 +346,7 @@ class String { } /** - * Unicode aware version of wordwrap. + * Unicode and newline aware version of wordwrap. * * @param string $text The text to format. * @param int $width The width to wrap to. Defaults to 72. @@ -355,6 +355,23 @@ class String { * @return string Formatted text. */ public static function wordWrap($text, $width = 72, $break = "\n", $cut = false) { + $paragraphs = explode($break, $text); + foreach ($paragraphs as &$paragraph) { + $paragraph = String::_wordWrap($paragraph, $width, $break, $cut); + } + return implode($break, $paragraphs); + } + +/** + * Unicode aware version of wordwrap as helper method. + * + * @param string $text The text to format. + * @param int $width The width to wrap to. Defaults to 72. + * @param string $break The line is broken using the optional break parameter. Defaults to '\n'. + * @param bool $cut If the cut is set to true, the string is always wrapped at the specified width. + * @return string Formatted text. + */ + protected static function _wordWrap($text, $width = 72, $break = "\n", $cut = false) { if ($cut) { $parts = array(); while (mb_strlen($text) > 0) {