Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate typescript definitions #102

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"laravel/pint": "^1.14",
"orchestra/testbench": "^7.0|^8.0|^9.0",
"pestphp/pest": "^1.20|^2.0",
"pestphp/pest-plugin-faker": "^1.0|^2.0"
"pestphp/pest-plugin-faker": "^1.0|^2.0",
"spatie/typescript-transformer": "^2.4"
},
"scripts": {
"lint": "pint",
Expand Down
41 changes: 41 additions & 0 deletions src/Support/TypeScriptCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace WendellAdriel\ValidatedDTO\Support;

use ReflectionClass;
use Spatie\TypeScriptTransformer\Collectors\DefaultCollector;
use Spatie\TypeScriptTransformer\Structures\TransformedType;
use Spatie\TypeScriptTransformer\TypeReflectors\ClassTypeReflector;
use WendellAdriel\ValidatedDTO\ValidatedDTO;

class TypeScriptCollector extends DefaultCollector
{
public function getTransformedType(ReflectionClass $class): ?TransformedType
{
if (! $this->shouldCollect($class)) {
return null;
}

$reflector = ClassTypeReflector::create($class);

// Always use our ValidatedDtoTransformer
$transformer = $this->config->buildTransformer(TypeScriptTransformer::class);

return $transformer->transform(
$reflector->getReflectionClass(),
$reflector->getName()
);
}

protected function shouldCollect(ReflectionClass $class): bool
{
// Only collect classes that extend ValidatedDTO
if (! $class->isSubclassOf(ValidatedDTO::class)) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make this work with any of the DTOs by checking if it's a subclass of the SimpleDTO instead?

return false;
}

return true;
}
}
99 changes: 99 additions & 0 deletions src/Support/TypeScriptTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

namespace WendellAdriel\ValidatedDTO\Support;

use ReflectionClass;
use ReflectionProperty;
use Spatie\TypeScriptTransformer\Structures\MissingSymbolsCollection;
use Spatie\TypeScriptTransformer\Structures\TransformedType;
use Spatie\TypeScriptTransformer\Transformers\Transformer;
use Spatie\TypeScriptTransformer\Transformers\TransformsTypes;
use Spatie\TypeScriptTransformer\TypeProcessors\ReplaceDefaultsTypeProcessor;
use Spatie\TypeScriptTransformer\TypeScriptTransformerConfig;
use WendellAdriel\ValidatedDTO\ValidatedDTO;

class TypeScriptTransformer implements Transformer
{
use TransformsTypes;

protected TypeScriptTransformerConfig $config;

/**
* Properties to exclude from the TypeScript output
*/
protected array $excludedProperties = [
'lazyValidation',
];

public function __construct(TypeScriptTransformerConfig $config)
{
$this->config = $config;
}

public function transform(ReflectionClass $class, string $name): ?TransformedType
{
if (! $this->canTransform($class)) {
return null;
}

$missingSymbols = new MissingSymbolsCollection();
$properties = $this->transformProperties($class, $missingSymbols);

return TransformedType::create(
$class,
$name,
'{' . PHP_EOL . $properties . '}',
$missingSymbols
);
}

protected function canTransform(ReflectionClass $class): bool
{
return $class->isSubclassOf(ValidatedDTO::class);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make this work with any of the DTOs by checking if it's a subclass of the SimpleDTO instead?

}

protected function transformProperties(
ReflectionClass $class,
MissingSymbolsCollection $missingSymbols
): string {
$properties = array_filter(
$class->getProperties(ReflectionProperty::IS_PUBLIC),
function (ReflectionProperty $property) {
// Exclude static properties
if ($property->isStatic()) {
return false;
}

// Exclude specific properties by name
if (in_array($property->getName(), $this->excludedProperties)) {
return false;
}

return true;
}
);

return array_reduce(
$properties,
function (string $carry, ReflectionProperty $property) use ($missingSymbols) {
$transformed = $this->reflectionToTypeScript(
$property,
$missingSymbols,
false,
new ReplaceDefaultsTypeProcessor($this->config->getDefaultTypeReplacements())
);

if ($transformed === null) {
return $carry;
}

$propertyName = $property->getName();

return "{$carry}{$propertyName}: {$transformed};" . PHP_EOL;
},
''
);
}
}
46 changes: 46 additions & 0 deletions tests/Feature/TypeScriptCollectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

use Spatie\TypeScriptTransformer\TypeScriptTransformerConfig;
use WendellAdriel\ValidatedDTO\Support\TypeScriptCollector;

it('returns null when class does not extend ValidatedDTO', function () {
$class = new class() {};

$reflection = new ReflectionClass($class);
$collector = new TypeScriptCollector(TypeScriptTransformerConfig::create());

$type = $collector->getTransformedType($reflection);

expect($type)->toBeNull();
});

it('uses the TypeScriptTransformer for an eligible class', function () {
eval('
namespace App\Data {
use WendellAdriel\ValidatedDTO\ValidatedDTO;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
class TransformerTestDTO extends ValidatedDTO {
use EmptyRules, EmptyCasts, EmptyDefaults;

public string $name;
}
}
');

$reflection = new ReflectionClass(\App\Data\TransformerTestDTO::class);

// Provide a config with no other conflicting transformers
$config = TypeScriptTransformerConfig::create()
->transformers([\WendellAdriel\ValidatedDTO\Support\TypeScriptTransformer::class]);

$collector = new TypeScriptCollector($config);

$type = $collector->getTransformedType($reflection);

expect($type)->not->toBeNull()
->and($type->getTypeScriptName())->toBe('App.Data.TransformerTestDTO');
});
136 changes: 136 additions & 0 deletions tests/Feature/TypeScriptTransformerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

declare(strict_types=1);

use Spatie\TypeScriptTransformer\Structures\TransformedType;
use Spatie\TypeScriptTransformer\TypeScriptTransformerConfig;
use WendellAdriel\ValidatedDTO\Support\TypeScriptTransformer;

it('returns null when class does not extend ValidatedDTO', function () {
$class = new class()
{
public string $name;
};

$reflection = new ReflectionClass($class);

$transformer = new TypeScriptTransformer(TypeScriptTransformerConfig::create());
$type = $transformer->transform($reflection, 'IrrelevantName');

expect($type)->toBeNull();
});

it('transforms a ValidatedDTO with public properties into a TransformedType', function () {
eval('
namespace App\Data {
use WendellAdriel\ValidatedDTO\ValidatedDTO;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
class TestTransformerDTO extends ValidatedDTO {
use EmptyRules, EmptyCasts, EmptyDefaults;

public string $name;
public int $age;
public static string $shouldNotAppear = "excluded";
protected string $invisible = "excluded";
}
}
');

$reflection = new ReflectionClass(\App\Data\TestTransformerDTO::class);

$transformer = new TypeScriptTransformer(TypeScriptTransformerConfig::create());
$type = $transformer->transform($reflection, 'TransformedDTO');

// Should only include public, non-static properties
expect($type)->toBeInstanceOf(TransformedType::class)
->and($type->name)->toBe('TransformedDTO')
->and($type->transformed)->toContain('name: string;')
->and($type->transformed)->toContain('age: number;')
->and($type->transformed)->not->toContain('shouldNotAppear')
->and($type->transformed)->not->toContain('invisible');
});

it('excludes properties listed in excludedProperties', function () {
eval('
namespace App\Data {
use WendellAdriel\ValidatedDTO\ValidatedDTO;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
class ExcludedPropertyDTO extends ValidatedDTO {
use EmptyRules, EmptyCasts, EmptyDefaults;

public bool $lazyValidation = true; // excluded by default
public string $title;
}
}
');

$reflection = new ReflectionClass(\App\Data\ExcludedPropertyDTO::class);

$transformer = new TypeScriptTransformer(TypeScriptTransformerConfig::create());
$type = $transformer->transform($reflection, 'ExcludedProps');

expect($type->transformed)->not->toContain('lazyValidation:')
->and($type->transformed)->toContain('title: string;')
->and($type->getTypeScriptName())->toBe('App.Data.ExcludedProps');
});

it('transforms a ValidatedDTO with nested DTO and enum property', function () {
eval('
namespace App\Enums {
enum FakeStatusEnum: string {
case FIRST = "first";
case SECOND = "second";
}
}
');

eval('
namespace App\Data {
use WendellAdriel\ValidatedDTO\ValidatedDTO;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
class ChildDTO extends ValidatedDTO {
use EmptyRules, EmptyCasts, EmptyDefaults;

public string $childField;
}
}
');

eval('
namespace App\Data {
use WendellAdriel\ValidatedDTO\ValidatedDTO;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
use App\Enums\FakeStatusEnum;

class ParentDTO extends ValidatedDTO {
use EmptyRules, EmptyCasts, EmptyDefaults;

public FakeStatusEnum $status;
public ChildDTO $child;
}
}
');

$reflection = new ReflectionClass(\App\Data\ParentDTO::class);
$transformer = new TypeScriptTransformer(TypeScriptTransformerConfig::create());
$type = $transformer->transform($reflection, 'ComplexDTO');

expect($type)->toBeInstanceOf(TransformedType::class)
->and($type->name)->toBe('ComplexDTO')
->and($type->transformed)->toContain('status: {%App\Enums\FakeStatusEnum%};')
->and($type->transformed)->toContain('child: {%App\Data\ChildDTO%};')
->and($type->missingSymbols->all())
// Missing Symbols contain references to other types. Once all types are
// transformed, the package will replace these references with their
// TypeScript types. When no type is found the type will default to any.
->toContain(\App\Enums\FakeStatusEnum::class)
->and($type->missingSymbols->all())->toContain(\App\Data\ChildDTO::class);
});
Loading