diff --git a/src/Commands/Generator/MakeData.php b/src/Commands/Generator/MakeData.php index 49971e3..3c3fcb1 100644 --- a/src/Commands/Generator/MakeData.php +++ b/src/Commands/Generator/MakeData.php @@ -4,16 +4,21 @@ use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Str; +use Spatie\TypeScriptTransformer\Attributes\Optional as TypeScriptOptional; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use XtendPackages\RESTPresenter\Concerns\WithTypeScriptGenerator; +use XtendPackages\RESTPresenter\Contracts\TypeScriptGeneratorContract; use function Laravel\Prompts\select; #[AsCommand(name: 'rest-presenter:make-data')] -class MakeData extends GeneratorCommand +class MakeData extends GeneratorCommand implements TypeScriptGeneratorContract { + use WithTypeScriptGenerator; + protected $name = 'rest-presenter:make-data'; protected $description = 'Create a new data class'; @@ -84,20 +89,23 @@ protected function buildResourceReplacements(): array protected function transformFieldProperties(array $fields): string { return collect($fields)->map(function (array $fieldProperties, string $field) { - $propertyType = match ($fieldProperties['type']) { + $fieldType = strtolower($fieldProperties['type']); + $propertyType = match ($fieldType) { 'int', 'integer', 'bigint' => 'int', 'tinyint' => 'bool', - 'timestamp', 'datetime' => 'Carbon | Optional | null', + 'timestamp', 'datetime' => 'Carbon', 'json' => 'array', default => 'string', }; $nullable = ! ($fieldProperties['notnull'] === 1); - if ($nullable && $propertyType !== 'Carbon | Optional | null') { + + if ($nullable) { $propertyType = '?' . $propertyType; } + $tsOptional = $nullable ? "#[TypeScriptOptional]\n\t\t" : ''; - return "public {$propertyType} \${$field}"; + return $tsOptional . "public {$propertyType} \${$field}"; })->implode(",\n\t\t"); } diff --git a/src/Commands/Generator/stubs/new/data.php.stub b/src/Commands/Generator/stubs/new/data.php.stub index b5ce4e2..475aab3 100644 --- a/src/Commands/Generator/stubs/new/data.php.stub +++ b/src/Commands/Generator/stubs/new/data.php.stub @@ -4,8 +4,9 @@ namespace {{ namespace }}; use Carbon\Carbon; use Spatie\LaravelData\Data; -use Spatie\LaravelData\Optional; +use Spatie\TypeScriptTransformer\Attributes\Optional as TypeScriptOptional; +/** @typescript */ class {{ class }} extends Data { public function __construct( diff --git a/src/Concerns/WithTypeScriptGenerator.php b/src/Concerns/WithTypeScriptGenerator.php new file mode 100644 index 0000000..3f868c6 --- /dev/null +++ b/src/Concerns/WithTypeScriptGenerator.php @@ -0,0 +1,8 @@ +