> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel 新代码分析生态 — surveyor / ranger / roster

> 介绍构成 Laravel 官方静态分析生态的 3 个包(surveyor、ranger、roster)。从 PHP 代码分析到包检测,解析包开发者与工具作者应当了解的这套新工具。

<Info>
  本文基于 GitHub 仓库的 README 与源代码进行整理。3 个包目前都还是正式发布前的 Beta 版(截至 2026 年 4 月)。
</Info>

<Warning>
  surveyor、ranger、roster 都处于 **Beta 阶段**。在 v1.0.0 发布前 API 可能变更。生产环境使用时请谨慎评估。
</Warning>

## 最新发布状况(2026 年 4 月)

| 包                  | 最新版本      | 备注                                                                                                       |
| ------------------ | --------- | -------------------------------------------------------------------------------------------------------- |
| `laravel/roster`   | `v0.5.1`  | `laravel/boost` 的 `composer.json` 中要求 `^0.5.0`,并在 `BoostServiceProvider` 中执行 `Roster::scan(base_path())` |
| `laravel/ranger`   | `v0.1.12` | `composer.json` 中依赖 `laravel/surveyor:^0.1.0`                                                            |
| `laravel/surveyor` | `v0.1.9`  | 作为 `ranger` 的分析底座使用的低层包                                                                                  |

## 概览

Laravel 在 2026 年公开了 3 个与代码分析相关的包。它们既能单独使用,也相互协作,组成了一套**代码分析生态**。

```mermaid theme={null}
graph TD
    A["laravel/roster<br>包检测"] --> B["laravel/ranger<br>高层内省"]
    B --> C["laravel/surveyor<br>低层静态分析引擎"]
    D["Boost<br>AI 开发辅助工具"] --> A
    E["工具 / 包开发者"] --> A
    E --> B
    E --> C
```

| 包                  | 角色                | 安装                                      |
| ------------------ | ----------------- | --------------------------------------- |
| `laravel/surveyor` | PHP 代码的静态分析引擎     | `composer require laravel/surveyor`     |
| `laravel/ranger`   | 对整个 Laravel 应用的内省 | `composer require laravel/ranger`       |
| `laravel/roster`   | 生态中包的检测           | `composer require laravel/roster --dev` |

下面依次看每个包的细节。

***

## laravel/surveyor — 静态分析引擎

[laravel/surveyor](https://github.com/laravel/surveyor) 是一个静态分析工具,负责解析 PHP 文件,把类、方法、属性、返回类型等详细元信息以结构化的形式提供出去。它专注于把信息抽取成可供其他工具和包使用的形式。

### 安装

```bash theme={null}
composer require laravel/surveyor
```

### 基本用法

#### 分析文件

```php theme={null}
use Laravel\Surveyor\Analyzer\Analyzer;

$analyzer = app(Analyzer::class);

// 按文件路径分析
$result = $analyzer->analyze('/path/to/your/File.php');

// 访问已分析的 scope
$scope = $result->analyzed();

// 访问类分析结果
$classResult = $result->result();
```

#### 直接分析一个类

```php theme={null}
$result = $analyzer->analyzeClass(\App\Models\User::class);
$classResult = $result->result();
```

### ClassResult 中可以取到的信息

```php theme={null}
$classResult = $analyzer->analyzeClass(App\Models\User::class)->result();

// 类信息
$name = $classResult->name();            // 'App\Models\User'
$namespace = $classResult->namespace();  // 'App\Models'
$filePath = $classResult->filePath();

// 继承关系
$extends = $classResult->extends();
$implements = $classResult->implements();

// 方法信息
$method = $classResult->getMethod('store');
$returnType = $method->returnType();
$parameters = $method->parameters();
$rules = $method->validationRules(); // 也能取到验证规则

// 属性信息
$property = $classResult->getProperty('email');
$type = $property->type;
$visibility = $property->visibility; // 'public'、'protected'、'private'

// 公开的方法和属性列表
$publicMethods = $classResult->publicMethods();
$publicProperties = $classResult->publicProperties();
```

### 类型系统

Surveyor 有一套完整的类型系统,可以把 PHP 类型结构化地处理。

```php theme={null}
use Laravel\Surveyor\Types\Type;

// 各种类型的构造
$stringType = Type::string();
$intType = Type::int();
$boolType = Type::bool();
$nullType = Type::null();

// 联合类型(string|null 等)
$unionType = Type::union(Type::string(), Type::null());

// 类型判定
use Laravel\Surveyor\Types\StringType;

if (Type::is($returnType, StringType::class)) {
    // 字符串类型的处理
}
```

### 缓存设置

可以缓存分析结果,改善反复执行时的性能。

```php theme={null}
use Laravel\Surveyor\Analyzer\AnalyzedCache;

// 启用磁盘缓存
AnalyzedCache::enableDiskCache(storage_path('surveyor-cache'));

// 清理缓存
AnalyzedCache::clear();
```

也可以通过环境变量配置。

```env theme={null}
SURVEYOR_CACHE_ENABLED=true
SURVEYOR_CACHE_DIR=/path/to/cache
```

### Eloquent 模型分析

Surveyor 会尝试连接数据库,对 Eloquent 模型做特殊分析。模型的关联、属性、访问器和 cast 也会被检测。

```php theme={null}
$result = $analyzer->analyzeClass(App\Models\User::class)->result();

// 自动检测数据库属性
$emailProperty = $result->getProperty('email');

// 判定是否为关联方法
$method = $result->getMethod('posts');
if ($method->isModelRelation()) {
    // 这是一个关联方法
}
```

<Info>
  Surveyor 在分析 Eloquent 模型时会尝试连接数据库,因此并不是纯粹的静态分析。此外,性能和内存占用还在持续优化中,欢迎社区贡献。
</Info>

***

## laravel/ranger — 高层内省

[laravel/ranger](https://github.com/laravel/ranger) 封装了 surveyor,遍历整个 Laravel 应用,收集路由、模型、Enum、广播事件、环境变量、Inertia 组件等信息,是一个高层库。

### 安装

```bash theme={null}
composer require laravel/ranger
```

### 基本用法

以回调形式,声明各组件被发现时的处理逻辑。

```php theme={null}
use Laravel\Ranger\Ranger;
use Laravel\Ranger\Components;
use Illuminate\Support\Collection;

$ranger = app(Ranger::class);

// 每发现一条路由都会被调用
$ranger->onRoute(function (Components\Route $route) {
    echo $route->uri();
});

// 每发现一个模型都会被调用
$ranger->onModel(function (Components\Model $model) {
    foreach ($model->getAttributes() as $name => $type) {
        // 处理属性名和类型
    }
});

// 每发现一个 Enum 都会被调用
$ranger->onEnum(function (Components\Enum $enum) {
    //
});

// 每发现一个广播事件都会被调用
$ranger->onBroadcastEvent(function (Components\BroadcastEvent $event) {
    //
});

// 所有路由收集完成后会被调用一次
$ranger->onRoutes(function (Collection $routes) {
    //
});

// 所有模型收集完成后会被调用一次
$ranger->onModels(function (Collection $models) {
    //
});

// 遍历整个应用并触发回调
$ranger->walk();
```

### Ranger 收集的组件

| 收集器                      | 说明                                          |
| ------------------------ | ------------------------------------------- |
| **Routes**               | 所有注册的路由(URI、参数、HTTP 方法、控制器、验证规则、响应)         |
| **Models**               | Eloquent 模型及其属性、类型、关联                       |
| **Enums**                | PHP 的 Backed Enum(带整数或字符串值的 Enum)及其 case 和值 |
| **BroadcastEvents**      | 实现了 `ShouldBroadcast` 的事件及其 payload         |
| **BroadcastChannels**    | 已注册的广播频道                                    |
| **EnvironmentVariables** | `.env` 文件中定义的环境变量                           |
| **Inertia Shared Data**  | 全局共享的 Inertia.js props                      |
| **Inertia Components**   | Inertia.js 的页面组件及期望的 props                  |

***

## laravel/roster — 包检测工具

[laravel/roster](https://github.com/laravel/roster) 是一个用于检测项目中安装了哪些 Laravel 生态包的工具。包开发者和工具作者可以借此轻松获知“这个项目是否使用了 Inertia?”、“Livewire 的版本是多少?”等信息。

### 安装

```bash theme={null}
composer require laravel/roster --dev
```

### 基本用法

```php theme={null}
use Laravel\Roster\Roster;
use Laravel\Roster\Packages;

// 扫描目录得到 Roster
$roster = Roster::scan($directory);

// 已安装包列表
$roster->packages();

// 只看生产依赖
$roster->packages()->production();

// 只看开发依赖
$roster->packages()->dev();

// 判断是否存在指定包
$roster->uses(Packages::INERTIA);        // bool
$roster->uses(Packages::LIVEWIRE);       // bool

// 带版本条件判断
$roster->usesVersion(Packages::INERTIA, '2.0.0', '>=');   // Inertia 是否 >= 2.0.0?
$roster->usesVersion(Packages::LIVEWIRE, '3.0.0', '>=');  // Livewire 是否 >= 3.0.0?

// JavaScript 包管理器检测
$packageManager = $roster->nodePackageManager(); // 'npm'、'yarn'、'bun' 等
```

***

## 实际用例

### AI 指南生成工具(Boost)

[Laravel Boost](https://github.com/laravel/boost) 使用 roster 来了解已安装的包组合,并据此自动调整发送给 AI 智能体(如 GitHub Copilot、Claude 等)的指南和技能。基于“项目是否用 Inertia?”、“是否装了 Livewire?”这些信息,选择合适的指南文件提供给 AI 智能体。

```mermaid theme={null}
sequenceDiagram
    participant Boost as Laravel Boost
    participant Roster as laravel/roster
    participant AI as AI 智能体
    Boost->>Roster: Roster::scan(base_path())
    Roster->>Boost: packages() [Inertia、Livewire、Pint...]
    Boost->>Boost: 按包选择相应指南
    Boost->>AI: Inertia 指南、Livewire 指南……
```

### 制作包兼容性检查器

如果你正在开发一个需要根据用户项目里已安装的包来切换行为的包,roster 会非常有用。

```php theme={null}
use Laravel\Roster\Roster;
use Laravel\Roster\Packages;

$roster = Roster::scan(base_path());

if ($roster->uses(Packages::INERTIA)) {
    // 面向 Inertia 的处理
    if ($roster->usesVersion(Packages::INERTIA, '2.0.0', '>=')) {
        // 面向 Inertia v2 及以上的处理
    }
}

if ($roster->uses(Packages::LIVEWIRE)) {
    // 面向 Livewire 的处理
}

// 根据 JavaScript 包管理器切换安装命令
$pm = $roster->nodePackageManager();
echo "Run: {$pm} install your-package";
```

### 自动生成应用文档

使用 ranger,可以构建一个工具,自动收集 Laravel 应用的路由、模型、Enum,并生成文档。

```php theme={null}
use Laravel\Ranger\Ranger;
use Laravel\Ranger\Components;

$ranger = app(Ranger::class);
$docs = [];

$ranger->onRoute(function (Components\Route $route) use (&$docs) {
    $docs['routes'][] = [
        'uri' => $route->uri(),
        // 也可以获取路由的验证规则、响应类型等
    ];
});

$ranger->onModel(function (Components\Model $model) use (&$docs) {
    $docs['models'][] = [
        'attributes' => $model->getAttributes(),
    ];
});

$ranger->walk();

// $docs 中收集了整个应用的结构信息
```

***

## 总结

surveyor、ranger、roster 为 Laravel 生态提供了新的**通过程序进行代码分析**的基础。

```mermaid theme={null}
graph LR
    A["surveyor<br>解析 PHP 文件<br>抽取类 / 方法 / 类型"] --> B["ranger<br>扫描整个 Laravel 应用<br>收集路由 / 模型 / Enum"]
    B --> C["roster<br>检测已安装的包<br>确认版本 / 类型"]
```

这些包主要面向包开发者和工具作者,并不是普通终端用户直接使用的产品。但像 Laravel Boost 这样的 Laravel 官方工具也在其内部积极使用,未来会在生态中扮演越来越重要的角色。

<Columns cols={3}>
  <Card title="laravel/surveyor" icon="github" href="https://github.com/laravel/surveyor">
    PHP 代码的静态分析引擎
  </Card>

  <Card title="laravel/ranger" icon="github" href="https://github.com/laravel/ranger">
    高层内省库
  </Card>

  <Card title="laravel/roster" icon="github" href="https://github.com/laravel/roster">
    包检测工具
  </Card>
</Columns>


## Related topics

- [PHP AST](/zh/advanced/php-ast.md)
- [Laravel Octane](/zh/octane.md)
- [包的静态分析（PHPStan / Larastan）](/zh/advanced/package-static-analysis.md)
- [2026 年 3 月 Laravel 更新](/zh/blog/changelog/202603.md)
- [Laravel Console Starter](/zh/packages/laravel-console-starter/index.md)
