我正在试验 Typescript,在我目前的契约(Contract)中,我用 PHP 编写后端代码。
在几个项目中,我为后端代码提供的 AJAX 响应编写了 Typescript 接口(interface),以便前端开发人员(有时也是我,有时是其他人)知道期望什么并进行类型检查等.
在编写了一些这样的后端服务之后,似乎响应的接口(interface)和相关类也应该存在于 PHP 端。这让我觉得,如果我可以只用两种语言中的一种编写它们并运行一些构建时工具(我会在 Typescript 编译器运行之前用 gulp 任务调用它)来导出这些,那就太好了与其他语言的接口(interface)。
有这样的东西吗?可能吗?实用吗?
(我意识到 PHP 不是强类型的,但是如果接口(interface)是用 PHP 编写的,那么那里可能会有一些类型提示,例如导出器识别并转移到 Typescript 的文档字符串。)
最佳答案
你可以使用 amazing nikic/PHP-Parser创建一个工具,用于将选定的 PHP 类(那些在 phpDoc 中带有 @TypeScriptMe
字符串的类)很容易地转换为 TypeScript 接口(interface)。下面的脚本非常简单,但我认为你可以扩展它,你可以自动生成 TypeScript 接口(interface),并可能通过 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 - 将 PHP 接口(interface)导出到 Typescript 接口(interface),反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176888/