Skip to content

Instantly share code, notes, and snippets.

@peinwag
Last active December 23, 2015 15:59
Show Gist options
  • Save peinwag/6659063 to your computer and use it in GitHub Desktop.
Save peinwag/6659063 to your computer and use it in GitHub Desktop.
tdd session phpunconference2013
<?php
class StringCalculator
{
public function add($numbers)
{
$separators = array(',', "\n");
$matches = null;
preg_match_all("~^\[(.)\]*~", $numbers, $matches);
if(isset($matches[1][0]) && $matches[1][0] != null) {
$separators[] = $matches[1][0];
$numbers = substr($numbers, strlen($matches[0][0]) , strlen($numbers) - strlen($matches[0][0]));
}
foreach ($separators as $separator) {
if(strstr($numbers, $separator)) {
break;
}
}
$numbers = explode($separator, $numbers);
return array_sum($numbers);
}
}
class StringCalculatorTest extends PHPUnit_Framework_TestCase
{
public function testAddEmptyString()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("");
$this->assertSame(0, $result);
}
public function testAddOneNumber()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("7");
$this->assertSame(7, $result);
}
public function testAddTwoNumbersCommaSeparated()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("3,8");
$this->assertSame(11, $result);
}
public function testAddThreeNumbersCommaSeparated()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("3,8,7");
$this->assertSame(18, $result);
}
public function testAddTwoNumbersNewlineSeparated()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("3\n8");
$this->assertSame(11, $result);
}
public function testAddThreeNumbersConfigurableDelimiterSeparated()
{
$stringCalculator = new StringCalculator();
$result = $stringCalculator->add("[q]3q8q7");
$this->assertSame(18, $result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment