cspray/annotated-target

一个用于使用 PHP-Parser 静态解析属性的 PHP 8 库。

v2.0.0.alpha.1 2024-06-17 12:51 UTC

README

PHP 8 的静态分析工具,用于收集给定代码库中所有使用属性的地点。简而言之,给这个工具一组目录,我们将提供一个生成器,它会在找到属性的地方提供信息。您可以按属性类型筛选以获取所需信息的特定内容。有关更多信息,请查看下面的快速入门。

安装

使用 Composer 安装此包。

composer require cspray/annotated-target

快速入门

在 Annotated Target 中,核心概念是一个名为 AnnotatedTarget 的接口,它跟踪您代码库中每个属性使用的位置信息。它提供以下三份数据

  1. 属性所针对的 Reflector。例如,如果属性被发现在针对一个类,则将有一个 ReflectionClass
  2. 属性的 ReflectionAttribute
  3. 给定属性的实例。

让我们看看一些带注释的代码以及如何访问解析后的属性。我们假设此代码存在于 __DIR__ . 'src/Foo.php'

<?php declare(strict_types=1);

#[ClassAttr]
class Foo {

    #[PropAttr]
    private string $prop = 'foo';

    #[MethodAttr]
    public function getProp() : string {
        return $this->prop;
    }
    
}

要访问这些属性,我们需要解析源代码。这可以通过使用 Cspray\AnnotatedTarget\parseAttributes 函数完成,或者您可以直接使用 Cspray\AnnotatedTarget\PhpParserAnnotatedTargetParser。推荐使用 parseAttributes 函数与该库交互。

如果您想获取 所有 属性,您可以仅传递要扫描的目录。库将查看所有以 .php 结尾的源文件,并对其使用属性进行静态分析。第一个参数可以接受字符串或数组,以防您要扫描多个目录。

<?php declare(strict_types=1);

use function Cspray\AnnotatedTarget\parseAttributes;

// parseAttributes returns a Generator, iterate over it to retrieve all Attributes found
foreach (parseAttributes(__DIR__ . '/src') as $annotatedTarget) {
    // $annotatedTarget is an instanceof AnnotatedTarget
    // This will be a ReflectionClass, ReflectionProperty, or ReflectionMethod depending on which iteration
    $target = $annotatedTarget->getTargetReflection();
    // This will be a ReflectionAttribute
    $attributeReflection = $annotatedTarget->getAttributeReflection();
    // This will be an instance of the Attribute returned from $this->getAttributeReflection()->newInstance()
    $attributeInstance = $annotatedTarget->getAttributeInstance();
    
    // All the methods above are shared
    $isShared = $annotatedTarget->getTargetReflection() === $annotatedTarget->getTargetReflection(); // true
}

如果您只关心某些属性,您可以向 parseAttributes 传递第二个参数,即要筛选的属性类型数组。例如,要获取仅 #[MethodAttr] 属性,我们将运行以下操作。

<?php declare(stric_types=1)

use function Cspray\AnnotatedTarget\parseAttributes;

foreach (parseAttributes(__DIR__ . '/src', [MethodAttr::class]) as $target) {
    // Only targets for usages of MethodAttr will be included
}