From 4d4a278b17cb45da83de1bffd37c124c29f4a0df Mon Sep 17 00:00:00 2001 From: Deeka Wong Date: Wed, 17 Jul 2024 23:38:57 +0800 Subject: [PATCH] feat: Add support for casting SimpleDTO in TinkerCaster (#687) --- src/Command/TinkerCommand.php | 1 + src/TinkerCaster.php | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/Command/TinkerCommand.php b/src/Command/TinkerCommand.php index f86824b..75a0755 100644 --- a/src/Command/TinkerCommand.php +++ b/src/Command/TinkerCommand.php @@ -139,6 +139,7 @@ protected function getCasters(): array 'Hyperf\ViewEngine\HtmlString' => 'FriendsOfHyperf\Tinker\TinkerCaster::castHtmlString', 'Stringable' => 'FriendsOfHyperf\Tinker\TinkerCaster::castStringable', 'Symfony\Component\Console\Application' => 'FriendsOfHyperf\Tinker\TinkerCaster::castApplication', + 'FriendsOfHyperf\ValidatedDTO\SimpleDTO' => 'FriendsOfHyperf\Tinker\TinkerCaster::castSimpleDTO', ]; return array_merge($casters, (array) $this->config->get('tinker.casters', [])); diff --git a/src/TinkerCaster.php b/src/TinkerCaster.php index b4f63bd..13ae69b 100644 --- a/src/TinkerCaster.php +++ b/src/TinkerCaster.php @@ -11,6 +11,8 @@ namespace FriendsOfHyperf\Tinker; +use ReflectionClass; +use ReflectionProperty; use Stringable; use Symfony\Component\VarDumper\Caster\Caster; use Throwable; @@ -185,4 +187,23 @@ public static function castMessageBag($messageBag): array Caster::PREFIX_PROTECTED . 'format' => $messageBag->getFormat(), ]; } + + /** + * @param \FriendsOfHyperf\ValidatedDTO\SimpleDTO $dto + */ + public static function castSimpleDTO($dto): array + { + $reflectionClass = new ReflectionClass($dto); + $results = []; + + foreach ($reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + $property->setAccessible(true); + $results[Caster::PREFIX_VIRTUAL . $property->getName()] = $property->getValue($dto); + } + + $results[Caster::PREFIX_PROTECTED . 'validatedData'] = (fn () => $this->validatedData ?? [])->call($dto); + $results[Caster::PREFIX_VIRTUAL . $dto::class . '::toArray()'] = $dto->toArray(); + + return $results; + } }