Created
September 23, 2011 07:25
-
-
Save kiltec/1236896 to your computer and use it in GitHub Desktop.
Wordwrap Kata in PHP. See: http://sites.google.com/site/tddproblems/all-problems-1/word-wrapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class WordWrapTest extends PHPUnit_Framework_TestCase { | |
public function testDoNotWrapWhenNoText() { | |
$text = ""; | |
$actual = word_wrap($text, 60); | |
$this->assertEquals("", $actual); | |
} | |
public function testNoWrapWhenTextSmallerThanRowLength() { | |
$text = "This fits!"; | |
$actual = word_wrap($text, 60); | |
$this->assertEquals($text, $actual); | |
} | |
public function testNoWrapWhenTextFitsExactlyInRow() { | |
$text = "1234567890"; | |
$actual = word_wrap($text, 10); | |
$this->assertEquals($text, $actual); | |
} | |
public function testWrapWhenRowLengthSameAsFirstWordLength() { | |
$text = "abc def"; | |
$actual = word_wrap($text, 3); | |
$expected = array("abc", "def"); | |
$this->assertEquals($expected, $actual); | |
} | |
public function testWrapWhenRowLengthShorterThanFirstWordLength() { | |
$text = "abcdef"; | |
$actual = word_wrap($text, 3); | |
$expected = array("abc", "def"); | |
$this->assertEquals($expected, $actual); | |
} | |
public function testWrapTwoWords() { | |
$text = "abcdef ghi"; | |
$actual = word_wrap($text, 3); | |
$expected = array("abc", "def", "ghi"); | |
$this->assertEquals($expected, $actual); | |
} | |
public function testWrapLotsOfSingleLetterWords() { | |
$text = "a b c d e f"; | |
$actual = word_wrap($text, 3); | |
$expected = array("a b", "c d", "e f"); | |
$this->assertEquals($expected, $actual); | |
} | |
} | |
function word_wrap($text, $row_length) { | |
if(strlen($text) <= $row_length) { | |
return $text; | |
} else { | |
$lines = array(); | |
while($text) { | |
$lines[] = trim(substr($text, 0, $row_length)); | |
$text = trim(substr($text, $row_length)); | |
} | |
return $lines; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment