【问题标题】:Export PHP interface to Typescript interface, or vice versa?将 PHP 接口导出到 Typescript 接口,反之亦然?
【发布时间】:2016-01-15 14:02:17
【问题描述】:

我正在试验 Typescript,在我目前的合同中,我使用 PHP 编写后端代码。

在几个项目中,我为我的后端代码提供的那种 AJAX 响应编写了 Typescript 接口,以便前端开发人员(有时也是我,有时是其他人)知道会发生什么并进行类型检查等等.

在编写了一些这样的后端服务之后,似乎响应的接口和相关类也应该存在于 PHP 端。这让我觉得如果我可以只用两种语言中的一种编写它们并运行一些构建时工具(我会在 Typescript 编译器运行之前用 gulp 任务调用它)来导出这些,那就太好了与其他语言的接口。

这样的事情存在吗?可能吗?实用吗?

(我意识到 PHP 不是强类型的,但是如果接口是用 PHP 编写的,那么那里可能会有一些类型提示,例如导出器识别并传递给 Typescript 的文档字符串。)

【问题讨论】:

  • 从 php7 开始(在 hack 中),您可以使用所有基本和复杂类型(对象、数组和可调用对象在 php 5.x+ 中可类型提示)作为类型提示供您使用(它们是如何由运行时强制执行的与出口无关)。所以你可以避免解析文档块。无论哪种方式,您都可以使用php-parser 生成 AST 并基于它生成一个打字稿文件。不应该太复杂。 (我对 typescript 没有更深入的了解,所以我不知道类型系统的匹配程度如何,但由于它似乎受到 c# 的启发,它们应该在某种程度上兼容)
  • 很高兴知道。所以剩下的就是这样的东西是否已经存在了。

标签: php interface typescript


【解决方案1】:

您可以使用惊人的nikic/PHP-Parser 创建一个工具,将选定的 PHP 类(那些在 phpDoc 中带有 @TypeScriptMe 字符串的类)轻松转换为 TypeScript 接口。以下脚本非常简单,但我认为您可以扩展它,您可以自动生成 TypeScript 接口,并可能通过 git 跟踪更改。

示例

对于这个输入:

<?php
/**
 * @TypeScriptMe
 */
class Person
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var int
     */
    public $age;

    /**
     * @var \stdClass
     */
    public $mixed;

    /**
     * @var string
     */
    private $propertyIsPrivateItWontShow;
}

class IgnoreMe {

    public function test() {

    }
}

你会得到:

interface Person {
  name: string,
  age: number,
  mixed: any
}

源代码

index.php:

<?php

namespace TypeScript {

    class Property_
    {
        /** @var string */
        public $name;
        /** @var string */
        public $type;

        public function __construct($name, $type = "any")
        {
            $this->name = $name;
            $this->type = $type;
        }

        public function __toString()
        {
            return "{$this->name}: {$this->type}";
        }
    }

    class Interface_
    {
        /** @var string */
        public $name;
        /** @var Property_[] */
        public $properties = [];

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

        public function __toString()
        {
            $result = "interface {$this->name} {\n";
            $result .= implode(",\n", array_map(function ($p) { return "  " . (string)$p;}, $this->properties));
            $result .= "\n}";
            return $result;
        }
    }
}

namespace MyParser {

    ini_set('display_errors', 1);
    require __DIR__ . "/vendor/autoload.php";

    use PhpParser;
    use PhpParser\Node;
    use TypeScript;

    class Visitor extends PhpParser\NodeVisitorAbstract
    {
        private $isActive = false;

        /** @var TypeScript/Interface_[] */
        private $output = [];

        /** @var TypeScript\Interface_ */
        private $currentInterface;

        public function enterNode(Node $node)
        {
            if ($node instanceof PhpParser\Node\Stmt\Class_) {

                /** @var PhpParser\Node\Stmt\Class_ $class */
                $class = $node;
                // If there is "@TypeScriptMe" in the class phpDoc, then ...
                if ($class->getDocComment() && strpos($class->getDocComment()->getText(), "@TypeScriptMe") !== false) {
                    $this->isActive = true;
                    $this->output[] = $this->currentInterface = new TypeScript\Interface_($class->name);
                }
            }

            if ($this->isActive) {
                if ($node instanceof PhpParser\Node\Stmt\Property) {
                    /** @var PhpParser\Node\Stmt\Property $property */
                    $property = $node;

                    if ($property->isPublic()) {
                        $type = $this->parsePhpDocForProperty($property->getDocComment());
                        $this->currentInterface->properties[] = new TypeScript\Property_($property->props[0]->name, $type);
                    }
                }
            }
        }

        public function leaveNode(Node $node)
        {
            if ($node instanceof PhpParser\Node\Stmt\Class_) {
                $this->isActive = false;
            }
        }

        /**
         * @param \PhpParser\Comment|null $phpDoc
         */
        private function parsePhpDocForProperty($phpDoc)
        {
            $result = "any";

            if ($phpDoc !== null) {
                if (preg_match('/@var[ \t]+([a-z0-9]+)/i', $phpDoc->getText(), $matches)) {
                    $t = trim(strtolower($matches[1]));

                    if ($t === "int") {
                        $result = "number";
                    }
                    elseif ($t === "string") {
                        $result = "string";
                    }
                }
            }

            return $result;
        }

        public function getOutput()
        {
            return implode("\n\n", array_map(function ($i) { return (string)$i;}, $this->output));
        }
    }

    ### Start of the main part


    $parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative);
    $traverser = new PhpParser\NodeTraverser;
    $visitor = new Visitor;
    $traverser->addVisitor($visitor);

    try {
        // @todo Get files from a folder recursively
        //$code = file_get_contents($fileName);

        $code = <<<'EOD'
<?php
/**
 * @TypeScriptMe
 */
class Person
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var int
     */
    public $age;

    /**
     * @var \stdClass
     */
    public $mixed;

    /**
     * @var string
     */
    private $propertyIsPrivateItWontShow;
}

class IgnoreMe {

    public function test() {

    }
}

EOD;

        // parse
        $stmts = $parser->parse($code);

        // traverse
        $stmts = $traverser->traverse($stmts);

        echo "<pre><code>" . $visitor->getOutput() . "</code></pre>";

    } catch (PhpParser\Error $e) {
        echo 'Parse Error: ', $e->getMessage();
    }
}

composer.json

{
    "name": "experiment/experiment",
    "description": "...",
    "homepage": "http://example.com",
    "type": "project",
    "license": ["Unlicense"],
    "authors": [
        {
            "name": "MrX",
            "homepage": "http://example.com"
        }
    ],
    "require": {
        "php": ">= 5.4.0",
        "nikic/php-parser": "^1.4"
    },
    "minimum-stability": "stable"
}

【讨论】:

    【解决方案2】:

    有点晚了,但如果你使用 Symfony 作为项目的框架,你可以使用https://github.com/snakedove/php-to-typescript-converter。它添加了一个命令,例如“ts-create-all”到您的控制台,并让您转换所有 POPO,例如一个文件夹的 DTO 到 TypeScript 接口。只能单向工作。它有一个特殊的选项可以将迭代转换为给定类型的数组,这在某些情况下可能很有用。

    【讨论】:

      【解决方案3】:

      您可以查看TypeSchema,您可以在其中根据您的 PHP 模型生成 JSON 格式,并将这些 JSON 格式转换回不同的语言,即 TypeScript、Java 等,这可以解决您描述的问题。

      【讨论】:

        猜你喜欢
        • 2015-08-23
        • 2013-08-16
        • 2012-06-27
        • 2021-05-12
        • 2019-02-27
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        相关资源
        最近更新 更多