Skip to content

Commit

Permalink
feat: Add support for casting SimpleDTO in TinkerCaster (#687)
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia committed Jul 17, 2024
1 parent 048be73 commit 4d4a278
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Command/TinkerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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', []));
Expand Down
21 changes: 21 additions & 0 deletions src/TinkerCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace FriendsOfHyperf\Tinker;

use ReflectionClass;
use ReflectionProperty;
use Stringable;
use Symfony\Component\VarDumper\Caster\Caster;
use Throwable;
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 4d4a278

Please sign in to comment.