Skip to content

Commit

Permalink
Fixed casting: Argument #1 ($value) must be of type X, Y given
Browse files Browse the repository at this point in the history
  • Loading branch information
andrey-helldar committed Nov 11, 2022
1 parent 38c33c4 commit 669940d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
12 changes: 11 additions & 1 deletion src/DataTransferObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
}
}
3 changes: 3 additions & 0 deletions tests/Fixtures/Cast.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 4 additions & 3 deletions tests/Unit/CastTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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',
Expand All @@ -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());
}
}

0 comments on commit 669940d

Please sign in to comment.