You might want to apply some transformations to the resultant file containing types. For example, you may wish to format it with a tool of your choice or prepend the code with a warning such as "// This file was autogenerated. Do not edit it manually". To add such a warning, you can use the built-in extension:
return static function (PhpConverterConfig $config) {
$config->addVisitor(new DtoVisitor(new PhpAttributeFilter(Dto::class)));
$config->setOutputGenerator(new TypeScriptGenerator(
new SingleFileOutputWriter('generated.ts'),
[
new DateTimeTypeResolver(),
new ClassNameTypeResolver(),
],
new OutputFilesProcessor([
new PrependAutogeneratedNoticeFileProcessor(),
]),
));
};
Feel free to create your own processor based on PrependAutogeneratedNoticeFileProcessor source.
Here's an example of what a Prettier formatter could look like:
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class PrettierFormatProcessor implements SingleOutputFileProcessorInterface
{
public function process(OutputFile $outputFile): OutputFile
{
$fs = new Filesystem();
$temporaryGeneratedFile = $fs->tempnam(sys_get_temp_dir(), "dto", '.ts');
$fs->appendToFile($temporaryGeneratedFile, $outputFile->getContent());
$process = new Process(["./node_modules/.bin/prettier", $temporaryGeneratedFile, '--write', '--config', '.prettierrc.js']);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return new OutputFile(
$outputFile->getRelativeName(),
file_get_contents($temporaryGeneratedFile)
);
}
}
Then add it to the list:
return static function (PhpConverterConfig $config) {
$config->addVisitor(new DtoVisitor(new PhpAttributeFilter(Dto::class)));
$config->setOutputGenerator(new TypeScriptGenerator(
new SingleFileOutputWriter('generated.ts'),
[
new DateTimeTypeResolver(),
new ClassNameTypeResolver(),
],
new OutputFilesProcessor([
new PrependAutogeneratedNoticeFileProcessor(),
new PrettierFormatProcessor(),
]),
));
};
By default, php-converter
writes all the types into one file. You can configure it to put each type or class into a separate file, complete with all the required imports. Here is an example of how to achieve it:
return static function (PhpConverterConfig $config) {
$config->addVisitor(new DtoVisitor(new PhpAttributeFilter(Dto::class)));
+ $fileNameGenerator = new KebabCaseFileNameGenerator('.ts');
$config->setOutputGenerator(new TypeScriptGenerator(
new SingleFileOutputWriter('generated.ts'),
- new SingleFileOutputWriter('generated.ts'),
+ new EntityPerClassOutputWriter(
+ $fileNameGenerator,
+ new TypeScriptImportGenerator(
+ $fileNameGenerator,
+ new DtoTypeDependencyCalculator()
+ )
+ ),
[
new DateTimeTypeResolver(),
new ClassNameTypeResolver(),
],
));
};
Feel free to create your own OutputWriter.