Skip to content
This repository was archived by the owner on Apr 7, 2025. It is now read-only.

Commit c773735

Browse files
author
Andrey Helldar
authored
Merge pull request #36 from TheDragonCode/2.x
Fixed casting: Argument #1 ($value) must be of type X, Y given
2 parents 4daa6ad + 72fca12 commit c773735

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

src/DataTransferObject.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ public function set(string $key, $value): DataTransferObject
6363
/**
6464
* @param array $items
6565
*
66-
* @throws ReflectionException
66+
* @throws \ReflectionException
67+
* @return \DragonCode\SimpleDataTransferObject\DataTransferObject
6768
*/
6869
public function merge(array $items): DataTransferObject
6970
{
@@ -91,6 +92,10 @@ public function toArray(): array
9192
protected function setMap(array $items): void
9293
{
9394
foreach ($this->map as $from => $to) {
95+
if ($this->sourceKeyDoesntExist($items, $from)) {
96+
continue;
97+
}
98+
9499
$value = $this->getValueByKey($items, $from, $to);
95100

96101
$this->setValue($to, $value);
@@ -165,4 +170,9 @@ protected function isAllowKey(string $key): bool
165170
{
166171
return ! in_array(Str::lower($key), $this->disallow, true);
167172
}
173+
174+
protected function sourceKeyDoesntExist(array $items, string $key): bool
175+
{
176+
return ! Arr::exists($items, $key);
177+
}
168178
}

tests/Fixtures/Cast.php

+3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ class Cast extends DataTransferObject
1515

1616
public $baz;
1717

18+
public $baq;
19+
1820
protected $map = [
1921
'wa.sd' => 'foo',
2022
'qwe.rty' => 'bar',
23+
'int' => 'baq',
2124
];
2225

2326
protected function castFoo(string $value)

tests/Unit/CastTest.php

+4-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
use DragonCode\Support\Facades\Helpers\Str;
88
use Tests\Fixtures\Cast;
9-
use Tests\Fixtures\Map;
109
use Tests\TestCase;
1110

1211
class CastTest extends TestCase
@@ -60,12 +59,13 @@ public function testToArray()
6059
'foo' => Str::upper($this->foo),
6160
'bar' => Str::lower($this->bar),
6261
'baz' => $this->baz,
62+
'baq' => null,
6363
], $object->toArray());
6464
}
6565

6666
public function testSurplusValues()
6767
{
68-
$object = new Map([
68+
$object = new Cast([
6969
'wa' => [
7070
'sd' => $this->foo,
7171
'df' => 'some',
@@ -75,9 +75,10 @@ public function testSurplusValues()
7575
$this->assertIsArray($object->toArray());
7676

7777
$this->assertSame([
78-
'foo' => $this->foo,
78+
'foo' => Str::upper($this->foo),
7979
'bar' => null,
8080
'baz' => null,
81+
'baq' => null,
8182
], $object->toArray());
8283
}
8384
}

0 commit comments

Comments
 (0)