From 34d7865a4907b22d77fde13d484ee6fa31db3dfd Mon Sep 17 00:00:00 2001 From: Arne De Smedt Date: Wed, 15 Apr 2020 08:49:02 +0200 Subject: [PATCH] exclude keys in toArray function --- src/ImmutableRecord.php | 2 +- src/ImmutableRecordLogic.php | 6 +++++- tests/ImmutableRecordLogicTest.php | 23 +++++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/ImmutableRecord.php b/src/ImmutableRecord.php index 0abe53e..f2eff4f 100644 --- a/src/ImmutableRecord.php +++ b/src/ImmutableRecord.php @@ -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; } diff --git a/src/ImmutableRecordLogic.php b/src/ImmutableRecordLogic.php index 717647b..89f2f37 100644 --- a/src/ImmutableRecordLogic.php +++ b/src/ImmutableRecordLogic.php @@ -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: diff --git a/tests/ImmutableRecordLogicTest.php b/tests/ImmutableRecordLogicTest.php index aa62013..21e50ae 100644 --- a/tests/ImmutableRecordLogicTest.php +++ b/tests/ImmutableRecordLogicTest.php @@ -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 */