Expanding String::wrap to be able to indent and start indenting at a specific offset.

This commit is contained in:
mark_story 2010-10-15 22:46:03 -04:00
parent 5f90ac2b45
commit 98a654c4b9
2 changed files with 29 additions and 3 deletions

View file

@ -327,6 +327,8 @@ class String {
*
* - `width` The width to wrap to. Defaults to 72
* - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* - `indent` String to indent with. Defaults to null.
* - `indentAt` 0 based index to start indenting at. Defaults to 0.
*
* @param string $text Text the text to format.
* @param mixed $options Array of options to use, or an integer to wrap the text to.
@ -336,10 +338,19 @@ class String {
if (is_numeric($options)) {
$options = array('width' => $options);
}
$options += array('width' => 72, 'wordWrap' => true);
$options += array('width' => 72, 'wordWrap' => true, 'indent' => null, 'indentAt' => 0);
if ($options['wordWrap']) {
return wordwrap($text, $options['width'], "\n");
$wrapped = wordwrap($text, $options['width'], "\n");
} else {
$wrapped = trim(chunk_split($text, $options['width'] - 1, "\n"));
}
return trim(chunk_split($text, $options['width'] - 1, "\n"));
if (!empty($options['indent'])) {
$chunks = explode("\n", $wrapped);
for ($i = $options['indentAt'], $len = count($chunks); $i < $len; $i++) {
$chunks[$i] = $options['indent'] . $chunks[$i];
}
$wrapped = implode("\n", $chunks);
}
return $wrapped;
}
}

View file

@ -334,4 +334,19 @@ the song that never
TEXT;
$this->assertEquals($expected, $result, 'Text not wrapped.');
}
/**
* test wrap() indenting
*
* @return void
*/
function testWrapIndent() {
$text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
$result = String::wrap($text, array('width' => 33, 'indent' => "\t", 'indentAt' => 1));
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
}
}