crodas/notoj

注释解析器。使用反射并提供开箱即用的缓存。

v1.7.0 2019-12-15 05:55 UTC

README

另一个注释解析器(DocBlocks)。它旨在简单直观。它扩展了Notoj命名空间内的反射方法(ReflectionClass、RefletionProperties、ReflectionMethod等),并添加了getAnnotations()方法。

<?php
use Notoj\ReflectionClass;
  
/** @foo @bar */
class Foo {
}
  
$reflection = new ReflectionClass('Foo');
var_dump($reflection->getAnnotations());

getAnnotations() 返回一个数组,具有非常简单的数组结构(array("method" => "Foo", "args" => NULL)

如何使用

Notoj支持两种场景的工作,离线在线解析。

在线

在线解析意味着您想要从运行时存在的对象、类或函数中检索注释。要使用它,您需要使用Notoj命名空间中的反射类。

离线

离线解析意味着您想要从文件或目录中获取注释,并且您不想使用在线 API来包含它们。Notoj提供了Notoj\File\Notoj\Dir类来完成此操作。它们都返回Annotations对象,该对象的行为类似于Annotation数组(在线 API的输出),同时还提供了一些额外的东西,例如fileline

文件

<?php
$parser = new \Notoj\File("/foo.php");
$parser->getAnnotations();

目录

<?php
$parser = new \Notoj\Dir("/foo"); // The parser is recursive
$parser->setFilter(function($file) {
 return true;
});
$annotations = $parser->getAnnotations();
foreach ($annotations->get('Foo\Bar') as $annotations) {
   foreach ($annotations as $annotation) {
      var_dump(
          "found @Foo\Bar at " . $annotation['file'] 
          . ($annotation->isClass() ? ' on a class ' : ' on something else other than a class')
      );
   }
}

注释对象

它是表示注释的输出对象。请注意,它代表的是对象、类或函数中的注释,而不仅仅是单个注释。

它提供了->get($tag)->has($tag)过滤器,有助于处理对象。

<?php
// check if there is a @Foo
if (!$annotation->has('Foo')) {
  throw new \RuntimeException("We were expecting a Foo annotation tag");
}

// ensure that *every* @Foo has at least some argument
foreach ($annotation->get('Foo') as $ann) {
   if (empty($ann['args'])) {
      throw new \RuntimeException("we were expecting arguments");
   }
}

foreach ($annotation as $ann) {
    // get *All* iterations
}

注释对象

它是一个类似于Annotation对象数组的对象。提供了非常简单的过滤器->get($name)->has($name)

格式

<?php
/** @Foo */
/** @Foo("some") */
/** @Foo some other strings */
/** @Foo(some_label="something here") */
/** @Foo({some: "array here", arr:[1,2,3]}) */
/** @Foo(some_label={some: "array here", arr:[1,2,3]}) */

警告:Notoj会尽力解析损坏的注释,但如果出现错误,它将静默失败。此外,在@foo bar foobar格式中,空白将被忽略。

缓存支持

Notoj支持缓存,这有助于Notoj引擎避免重复解析相同的字符串。缓存将自动失效。

要启用此功能,您需要指定用于保存缓存的文件,Notoj将完成其余操作:-)。

Notoj::enableCache("/tmp/annotations.php");

待办事项

  • 离线解析的缓存

请随时通过电子邮件发送分支和提交pull请求,或给我crodas@php.net写信。