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

Basic generator #1

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
composer.lock
vendor
10 changes: 10 additions & 0 deletions A5sysTypeScriptGeneratorBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace A5sys\TypeScriptGeneratorBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class A5sysTypeScriptGeneratorBundle extends Bundle
{

}
54 changes: 54 additions & 0 deletions Command/GenerateTypeScriptCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace A5sys\TypeScriptGeneratorBundle\Command;

use A5sys\TypeScriptGeneratorBundle\Generator\TypeScriptGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
* Class GenerateTypeScriptCommand
*/
class GenerateTypeScriptCommand extends Command
{
private $generator;
private $commandName;

/**
* GenerateTypeScriptCommand constructor.
* @param \A5sys\TypeScriptGeneratorBundle\Generator\TypeScriptGenerator $generator
* @param string $commandName
* @param null $name
*/
public function __construct(TypeScriptGenerator $generator, string $commandName, $name = null)
{
$this->generator = $generator;
$this->commandName = $commandName;
parent::__construct($name);
}

/**
* @{@inheritdoc}
*/
protected function configure()
{
$this
->setName('a5sys:ts-generator:'.$this->commandName)
->addArgument('input', InputArgument::REQUIRED, 'Input path')
->addArgument('output', InputArgument::REQUIRED, 'Output path')
->setDescription(sprintf('Generate TypeScript %s from PHP classes', $this->commandName))
;
}

/**
* @{@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$inputPath = $input->getArgument('input');
$outputPath = $input->getArgument('output');
$this->generator->generate($inputPath, $outputPath);
}
}
23 changes: 23 additions & 0 deletions DependencyInjection/A5sysTypeScriptGeneratorExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace A5sys\TypeScriptGeneratorBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

/**
* Class A5sysTypeScriptGeneratorExtension
*/
class A5sysTypeScriptGeneratorExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
196 changes: 196 additions & 0 deletions Generator/TypeScriptGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
<?php

namespace A5sys\TypeScriptGeneratorBundle\Generator;

use A5sys\TypeScriptGeneratorBundle\Util\ClassExtractor;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\PropertyInfo\Type;

/**
* Class TypeScriptGenerator
*/
class TypeScriptGenerator
{
private const TYPE_TRANSLATION = [
'DateTime' => 'Date',
'int' => 'number',
'float' => 'number',
'bool' => 'boolean',
];

private $twig;
private $templateName;
private $propertyInfo;

/**
* TypeScriptInterfaceGenerator constructor.
* @param \Twig_Environment $twig
* @param string $templateName
*/
public function __construct(\Twig_Environment $twig, string $templateName)
{
$this->twig = $twig;
$this->templateName = $templateName;

$phpDocExtractor = new PhpDocExtractor();
$reflectionExtractor = new ReflectionExtractor();
$doctrineExtractor = new DoctrineExtractor(new DisconnectedClassMetadataFactory());

$this->propertyInfo = new PropertyInfoExtractor(
[$reflectionExtractor, $doctrineExtractor],
[$phpDocExtractor, $reflectionExtractor, $doctrineExtractor],
[$phpDocExtractor],
[$reflectionExtractor]
);
}

/**
* @param string $inputPath
* @param string $outputPath
*/
public function generate(string $inputPath, string $outputPath): void
{
$this->checkPath($inputPath);
$this->checkPath($outputPath);

$template = $this->twig->load($this->templateName);
$fs = new Filesystem();

$classes = ClassExtractor::createMap($inputPath);
foreach ($classes as $class) {
$fs->dumpFile($outputPath.'/'.$class['className'].'.ts', $template->render($this->getClassDefinition($class)));
}
}

/**
* @param string $path
* @throws \RuntimeException
*/
private function checkPath(string $path): void
{
if (!is_dir($path)) {
throw new \InvalidArgumentException(sprintf('The provided path %s is not a directory', $path));
}
}

/**
* @param array $class
* @return array
*/
private function getClassDefinition(array $class): array
{
$classDefinition = [
'name' => $class['className'],
'properties' => [],
'classesToImport' => [],
];
foreach ($this->propertyInfo->getProperties($class['fqcn']) as $propertyName) {
$types = $this->propertyInfo->getTypes($class['fqcn'], $propertyName);

[$type, $classToImport] = $this->getType($types ?? []);
if ($classToImport) {
$classDefinition['classesToImport'][] = $classToImport;
}
$classDefinition['properties'][] = [
'name' => $propertyName,
'type' => $type,
];
}

return $classDefinition;
}

/**
* @param \Symfony\Component\PropertyInfo\Type[] $types
* @return array
*/
private function getType(array $types): array
{
foreach ($types as $type) {
switch ($type->getBuiltinType()) {
case Type::BUILTIN_TYPE_BOOL:
case Type::BUILTIN_TYPE_FLOAT:
case Type::BUILTIN_TYPE_INT:
case Type::BUILTIN_TYPE_NULL:
case Type::BUILTIN_TYPE_STRING:
return $this->computePritimiveType($type);

case Type::BUILTIN_TYPE_ARRAY:
return $this->computeArrayType($type);

case Type::BUILTIN_TYPE_OBJECT && ($type->getClassName() !== ArrayCollection::class):
return $this->computeObjectType($type);
}
}

return ['any', null];
}

/**
* @param \Symfony\Component\PropertyInfo\Type $type
* @return array
*/
private function computePritimiveType(Type $type): array
{
$returnType = $this->translateTypeName($type->getBuiltinType());
if ($type->isNullable()) {
$returnType .= ' | null';
}

return [$returnType, null];
}

/**
* @param \Symfony\Component\PropertyInfo\Type $type
* @return array
*/
private function computeArrayType(Type $type): array
{
if ($type->getCollectionValueType() !== null) {
[$inferredType, $typeToImport] = $this->getType([$type->getCollectionValueType()]);

return [$inferredType.'[]', $typeToImport];
}

return ['[]', null];
}

/**
* @param \Symfony\Component\PropertyInfo\Type $type
* @return array
*/
private function computeObjectType(Type $type): array
{
$className = (new \ReflectionClass($type->getClassName()))->getShortName();
$returnType = $this->translateTypeName($className);
if ($type->isNullable()) {
$returnType .= ' | null';
}

$typeToImport = null;
if ($type->getClassName() !== \DateTime::class) {
$typeToImport = $className;
}

return [$returnType, $typeToImport];
}

/**
* @param string $typeName
* @return string
*/
private function translateTypeName(string $typeName): string
{
if (isset(static::TYPE_TRANSLATION[$typeName])) {
return static::TYPE_TRANSLATION[$typeName];
}

return $typeName;
}
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 A5sys

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
35 changes: 34 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,35 @@
# TypeScriptGeneratorBundle
Generate TypeScript Classes or Interfaces from PHP classes (phpdoc, doctrine, php types)
This bundle adds two Symfony command to generate TypeScript classesor interfaces from PHP classes.

The fields and their types are extracted from the phpdoc, Doctrine's metadata and PHP's types using [Symfony's Property Info Component](https://symfony.com/doc/current/components/property_info.html) .

## Installation
Require the bundle in Composer:
```
composer require --dev a5sys/typescript-generator-bundle
```
Register the bundle in your AppKernel:
```php
public function registerBundles()
{
// ...
if ('dev' === $this->getEnvironment()) {
// ...
$bundles[] = new A5sys\TypeScriptGeneratorBundle\A5sysTypeScriptGeneratorBundle();
}
}
```
## Usage
To generate classes:
```
mkdir generated-classes
php bin/console a5sys:ts-generator:class src/AppBundle/Entity generated-classes
```
This command will scan all classes in the directory `src/AppBundle/Entity` and generate their typescript's equivalence in the directory `generated-classes`.

To generate interfaces:
```
mkdir generated-interfaces
php bin/console a5sys:ts-generator:interface src/AppBundle/Entity generated-interfaces
```
This command will scan all classes in the directory `src/AppBundle/Entity` and generate their typescript's equivalence in the directory `generated-interface`.
28 changes: 28 additions & 0 deletions Resources/config/services.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
<service id="a5sys_typescript_generator.generate_interface_command" class="A5sys\TypeScriptGeneratorBundle\Command\GenerateTypeScriptCommand">
<argument type="service" id="a5sys_typescript_generator.interface_generator"/>
<argument type="string">interface</argument>
<tag name="console.command" />
</service>
<service id="a5sys_typescript_generator.generate_class_command" class="A5sys\TypeScriptGeneratorBundle\Command\GenerateTypeScriptCommand">
<argument type="service" id="a5sys_typescript_generator.class_generator"/>
<argument type="string">class</argument>
<tag name="console.command" />
</service>
<service id="a5sys_typescript_generator.generator" class="A5sys\TypeScriptGeneratorBundle\Generator\TypeScriptGenerator" abstract="true" lazy="true">
<argument type="service" id="twig" />
</service>
<service id="a5sys_typescript_generator.interface_generator" class="A5sys\TypeScriptGeneratorBundle\Generator\TypeScriptGenerator" parent="a5sys_typescript_generator.generator">
<argument type="string">@A5sysTypeScriptGenerator/interface.ts.twig</argument>
</service>
<service id="a5sys_typescript_generator.class_generator" class="A5sys\TypeScriptGeneratorBundle\Generator\TypeScriptGenerator" parent="a5sys_typescript_generator.generator">
<argument type="string">@A5sysTypeScriptGenerator/class.ts.twig</argument>
</service>
</services>
</container>
11 changes: 11 additions & 0 deletions Resources/views/class.ts.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% for classToImport in classesToImport %}
import { {{ classToImport }} } from './{{ classToImport }}';
{% endfor %}

export class {{ name }} {
constructor(
{% for property in properties %}
{{ property.name }}: {{ property.type }},
{% endfor -%}
) {}
}
9 changes: 9 additions & 0 deletions Resources/views/interface.ts.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% for classToImport in classesToImport %}
import { {{ classToImport }} } from './{{ classToImport }}';
{% endfor %}

export interface {{ name }} {
{% for property in properties %}
{{ property.name }}: {{ property.type }};
{% endfor %}
}
Loading