gpt4 book ai didi

php 注释、命名空间和 use 关键字

转载 作者:行者123 更新时间:2023-12-04 16:59:21 26 4
gpt4 key购买 nike

我正在为 php 编写一个注释解析器(由于特定需要,我不能使用任何 3rd 方的)并且我以 sympfony2 代码为灵感

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="product")
*/
class Product
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

正如我在这里看到的,我们在 use 语句中定义了 ORM,然后注释解析器知道 ORM 是 Doctrine\ORM\Mapping 的别名。

我的最终目标是能够将类名作为别名传递到我的注释中
use some/namespace/Enum;
use another/ns/PropEnum;

class Abc
{
/**
* @Enum(PropEnum)
**/
protected $prop;
}

您能否指出我正确的方向,因为我什至不知道从哪里开始?

谢谢

最佳答案

让我们看看如何doctrine/annotations (Symfony 使用的包)解决了这个问题。

PhpParser 解析类的 PHP 文件(您可以通过 ReflectionClass#getFilename() 获得)。让我们看看 parseClass() 逐行方法:

if (method_exists($class, 'getUseStatements')) {
return $class->getUseStatements();
}

教义有自定义 StaticReflectionClass 已经有 getUseStatements() 的类方法来获取类文件中的 use 语句。我假设你不使用那个类,所以让我们继续!
if (false === $filename = $class->getFilename()) {
return array();
}

$content = $this->getFileContent($filename, $class->getStartLine());

if (null === $content) {
return array();
}

这些语句检索类的文件内容。如果没有内容或没有文件,也没有 use 语句。
$namespace = preg_quote($class->getNamespaceName());
$content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);

在这里,他们正在寻找为文件中的类定义命名空间的行。它后面是 use 语句,所以正则表达式只提取命名空间和它后面的所有内容。
$tokenizer = new TokenParser('<?php ' . $content);

$statements = $tokenizer->parseUseStatements($class->getNamespaceName());

return $statements;

然后它创建一个 TokenParser类中只包含该内容,并让它在其中找到 use 语句。

如果你看 TokenParser ,你会发现它使用 token_get_all() 将文件转换为 PHP 引擎使用的 PHP token ,然后在该 token 树中移动查找 T_USE语句,它提取并保存。

关于php 注释、命名空间和 use 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24550441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com