Skip to content

Commit 4d4a278

Browse files
authored
feat: Add support for casting SimpleDTO in TinkerCaster (#687)
1 parent 048be73 commit 4d4a278

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

src/Command/TinkerCommand.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ protected function getCasters(): array
139139
'Hyperf\ViewEngine\HtmlString' => 'FriendsOfHyperf\Tinker\TinkerCaster::castHtmlString',
140140
'Stringable' => 'FriendsOfHyperf\Tinker\TinkerCaster::castStringable',
141141
'Symfony\Component\Console\Application' => 'FriendsOfHyperf\Tinker\TinkerCaster::castApplication',
142+
'FriendsOfHyperf\ValidatedDTO\SimpleDTO' => 'FriendsOfHyperf\Tinker\TinkerCaster::castSimpleDTO',
142143
];
143144

144145
return array_merge($casters, (array) $this->config->get('tinker.casters', []));

src/TinkerCaster.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace FriendsOfHyperf\Tinker;
1313

14+
use ReflectionClass;
15+
use ReflectionProperty;
1416
use Stringable;
1517
use Symfony\Component\VarDumper\Caster\Caster;
1618
use Throwable;
@@ -185,4 +187,23 @@ public static function castMessageBag($messageBag): array
185187
Caster::PREFIX_PROTECTED . 'format' => $messageBag->getFormat(),
186188
];
187189
}
190+
191+
/**
192+
* @param \FriendsOfHyperf\ValidatedDTO\SimpleDTO $dto
193+
*/
194+
public static function castSimpleDTO($dto): array
195+
{
196+
$reflectionClass = new ReflectionClass($dto);
197+
$results = [];
198+
199+
foreach ($reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
200+
$property->setAccessible(true);
201+
$results[Caster::PREFIX_VIRTUAL . $property->getName()] = $property->getValue($dto);
202+
}
203+
204+
$results[Caster::PREFIX_PROTECTED . 'validatedData'] = (fn () => $this->validatedData ?? [])->call($dto);
205+
$results[Caster::PREFIX_VIRTUAL . $dto::class . '::toArray()'] = $dto->toArray();
206+
207+
return $results;
208+
}
188209
}

0 commit comments

Comments
 (0)