PHP code example of cleatsquad / php-http-replay

1. Go to this page and download the library: Download cleatsquad/php-http-replay library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cleatsquad / php-http-replay example snippets


use CleatSquad\HttpReplay\Engine\HttpReplayEngine;
use CleatSquad\HttpReplay\Enum\ExecutionMode;
use CleatSquad\HttpReplay\Integration\Guzzle\GuzzleReplayHandler;
use CleatSquad\HttpReplay\Matcher\DefaultRequestMatcher;
use CleatSquad\HttpReplay\Sanitizer\DefaultSanitizer;
use CleatSquad\HttpReplay\Storage\JsonCassetteStore;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$engine = new HttpReplayEngine(
    ExecutionMode::Replay,
    new JsonCassetteStore(__DIR__ . '/fixtures/cassettes'),
    'openai_chat_cassette',
    new DefaultRequestMatcher(),
    new DefaultSanitizer()
);

$client = new Client(['handler' => HandlerStack::create(new GuzzleReplayHandler($engine))]);

// No network call: the recorded PSR-7 response is returned as is.
$response = $client->post('https://api.openai.com/v1/chat/completions', [
    'json' => ['model' => 'gpt-4o', 'messages' => [['role' => 'user', 'content' => 'Hello']]],
]);

use CleatSquad\HttpReplay\Enum\ExecutionMatchingMode;

$engine = new HttpReplayEngine(
    ExecutionMode::Replay,
    $cassetteStore,
    'cassette_name',
    $requestMatcher,
    $sanitizer,
    matchingMode: ExecutionMatchingMode::Unordered,
);

try {
    $engine->sendRequest($request);
} catch (RequestMismatchException $e) {
    echo $e->toCliString(colorize: true);
}

$sanitizer = new DefaultSanitizer(
    sensitiveHeaders: ['authorization', 'x-api-key'],
    sensitiveBodyKeys: ['api_key', 'token', 'secret'],
    sensitiveQueryParams: ['api_key', 'token'],
    replacement: '[REDACTED]',
    sensitiveJsonPaths: ['$.user.profile.token', 'payment.card.number'],
);

$stats = $engine->stats();
echo "Replayed: {$stats->replayedCount}/{$stats->totalExchanges}\n";

if ($stats->hasUnusedExchanges()) {
    echo "Unused exchange indices: " . implode(', ', $stats->unusedIndices);
}

if ($stats->isFullyConsumed()) {
    echo "All cassette exchanges were executed successfully.";
}

use CleatSquad\HttpReplay\Naming\CallbackCassetteNamingStrategy;

$naming = new CallbackCassetteNamingStrategy(fn () => 'test_' . $testId);

use CleatSquad\HttpReplay\PhpVcr\PhpVcrCassetteImporter;

$cassette = PhpVcrCassetteImporter::fromYaml(__DIR__ . '/fixtures/legacy.yml');