将PHP接口导出到Typescript接口,反之亦然?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了将PHP接口导出到Typescript接口,反之亦然?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_360_4@ 我正在尝试使用TyPEscript,根据我目前的合同,我在 PHP中编写后端代码.

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

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

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

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

解决方法

您可以使用惊人的 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"
}

脚本宝典总结

以上是脚本宝典为你收集整理的将PHP接口导出到Typescript接口,反之亦然?全部内容,希望文章能够帮你解决将PHP接口导出到Typescript接口,反之亦然?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。