
# Fetch 传输

Phasis 中默认的 `fetch()` 通过 PHP 的 `ext-curl` 运行——`CURLOPT_FOLLOWLOCATION=false`（规范中的重定向循环在 Phasis 环境中运行），并由 `CURLOPT_PROGRESSFUNCTION` 轮询 `AbortSignal`。对于大多数嵌入场景，这样就足够了。

其他场景——代理、自定义 DNS、宿主应用已有的 HTTP 客户端、网络沙箱、测试模拟——都可以使用**可插拔**传输。

## 接口

```php
public function setFetchTransport(callable $transport): void
```

你的可调用对象会收到：

```php
function (array $request, ?\Phasis\Value\JsObject $signal): array
```

`$request` 是一个关联数组：

| 键 | 类型 | 说明 |
|---|---|---|
| `method` | `string` | 已转换为大写（`GET`、`POST`、…） |
| `url` | `string` | 经 URL 解析器和重定向链解析后的绝对 URL |
| `headers` | `list<list<string>>` | `[name, value]` 键值对；大小写按规范进行规范化；多值条目使用独立键值对（如 Set-Cookie） |
| `body` | `string` | 原始字节。无正文的方法会使用空字符串。 |
| `redirect` | `string` | `"follow"` / `"error"` / `"manual"`（传输不应跟随重定向——重定向循环在 Phasis 中运行） |
| `timeout` | `int` | 墙上时钟预算，单位为毫秒。`0` = 无限制。 |
| `credentials` | `string` | `"omit"` / `"same-origin"` / `"include"` — 仅供参考；Cookie 通过 `setCookieJar()` 单独接入。 |

如果请求没有提供信号，`$signal` 为 `null`；否则它是一个公开 `aborted` 和 `reason` 的 `JsObject`。长时间传输期间应轮询它。

返回值结构：

```php
return [
    'status'     => 200,                          // int
    'statusText' => 'OK',                         // string
    'headers'    => [['content-type', 'text/plain'], ['x-custom', '1']],
    'body'       => '...response bytes...',       // string
];
```

如果传输抛出异常，Phasis 会捕获并转换：

- 带有 `$e->kind === "aborted"` 的 `Phasis\BuiltIn\Fetch\TransportException` → `fetch` 以 `AbortError DOMException` 拒绝。
- `kind === "timeout"` → 携带该消息的 `TypeError`。
- `kind === "network-error"`（默认）→ `TypeError`。
- 其他任何情况 → 带有异常消息的 `TypeError`。

## 示例详解

### Guzzle

```php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

$client = new Client(['allow_redirects' => false]);

$engine->setFetchTransport(function (array $req, $signal) use ($client) {
    try {
        $r = $client->request($req['method'], $req['url'], [
            'headers'     => collect($req['headers'])->groupBy(0)->map->pluck(1)->all(),
            'body'        => $req['body'],
            'timeout'     => max(1, $req['timeout'] / 1000.0),
            'http_errors' => false,
        ]);
    } catch (GuzzleException $e) {
        throw new \Phasis\BuiltIn\Fetch\TransportException($e->getMessage(), 'network-error');
    }
    $headers = [];
    foreach ($r->getHeaders() as $name => $values) {
        foreach ($values as $v) {
            $headers[] = [$name, $v];
        }
    }
    return [
        'status'     => $r->getStatusCode(),
        'statusText' => $r->getReasonPhrase(),
        'headers'    => $headers,
        'body'       => (string) $r->getBody(),
    ];
});
```

### Symfony HttpClient

```php
use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create(['max_redirects' => 0]);

$engine->setFetchTransport(function (array $req, $signal) use ($client) {
    $headers = [];
    foreach ($req['headers'] as [$name, $value]) {
        $headers[$name][] = $value;
    }
    $r = $client->request($req['method'], $req['url'], [
        'headers'      => $headers,
        'body'         => $req['body'],
        'timeout'      => $req['timeout'] / 1000.0,
        'max_redirects'=> 0,
    ]);
    return [
        'status'     => $r->getStatusCode(),
        'statusText' => '',
        'headers'    => collect($r->getHeaders(false))
            ->flatMap(fn ($values, $name) => array_map(fn ($v) => [$name, $v], $values))
            ->values()->all(),
        'body'       => $r->getContent(false),
    ];
});
```

### 全部拒绝

```php
$engine->setFetchTransport(function () {
    throw new \Phasis\BuiltIn\Fetch\TransportException(
        'network access disabled in this sandbox',
        'network-error',
    );
});
```

这样所有 `fetch()` 调用都会以 TypeError 拒绝。适合沙箱化用户提供的 JS。

### 用于测试的模拟传输

```php
$canned = [
    'https://api.example.com/users' => ['status' => 200, 'body' => '{"users":[]}'],
    'https://api.example.com/404'   => ['status' => 404, 'body' => 'not found'],
];

$engine->setFetchTransport(function (array $req) use ($canned) {
    $r = $canned[$req['url']] ?? ['status' => 500, 'body' => 'no mock'];
    return [
        'status'     => $r['status'],
        'statusText' => $r['status'] === 200 ? 'OK' : 'ERR',
        'headers'    => [['content-type', 'application/json']],
        'body'       => $r['body'],
    ];
});
```

## 策略钩子

传输负责执行请求；**策略钩子**决定是否执行请求。可用于仅针对 HTTPS 的强制限制、注入标头、重写 URL、设置允许列表或按租户绑定凭据。

```php
public function setFetchPolicy(callable $hook): void
```

钩子签名：`function (JsObject $request): ?JsObject`。返回 `null` 表示原样放行。返回 Request 会重写请求。抛出异常会使 fetch 带着该异常拒绝。

```php
$allowedHosts = ['api.example.com', 'cdn.example.com'];

$engine->setFetchPolicy(function ($req) use ($allowedHosts) {
    $url = parse_url($req->get('url')->value);
    if (!in_array($url['host'] ?? '', $allowedHosts, true)) {
        throw new \RuntimeException("host not allowed: " . ($url['host'] ?? ''));
    }
    // Inject internal-only auth header
    $req->get('headers')->call('set', 'X-Internal-Token', $secret);
    return null;
});
```

策略钩子在传输**之前**运行，因此即使传输存在缺陷或不可信，也无法绕过它。

## 默认行为摘要

| 注意事项 | 默认行为 |
|---|---|
| 传输 | `CurlTransport`（PHP `ext-curl`） |
| 重定向 | 按规范最多跟随 20 次。`redirect: "manual"` 会返回带有 `type: "opaqueredirect"` 的重定向 Response。 |
| 超时 | 墙上时钟 30 s，连接 10 s |
| TLS 验证 | `CURLOPT_SSL_VERIFYPEER = true`（不可禁用——可通过替换传输覆盖） |
| User-Agent | 仅在未设置时注入 `Phasis/0.1` |
| Cookie | 不存储。使用 `setCookieJar()` 启用。 |
| 策略钩子 | 无。除非明确拒绝，否则允许所有请求。 |
| AbortSignal | 通过 curl 进度回调轮询，在传输过程中予以响应。 |

## 另请参阅

- [API 参考](https://phasis.inline0.dev/zh/docs/api#fetch-hooks) — Fetch 钩子的简短签名参考。
- [Web API](https://phasis.inline0.dev/zh/docs/compatibility/web-apis) — Fetch Pack 的完整功能范围。
- [Cookie jar](https://phasis.inline0.dev/zh/docs/interop/cookie-jar) — 使用 PHP 或 JS jar 对象，在多次 fetch 之间保存 Cookie。
