mirror of
https://github.com/kamilwylegala/cakephp2-php8.git
synced 2025-01-19 02:56:15 +00:00
Adding String::wrap() to handle wrapping strings for console output.
This commit is contained in:
parent
b8467164f8
commit
7b5ae6a5c4
2 changed files with 50 additions and 0 deletions
|
@ -319,4 +319,27 @@ class String {
|
|||
}
|
||||
return $str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps text to a specific width, can optionally wrap at word breaks.
|
||||
*
|
||||
* ### Options
|
||||
*
|
||||
* - `width` The width to wrap to. Defaults to 72
|
||||
* - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
|
||||
*
|
||||
* @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 Formatted text.
|
||||
*/
|
||||
public static function wrap($text, $options = array()) {
|
||||
if (is_numeric($options)) {
|
||||
$options = array('width' => $options);
|
||||
}
|
||||
$options += array('width' => 72, 'wordWrap' => true);
|
||||
if ($options['wordWrap']) {
|
||||
return wordwrap($text, $options['width'], "\n");
|
||||
}
|
||||
return trim(chunk_split($text, $options['width'] - 1, "\n"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -307,4 +307,31 @@ class StringTest extends CakeTestCase {
|
|||
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
|
||||
$this->assertEqual($expected, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* test wrap method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
function testWrap() {
|
||||
$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, 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 = String::wrap($text, array('width' => 20, 'wordWrap' => false));
|
||||
$expected = <<<TEXT
|
||||
This is the song th
|
||||
at never ends. This
|
||||
is the song that n
|
||||
ever ends. This is
|
||||
the song that never
|
||||
ends.
|
||||
TEXT;
|
||||
$this->assertEquals($expected, $result, 'Text not wrapped.');
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue