<?php
namespace Ampersand\DevTest\BasicOop;
interface NumberInterface
{
/**
* Adds n to this number
*
* @param int $n The amount to add to this number
* @return int The new integer value of this number
*/
public function add($n);
/**
* Subtracts n from this number
*
* @param int $n The amount to subtract from this number
* @return int The new integer value of this number
*/
public function subtract($n);
/**
* Multiplies this number by n
*
* @param int $n The amount to multiply this number by
* @return int The new integer value of this number
*/
public function multiply($n);
/**
* Divides this number by n
*
* @param int $n The amount to divide this number by
* @return int The new integer value of this number
*/
public function divide($n);
/**
* Returns the integer value of this number
*
* @return int The current integer value of this number
*/
public function toInt();
}
class NumberTest
{
public function testConstruct()
{
$n = new Number;
$this->assertEquals(0, $n->toInt());
$n = new Number(0);
$this->assertEquals(0, $n->toInt());
$n = new Number(3);
$this->assertEquals(3, $n->toInt());
}
public function testAdd()
{
$n = new Number;
$n->add(5);
$this->assertEquals(5, $n->toInt());
$n->add(-7);
$this->assertEquals(-2, $n->toInt());
}
public function testSubtract()
{
$n = new Number;
$n->subtract(8);
$this->assertEquals(-8, $n->toInt());
$n->subtract(-10);
$this->assertEquals(2, $n->toInt());
}
public function testMultiply()
{
$n = new Number(1);
$n->multiply(10);
$this->assertEquals(10, $n->toInt());
$n->multiply(6);
$this->assertEquals(60, $n->toInt());
}
public function testDivide()
{
$n = new Number(100);
$n->divide(5);
$this->assertEquals(20, $n->toInt());
$n->divide(5);
$this->assertEquals(4, $n->toInt());
$hasThrownEx = false;
try {
$n->divide(0);
} catch (\InvalidArgumentException $e) {
$hasThrownEx = true;
}
$this->assertEquals(true, $hasThrownEx);
}
private function assertEquals($expected, $actual)
{
if ($expected !== $actual) {
echo "\n";
var_dump($actual);
echo ' does not match expected ';
var_dump($expected);
echo "\n";
} else {
echo '.';
}
}
}
class Number implements NumberInterface
{
private $value;
public function __construct($value = 0)
{
$this->value = $value;
}
public function add($value)
{
$this->value += $value;
return $this->value;
}
public function subtract($value)
{
$this->value -= $value;
return $this->value;
}
public function multiply($value)
{
$this->value *= $value;
return $this->value;
}
public function divide($value)
{
if (0 === $value) {
throw new \InvalidArgumentException;
}
$this->value /= $value;
return $this->value;
}
public function toInt()
{
return $this->value;
}
}
$test = new NumberTest;
$test->testConstruct();
$test->testAdd();
$test->testSubtract();
$test->testMultiply();
$test->testDivide();