From 669940d187ce893b5103da540bcfadad3dd17895 Mon Sep 17 00:00:00 2001 From: Andrey Helldar Date: Fri, 11 Nov 2022 18:59:11 +0300 Subject: [PATCH] Fixed casting: Argument #1 ($value) must be of type X, Y given --- src/DataTransferObject.php | 12 +++++++++++- tests/Fixtures/Cast.php | 3 +++ tests/Unit/CastTest.php | 7 ++++--- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/DataTransferObject.php b/src/DataTransferObject.php index ce7d005..1a0ab99 100644 --- a/src/DataTransferObject.php +++ b/src/DataTransferObject.php @@ -63,7 +63,8 @@ public function set(string $key, $value): DataTransferObject /** * @param array $items * - * @throws ReflectionException + * @throws \ReflectionException + * @return \DragonCode\SimpleDataTransferObject\DataTransferObject */ public function merge(array $items): DataTransferObject { @@ -91,6 +92,10 @@ public function toArray(): array protected function setMap(array $items): void { foreach ($this->map as $from => $to) { + if ($this->sourceKeyDoesntExist($items, $from)) { + continue; + } + $value = $this->getValueByKey($items, $from, $to); $this->setValue($to, $value); @@ -165,4 +170,9 @@ protected function isAllowKey(string $key): bool { return ! in_array(Str::lower($key), $this->disallow, true); } + + protected function sourceKeyDoesntExist(array $items, string $key): bool + { + return Arr::doesntExist($items, $key); + } } diff --git a/tests/Fixtures/Cast.php b/tests/Fixtures/Cast.php index b1245a3..9494537 100644 --- a/tests/Fixtures/Cast.php +++ b/tests/Fixtures/Cast.php @@ -15,9 +15,12 @@ class Cast extends DataTransferObject public $baz; + public $baq; + protected $map = [ 'wa.sd' => 'foo', 'qwe.rty' => 'bar', + 'int' => 'baq', ]; protected function castFoo(string $value) diff --git a/tests/Unit/CastTest.php b/tests/Unit/CastTest.php index 986e3d3..fd59061 100644 --- a/tests/Unit/CastTest.php +++ b/tests/Unit/CastTest.php @@ -6,7 +6,6 @@ use DragonCode\Support\Facades\Helpers\Str; use Tests\Fixtures\Cast; -use Tests\Fixtures\Map; use Tests\TestCase; class CastTest extends TestCase @@ -60,12 +59,13 @@ public function testToArray() 'foo' => Str::upper($this->foo), 'bar' => Str::lower($this->bar), 'baz' => $this->baz, + 'baq' => null, ], $object->toArray()); } public function testSurplusValues() { - $object = new Map([ + $object = new Cast([ 'wa' => [ 'sd' => $this->foo, 'df' => 'some', @@ -75,9 +75,10 @@ public function testSurplusValues() $this->assertIsArray($object->toArray()); $this->assertSame([ - 'foo' => $this->foo, + 'foo' => Str::upper($this->foo), 'bar' => null, 'baz' => null, + 'baq' => null, ], $object->toArray()); } }