Skip to content

Commit

Permalink
Adding Shell::wrapText() to extend String methods, with indenting whi…
Browse files Browse the repository at this point in the history
…ch can be useful in shell output.
  • Loading branch information
markstory committed Oct 15, 2010
1 parent 7b5ae6a commit 0492a18
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cake/console/libs/shell.php
Expand Up @@ -447,6 +447,32 @@ protected function _getInput($prompt, $options, $default) {
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
* are passed outputs just a newline.
Expand Down
24 changes: 24 additions & 0 deletions cake/tests/cases/console/libs/shell.test.php
Expand Up @@ -719,4 +719,28 @@ function testRunCommandHittingTask() {

$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.');
}
}

0 comments on commit 0492a18

Please sign in to comment.