Skip to content

Commit

Permalink
Add detections on removal / additions in Set::compute
Browse files Browse the repository at this point in the history
  • Loading branch information
Taluu committed Nov 15, 2013
1 parent 441e2d6 commit 0048e4c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
18 changes: 12 additions & 6 deletions src/Totem/Set.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
use Totem\AbstractSnapshot,
Totem\Exception\IncomparableDataException,

Totem\Change\Removal,
Totem\Change\Addition,
Totem\Change\Deletion,
Totem\Change\Modification,

Totem\Snapshot\ArraySnapshot,
Expand Down Expand Up @@ -131,13 +131,14 @@ public function count()
*/
private function compute(AbstractSnapshot $old, AbstractSnapshot $new)
{
if ($old->getDataKeys() !== $new->getDataKeys()) {
throw new \InvalidArgumentException('You can\'t compare two snapshots having a different structure');
}

$this->changes = [];

foreach ($new->getDataKeys() as $key) {
foreach ($old->getDataKeys() as $key) {
if (!isset($new[$key])) {
$this->changes[$key] = new Removal($old[$key] instanceof AbstractSnapshot ? $old[$key]->getRawData() : $old[$key]);
continue;
}

$current = ['old' => $old[$key] instanceof AbstractSnapshot ? $old[$key]->getRawData() : $old[$key],
'new' => $new[$key] instanceof AbstractSnapshot ? $new[$key]->getRawData() : $new[$key]];

Expand Down Expand Up @@ -165,6 +166,11 @@ private function compute(AbstractSnapshot $old, AbstractSnapshot $new)
}
}
}

// added elements
foreach (array_diff($new->getDataKeys(), $old->getDataKeys()) as $key) {
$this->changes[$key] = new Addition($new[$key] instanceof AbstractSnapshot ? $new[$key]->getRawData() : $new[$key]);
}
}
}

13 changes: 6 additions & 7 deletions test/Totem/SetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,19 @@
class SetTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @dataProvider invalidEntryProvider
*/
public function testSetChangesWithInvalidEntity($old, $new)
public function testSetChangesWithChangedStructure($old, $new, $class)
{
new Set(new Snapshot(['data' => $old]), new Snapshot(['data' => $new]));
$set = new Set(new Snapshot(['data' => $old]), new Snapshot(['data' => $new]));

$this->assertInstanceOf('Totem\\Change\\' . $class, $set->getChange('1'));
}

public function invalidEntryProvider()
{
return [[['foo'], ['bar' => 'baz']],
[['foo'], ['bar', 'baz']],
[['foo', 'bar'], ['baz']],
[['foo' => 'bar'], ['baz']]];
return [[['foo'], ['foo', 'bar'], 'Addition'],
[['foo', 'bar'], ['foo'], 'Removal']];
}

public function testHasChanged()
Expand Down

0 comments on commit 0048e4c

Please sign in to comment.