Added state cloning if it is object

This commit is contained in:
X25
2014-04-19 17:20:54 +04:00
parent 314fc18556
commit 90696ad348
3 changed files with 43 additions and 8 deletions

View File

@@ -4,11 +4,11 @@ namespace DesignPatterns\Memento;
class Memento
{
/* @var string */
/* @var mixed */
private $state;
/**
* @param string $stateToSave
* @param mixed $stateToSave
*/
public function __construct($stateToSave)
{
@@ -16,7 +16,7 @@ class Memento
}
/**
* @return string
* @return mixed
*/
public function getState()
{

View File

@@ -4,14 +4,14 @@ namespace DesignPatterns\Memento;
class Originator
{
/* @var string */
/* @var mixed */
private $state;
// The class could also contain additional data that is not part of the
// state saved in the memento..
/**
* @param string $state
* @param mixed $state
*/
public function setState($state)
{
@@ -23,7 +23,9 @@ class Originator
*/
public function saveToMemento()
{
return new Memento($this->state);
$state = is_object($this->state) ? clone $this->state : $this->state;
return new Memento($state);
}
public function restoreFromMemento(Memento $memento)

View File

@@ -5,12 +5,12 @@ namespace DesignPatterns\Tests\Memento;
use DesignPatterns\Memento;
/**
* MementoTest tests memento design pattern
* MementoTest tests the memento pattern
*/
class MementoTest extends \PHPUnit_Framework_TestCase
{
public function testOriginator()
public function testStringState()
{
$originator = new Memento\Originator();
$originator->setState("State1");
@@ -33,4 +33,37 @@ class MementoTest extends \PHPUnit_Framework_TestCase
$this->assertAttributeEquals("State2", "state", $originator);
}
public function testObjectState()
{
$originator = new Memento\Originator();
$foo = new \stdClass();
$foo->data = "foo";
$originator->setState($foo);
$this->assertAttributeEquals($foo, "state", $originator);
$savedState = $originator->saveToMemento();
$this->assertAttributeEquals($foo, "state", $savedState);
$bar = new \stdClass();
$bar->data = "bar";
$originator->setState($bar);
$this->assertAttributeEquals($bar, "state", $originator);
$originator->restoreFromMemento($savedState);
$this->assertAttributeEquals($foo, "state", $originator);
$foo->data = null;
$this->assertAttributeNotEquals($foo, "state", $savedState);
$this->assertAttributeNotEquals($foo, "state", $originator);
}
}