Skip to content

Commit

Permalink
Forward port fix for wordwrap and newlines (#5582).
Browse files Browse the repository at this point in the history
  • Loading branch information
euromark committed Jan 7, 2015
1 parent f1ff126 commit 8769a37
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Utility/Text.php
Expand Up @@ -306,7 +306,7 @@ public static function wrap($text, $options = [])
}

/**
* 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.
Expand All @@ -315,6 +315,24 @@ public static function wrap($text, $options = [])
* @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 = [];
Expand Down
17 changes: 17 additions & 0 deletions tests/TestCase/Utility/TextTest.php
Expand Up @@ -389,6 +389,23 @@ public function testWordWrapUnicodeAware()
$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 = <<<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.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}

/**
* test wrap method.
*
Expand Down

0 comments on commit 8769a37

Please sign in to comment.