Skip to content

Commit

Permalink
Merge 316e736 into 614d408
Browse files Browse the repository at this point in the history
  • Loading branch information
arnedesmedt committed Apr 15, 2020
2 parents 614d408 + 316e736 commit 44c664f
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ImmutableRecord.php
Expand Up @@ -45,5 +45,9 @@ public function with(array $recordData);

public function toArray(): array;

public function toArrayExcept(string ...$excludeKeys): array;

public function toArrayOnly(string ...$includeKeys): array;

public function equals(ImmutableRecord $other): bool;
}
14 changes: 14 additions & 0 deletions src/ImmutableRecordLogic.php
Expand Up @@ -124,6 +124,20 @@ public function toArray(): array
return $nativeData;
}

public function toArrayExcept(string ...$excludeKeys) : array
{
$nativeData = $this->toArray();

return array_diff_key($nativeData, array_flip($excludeKeys));
}

public function toArrayOnly(string ...$includeKeys) : array
{
$nativeData = $this->toArray();

return array_intersect_key($nativeData, array_flip($includeKeys));
}

public function equals(ImmutableRecord $other): bool
{
if (get_class($this) !== get_class($other)) {
Expand Down
46 changes: 46 additions & 0 deletions tests/ImmutableRecordLogicTest.php
Expand Up @@ -152,6 +152,52 @@ public function it_equals_other_record_with_same_values()
$this->assertTrue($valueObjects->equals($other));
}

/**
* @test
*/
public function it_excludes_keys_while_converting_back_to_array()
{
$valueObjects = TypeHintedImmutableRecord::fromArray($this->data);

$this->data['type'] = null;
$this->data['percentage'] = 0.5;

unset($this->data['version'], $this->data['name']);

$dataWithoutKeys = $valueObjects->toArrayExcept('version', 'name');

$this->assertArrayNotHasKey('version', $dataWithoutKeys);
$this->assertArrayNotHasKey('name', $dataWithoutKeys);

$this->assertEquals(
$this->data,
$dataWithoutKeys
);
}

/**
* @test
*/
public function it_includes_keys_while_converting_back_to_array()
{
$valueObjects = TypeHintedImmutableRecord::fromArray($this->data);

$this->data['type'] = null;
$this->data['percentage'] = 0.5;

unset($this->data['version'], $this->data['name'], $this->data['type'], $this->data['percentage']);

$dataWithKeys = $valueObjects->toArrayOnly('access', 'itemList');

$this->assertArrayHasKey('access', $dataWithKeys);
$this->assertArrayHasKey('itemList', $dataWithKeys);

$this->assertEquals(
$this->data,
$dataWithKeys
);
}

/**
* @test
*/
Expand Down

0 comments on commit 44c664f

Please sign in to comment.