From 98a654c4b9857a9a38d02d96e5312b9f54b38c9c Mon Sep 17 00:00:00 2001 From: mark_story Date: Fri, 15 Oct 2010 22:46:03 -0400 Subject: [PATCH] Expanding String::wrap to be able to indent and start indenting at a specific offset. --- cake/libs/string.php | 17 ++++++++++++++--- cake/tests/cases/libs/string.test.php | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/cake/libs/string.php b/cake/libs/string.php index c7c0694f3..affcc263b 100644 --- a/cake/libs/string.php +++ b/cake/libs/string.php @@ -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; } } diff --git a/cake/tests/cases/libs/string.test.php b/cake/tests/cases/libs/string.test.php index 39103c227..1e5e84d54 100644 --- a/cake/tests/cases/libs/string.test.php +++ b/cake/tests/cases/libs/string.test.php @@ -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 = <<