
# Trasporto fetch

La `fetch()` predefinita in Phasis passa per PHP `ext-curl`: `CURLOPT_FOLLOWLOCATION=false` (il ciclo di reindirizzamento delle specifiche viene eseguito lato Phasis) con `CURLOPT_PROGRESSFUNCTION` che controlla `AbortSignal`. Per la maggior parte delle integrazioni è una soluzione adeguata.

Per tutto il resto — proxy, DNS personalizzati, client HTTP già presente nell'app host, isolamento della rete, mock nei test — il trasporto è **sostituibile**.

## L'interfaccia

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

Il vostro callable riceve:

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

`$request` è un array associativo:

| Chiave | Tipo | Note |
|---|---|---|
| `method` | `string` | Già convertito in maiuscolo (`GET`, `POST`, …) |
| `url` | `string` | URL assoluto risolto dopo il parser URL e la catena di reindirizzamenti |
| `headers` | `list<list<string>>` | Coppie di `[name, value]`; maiuscole e minuscole secondo la normalizzazione delle specifiche; le voci con più valori sono coppie separate (Set-Cookie ecc.) |
| `body` | `string` | Byte grezzi. Stringa vuota per i metodi senza corpo. |
| `redirect` | `string` | `"follow"` / `"error"` / `"manual"` (il vostro trasporto NON deve seguirlo: il ciclo di reindirizzamento viene eseguito lato Phasis) |
| `timeout` | `int` | Tempo massimo in millisecondi. `0` = nessun limite. |
| `credentials` | `string` | `"omit"` / `"same-origin"` / `"include"` — solo a scopo informativo; i cookie sono gestiti separatamente tramite `setCookieJar()`. |

`$signal` è `null` se la richiesta non ha un segnale, altrimenti è un `JsObject` che espone `aborted` e `reason`. Controllatelo durante i trasferimenti lunghi.

Formato del valore restituito:

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

Se il trasporto genera un'eccezione, Phasis la intercetta e la converte:

- Un `Phasis\BuiltIn\Fetch\TransportException` con `$e->kind === "aborted"` → `fetch` viene rifiutato con `AbortError DOMException`.
- `kind === "timeout"` → `TypeError` con il messaggio dell'errore.
- `kind === "network-error"` (predefinito) → `TypeError`.
- Qualsiasi altro valore → `TypeError` con il messaggio dell'eccezione.

## Esempi pratici

### 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),
    ];
});
```

### Nega tutto

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

In questo modo ogni chiamata `fetch()` viene rifiutata con TypeError. Utile per isolare in una sandbox il codice JS fornito dagli utenti.

### Mock per i test

```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'],
    ];
});
```

## L'hook delle policy

Il trasporto esegue la richiesta; l'**hook delle policy** decide se eseguirla. Usatelo per imporre HTTPS soltanto, aggiungere header, riscrivere URL, definire liste consentite o associare credenziali per tenant.

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

Firma dell'hook: `function (JsObject $request): ?JsObject`. Restituendo `null`, la richiesta viene consentita senza modifiche. Restituendo un oggetto Request, viene riscritta. Se l'hook genera un'eccezione, la richiesta fetch viene rifiutata con l'errore generato.

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

L'hook delle policy viene eseguito **prima** del trasporto, quindi non può essere aggirato neppure da un trasporto difettoso o non attendibile.

## Riepilogo del comportamento predefinito

| Aspetto | Impostazione predefinita |
|---|---|
| Trasporto | `CurlTransport` (PHP `ext-curl`) |
| Reindirizzamenti | Fino a 20, secondo le specifiche. `redirect: "manual"` restituisce la risposta di reindirizzamento con `type: "opaqueredirect"`. |
| Timeout | 30 s di tempo reale, 10 s per la connessione |
| Verifica TLS | `CURLOPT_SSL_VERIFYPEER = true` (senza possibilità di disattivarla; sostituite il trasporto per modificarla) |
| User-Agent | `Phasis/0.1` aggiunto solo se non è impostato |
| Cookie | Nessuno memorizzato. Usate `setCookieJar()` per abilitarli. |
| Hook delle policy | Nessuno. Tutte le richieste sono consentite, a meno che non vengano negate esplicitamente. |
| AbortSignal | Rispettato durante il trasferimento tramite il controllo della callback di avanzamento curl. |

## Vedi anche

- [API riferimento — Hook Fetch](https://phasis.inline0.dev/it/docs/api#fetch-hooks) — riferimento sintetico alle firme.
- [API web](https://phasis.inline0.dev/it/docs/compatibility/web-apis) — superficie completa del Fetch Pack.
- [Archivio cookie](https://phasis.inline0.dev/it/docs/interop/cookie-jar) — conservazione dei cookie tra le richieste fetch con un oggetto archivio PHP o JS.
