Skip to content

Commit

Permalink
exclude keys in toArray function
Browse files Browse the repository at this point in the history
  • Loading branch information
arnedesmedt committed Apr 15, 2020
1 parent 614d408 commit 34d7865
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/ImmutableRecord.php
Expand Up @@ -43,7 +43,7 @@ public static function fromArray(array $nativeData);
*/
public function with(array $recordData);

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

public function equals(ImmutableRecord $other): bool;
}
6 changes: 5 additions & 1 deletion src/ImmutableRecordLogic.php
Expand Up @@ -87,12 +87,16 @@ public function with(array $recordData): self
return $copy;
}

public function toArray(): array
public function toArray(string ...$excludeKeys): array
{
$nativeData = [];
$arrayPropItemTypeMap = self::getArrayPropItemTypeMapFromMethodOrCache();

foreach (self::$__propTypeMap as $key => [$type, $isNative, $isNullable]) {
if (in_array($key, $excludeKeys)) {
continue;
}

switch ($type) {
case ImmutableRecord::PHP_TYPE_STRING:
case ImmutableRecord::PHP_TYPE_INT:
Expand Down
23 changes: 23 additions & 0 deletions tests/ImmutableRecordLogicTest.php
Expand Up @@ -152,6 +152,29 @@ 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->toArray('version', 'name');

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

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

/**
* @test
*/
Expand Down

0 comments on commit 34d7865

Please sign in to comment.