Adding Shell::wrapText() to extend String methods, with indenting which can be useful in shell output.

This commit is contained in:
mark_story 2010-10-14 22:58:23 -04:00
parent 7b5ae6a5c4
commit 0492a188ed
2 changed files with 50 additions and 0 deletions

View file

@ -447,6 +447,32 @@ class Shell extends Object {
return $result; return $result;
} }
/**
* Wrap a block of text.
* Allows you to set the width, and indenting on a block of text.
*
* ### Options
*
* - `width` The width to wrap to. Defaults to 72
* - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* - `indent` Indent the text with the string provided. Defaults to null.
*
* @param string $text Text the text to format.
* @param mixed $options Array of options to use, or an integer to wrap the text to.
* @return string Wrapped / indented text
*/
public function wrapText($text, $options = array()) {
$wrapped = String::wrap($text, $options);
if (is_array($options) && !empty($options['indent'])) {
$chunks = explode("\n", $wrapped);
foreach ($chunks as &$chunk) {
$chunk = $options['indent'] . $chunk;
}
return implode("\n", $chunks);
}
return $wrapped;
}
/** /**
* Outputs a single or multiple messages to stdout. If no parameters * Outputs a single or multiple messages to stdout. If no parameters
* are passed outputs just a newline. * are passed outputs just a newline.

View file

@ -719,4 +719,28 @@ class ShellTest extends CakeTestCase {
$Shell->runCommand('run_command', array('run_command', 'one', 'value')); $Shell->runCommand('run_command', array('run_command', 'one', 'value'));
} }
/**
* test wrapBlock wrapping text.
*
* @return void
*/
function testWrapText() {
$text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
$result = $this->Shell->wrapText($text, 33);
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertEquals($expected, $result, 'Text not wrapped.');
$result = $this->Shell->wrapText($text, array('indent' => ' ', 'width' => 33));
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertEquals($expected, $result, 'Text not wrapped.');
}
} }