> ## 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 公開的靜態分析生態系的三個套件（surveyor、ranger、roster）。從 PHP 程式碼分析到套件偵測，解說套件開發者與工具作者應了解的新工具群。

<Info>
  本文根據 GitHub 儲存庫的 README 與原始碼整理。這三個套件目前皆為正式發佈前的 Beta 版（2026 年 4 月時點）。
</Info>

<Warning>
  surveyor、ranger、roster 皆為 **Beta 發佈中**。API 有可能在 v1.0.0 前變更。用於正式環境請審慎評估。
</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 年後公開了三個與程式碼分析相關的套件。它們可獨立使用，但也共同構成一個**程式碼分析生態系**。

```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();

// Union 型別（如 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 模型時會嘗試連線資料庫進行特殊分析，會偵測到模型的關聯、屬性、accessor 與 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
```

### 基本用法

以 callback 形式撰寫各元件被發現時的處理。

```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) {
    //
});

// 走訪整個應用並觸發 callback
$ranger->walk();
```

### Ranger 收集的元件

| Collector                | 說明                                         |
| ------------------------ | ------------------------------------------ |
| **Routes**               | 所有已註冊路由（URI、參數、HTTP 方法、Controller、驗證規則、回應） |
| **Models**               | Eloquent 模型與屬性、型別、關聯                       |
| **Enums**                | PHP 的 Backed Enum（整數或字串值）與其 case、值         |
| **BroadcastEvents**      | 實作 `ShouldBroadcast` 的事件與 payload          |
| **BroadcastChannels**    | 已註冊的廣播 channel                             |
| **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 Agent（GitHub Copilot、Claude 等）產生準則與技能。它會根據「這個專案是否使用 Inertia？」「是否安裝 Livewire？」等資訊，挑選合適的準則檔案提供給 AI Agent。

```mermaid theme={null}
sequenceDiagram
    participant Boost as Laravel Boost
    participant Roster as laravel/roster
    participant AI as AI Agent
    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

- [部落格](/zh-TW/blog/index.md)
- [Laravel Boost](/zh-TW/boost.md)
- [博客](/zh-CN/blog/index.md)
- [Laravel 與 AI 開發](/zh-TW/ai.md)
- [PHP AST](/zh-TW/advanced/php-ast.md)
