
Imen Ezzine

PHP Symfony Developer

Side A · Part 1
Create a payment, issue a refund
Sync contacts, leads, opportunities
Stock, orders, invoices
A prompt in, and never the same answer twice
And every one of these features deserves tests.
| Real HTTP calls | Handwritten mocks | |
|---|---|---|
| Realism | Real responses | What we imagine the API returns |
| Speed | Slow (network) | Instant |
| Stability in CI | Depends on the provider (quotas, outages) | Stable |
| Cost | Paying APIs bill every call (OpenAI, payments…) | Free |
| Secrets | API keys in CI | None |
| Maintenance | None… as long as the API answers | Tedious, and it drifts |
$client = new MockHttpClient([
new MockResponse(
json_encode([
'id' => 'pay_123',
'status' => 'succeeded',
'amount' => 4200,
'currency' => 'eur',
// ... and the 40 other fields of the real response?
]),
['response_headers' => ['content-type' => 'application/json']],
),
]);
$service = new PaymentService($client);
Tedious to write, and nothing guarantees it still looks like the API.
class PaymentServiceTest extends TestCase
{
private const API = 'https://api.payment.example.com/v1';
public function testPaymentRequiringAuthenticationThenPartialRefund(): void
{
$client = new MockHttpClient([
function (string $method, string $url, array $options): MockResponse {
$this->assertSame('POST', $method);
$this->assertSame(self::API.'/customers', $url);
$this->assertSame('email=jane%40example.com&name=Jane+Doe&metadata%5Border_id%5D=1337', $options['body']);
$this->assertSame('Authorization: Bearer sk_test_123', $options['normalized_headers']['authorization'][0]);
$this->assertSame('Idempotency-Key: order-1337-customer', $options['normalized_headers']['idempotency-key'][0]);
return new MockResponse(json_encode([
'id' => 'cus_123', 'object' => 'customer', 'created' => 1760000000, 'email' => 'jane@example.com', 'name' => 'Jane Doe',
'balance' => 0, 'currency' => null, 'default_source' => null, 'delinquent' => false, 'description' => null, 'discount' => null,
'invoice_prefix' => 'A1B2C3', 'invoice_settings' => ['custom_fields' => null, 'default_payment_method' => null, 'footer' => null],
'livemode' => false, 'metadata' => ['order_id' => '1337'], 'phone' => null, 'preferred_locales' => [], 'shipping' => null, 'tax_exempt' => 'none',
]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_1']]);
},
function (string $method, string $url, array $options): MockResponse {
$this->assertSame('POST', $method);
$this->assertSame(self::API.'/payment_intents', $url);
$this->assertSame('amount=4200¤cy=eur&customer=cus_123&payment_method=pm_card_3ds&confirm=true&return_url=https%3A%2F%2Fshop.example.com%2Freturn', $options['body']);
$this->assertSame('Idempotency-Key: order-1337-payment', $options['normalized_headers']['idempotency-key'][0]);
return new MockResponse(json_encode([
'id' => 'pay_123', 'object' => 'payment_intent', 'amount' => 4200, 'amount_capturable' => 0, 'amount_received' => 0, 'currency' => 'eur',
'customer' => 'cus_123', 'status' => 'requires_action', 'capture_method' => 'automatic', 'confirmation_method' => 'automatic',
'client_secret' => 'pay_123_secret_456', 'created' => 1760000001, 'livemode' => false, 'payment_method' => 'pm_card_3ds',
'next_action' => ['type' => 'redirect_to_url', 'redirect_to_url' => ['url' => 'https://hooks.payment.example.com/3ds/pay_123', 'return_url' => 'https://shop.example.com/return']],
'payment_method_options' => ['card' => ['request_three_d_secure' => 'automatic', 'installments' => null, 'mandate_options' => null, 'network' => null]],
'payment_method_types' => ['card'], 'last_payment_error' => null, 'latest_charge' => null, 'metadata' => [], 'setup_future_usage' => null,
]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_2']]);
},
function (string $method, string $url, array $options): MockResponse {
$this->assertSame('GET', $method);
$this->assertSame(self::API.'/payment_intents/pay_123?expand%5B0%5D=latest_charge', $url);
return new MockResponse(json_encode([
'id' => 'pay_123', 'object' => 'payment_intent', 'amount' => 4200, 'amount_received' => 4200, 'currency' => 'eur', 'status' => 'succeeded',
'latest_charge' => [
'id' => 'ch_789', 'object' => 'charge', 'amount' => 4200, 'amount_captured' => 4200, 'amount_refunded' => 0, 'captured' => true, 'paid' => true,
'balance_transaction' => 'txn_321', 'billing_details' => ['address' => ['city' => 'Paris', 'country' => 'FR', 'line1' => null, 'postal_code' => '75002'], 'email' => 'jane@example.com'],
'outcome' => ['network_status' => 'approved_by_network', 'reason' => null, 'risk_level' => 'normal', 'risk_score' => 12, 'seller_message' => 'Payment complete.', 'type' => 'authorized'],
'payment_method_details' => ['type' => 'card', 'card' => ['brand' => 'visa', 'country' => 'FR', 'exp_month' => 12, 'exp_year' => 2030, 'funding' => 'credit', 'last4' => '3184',
'three_d_secure' => ['authentication_flow' => 'challenge', 'result' => 'authenticated', 'version' => '2.2.0'], 'network' => 'visa']],
'receipt_url' => 'https://pay.example.com/receipts/ch_789', 'refunded' => false, 'refunds' => ['object' => 'list', 'data' => [], 'has_more' => false],
],
'next_action' => null, 'last_payment_error' => null, 'customer' => 'cus_123', 'livemode' => false, 'metadata' => [],
]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_3']]);
},
function (string $method, string $url, array $options): MockResponse {
$this->assertSame('POST', $method);
$this->assertSame(self::API.'/refunds', $url);
$this->assertSame('payment_intent=pay_123&amount=1500&reason=requested_by_customer&metadata%5Border_id%5D=1337', $options['body']);
return new MockResponse(json_encode([
'id' => 're_654', 'object' => 'refund', 'amount' => 1500, 'balance_transaction' => 'txn_987', 'charge' => 'ch_789', 'created' => 1760000420,
'currency' => 'eur', 'destination_details' => ['type' => 'card', 'card' => ['reference' => '7412589630', 'reference_status' => 'available', 'reference_type' => 'acquirer_reference_number', 'type' => 'refund']],
'metadata' => ['order_id' => '1337'], 'payment_intent' => 'pay_123', 'reason' => 'requested_by_customer', 'receipt_number' => null, 'status' => 'succeeded',
]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_4']]);
},
new MockResponse('{"error":{"type":"rate_limit_error","code":"rate_limit","message":"Too many requests, please retry later."}}', ['http_code' => 429, 'response_headers' => ['retry-after' => '1']]),
new MockResponse('{"object":"list","data":[{"id":"re_654","amount":1500,"status":"succeeded"}],"has_more":false,"url":"/v1/refunds"}', ['http_code' => 200]),
]);
$service = new PaymentService($client, 'sk_test_123', new NullLogger());
$payment = $service->pay(new Order(1337, 4200, 'eur', new Customer('jane@example.com', 'Jane Doe')), 'pm_card_3ds');
$this->assertSame('requires_action', $payment->status);
$this->assertSame('https://hooks.payment.example.com/3ds/pay_123', $payment->redirectUrl);
$this->assertSame('succeeded', $service->refresh($payment)->status);
$this->assertSame('succeeded', $service->refund($payment, 1500)->status);
$this->assertCount(1, $service->refunds($payment));
$this->assertSame(6, $client->getRequestsCount());
}
}


… your mocks did not notice a thing.
The test makes the real calls once and saves every request / response pair.
The recording lives next to the test and is reviewed in the pull request like code.
Every following run replays the responses, without the network.
The idea is not new: php-vcr has been doing it for years.
Since Symfony 8.2, it is built into HttpClient, with no external dependency.
RecorderHttpClient
Decorates the HTTP client: replays, records, or passes through.
#[UseRecord]
Tells which HAR file a test uses.
SYMFONY_HTTP_RECORDER
Decides whether to replay or to record.
Side A · Part 2
The W3C JSON format for archiving HTTP exchanges: readable, reviewed in a pull request like code, opened by browser devtools
{
"startedDateTime": "2026-09-03T14:07:14.638Z",
"request": {
"method": "POST",
"url": "https://auth.example.com/oauth/token",
"postData": {
"text": "grant_type=client_credentials&client_secret=%5BREDACTED%5D"
}
},
"response": {
"status": 200,
"headers": [{"name": "content-type", "value": "application/json"}],
"content": {
"mimeType": "application/json",
"text": "{\"access_token\":\"[REDACTED]\",\"expires_in\":3600}"
}
}
}
Simplified excerpt of a file written by the recorder. A binary body is stored as base64.
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Test\HarFileResponseFactory;
$client = new MockHttpClient(new HarFileResponseFactory(__DIR__.'/fixtures/api.har'));
HarFileResponseFactory already exists in the componentThe recorder builds on what is already there: one HAR format, to record and to replay.
Step 1
<!-- phpunit.dist.xml -->
<extensions>
<bootstrap class="Symfony\Bridge\PhpUnit\SymfonyExtension">
<!-- optional: all recordings in a single directory -->
<parameter name="http-recorder-directory" value="tests/records"/>
</bootstrap>
</extensions>
Without the parameter, each .har file lives next to its test. With it, the tree follows the namespace: tests/records/App/Tests/FooTest/testBar.har
Step 2
use Symfony\Bridge\PhpUnit\Attribute\UseRecord;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class GetRandomControllerTest extends WebTestCase
{
#[UseRecord]
public function testRandom(): void
{
$client = static::createClient();
$client->request('GET', '/random');
$this->assertResponseIsSuccessful();
}
}
The test uses GetRandomControllerTest/testRandom.har, stored next to it. Nothing else changes in the code.
Step 3
GetRandomControllerTest/testRandom.har is writtenSYMFONY_HTTP_RECORDER=replay (the default when it is not set), replay, zero networkFail closed: a committed test never touches the network. Recording is an explicit choice.
With SYMFONY_HTTP_RECORDER=missing, a missing entry triggers the real call, which gets recorded.
# record a class again after an API change
SYMFONY_HTTP_RECORDER=record vendor/bin/phpunit --filter GetRandomControllerTest
# add what is missing in a group, without touching the rest
SYMFONY_HTTP_RECORDER=missing vendor/bin/phpunit --group payment
A recording mode must never be committed: it is a setting for the duration of a run.
Review the diff of the HAR files, like any other code.
SYMFONY_HTTP_RECORDER: a warning, then replaySide A · Part 3
Authorization, Proxy-Authorization, Cookie, Set-Cookie, DPoP, X-Api-Key, X-Auth-Token
IANA OAuth registry, OpenID Connect, SAML: access_token, refresh_token, id_token, client_secret, SAMLResponse…
password, secret, token, api_key
code and key: query string and forms only, not in JSON
+ URL fragments and the Location header, handled as URLs. On the request and on the response, before anything is written.
Real exchange
POST /oauth/token
Authorization: Basic bXktYXBwOnMzY3IzdA==
grant_type=client_credentials
&client_id=my-app&client_secret=s3cr3t
200 OK
{"access_token":"eyJhbGciOi...",
"token_type":"Bearer","expires_in":3600}
.har file
POST /oauth/token
Authorization: [REDACTED]
grant_type=client_credentials
&client_id=my-app&client_secret=%5BREDACTED%5D
200 OK
{"access_token":"[REDACTED]",
"token_type":"Bearer","expires_in":3600}
Without redaction, all of this would end up in a file the workflow asks you to commit.
http_client:
recorder:
# headers, query string, forms and JSON: added to the built-in lists
redact: ['X-Custom-Secret', 'sig', 'pin']
# never redacted, removed from the built-in lists
redact_except: ['code']
# or replace the redaction entirely
redactor: ~ # RedactorInterface service
redact_except: when code is not a secret in your tests, and you need it.
A field that changes on every request (timestamp, nonce, request id)? Add it to redact: redacted on both sides, it is also ignored when matching.
{"meta":{},"password":"x","n":1.0,"big":12345678901234567890}
json_decode + json_encode
{"meta":[],"password":"[REDACTED]","n":1,"big":1.2345678901234567e+19}
In-place replacement
{"meta":{},"password":"[REDACTED]","n":1.0,"big":12345678901234567890}
The JSON is no longer decoded then re-encoded: sensitive values are replaced in a single pass, the rest is byte-for-byte identical ({}, floats, big integers, escapes, formatting).
GET, POST…
Absolute, query string included
When it is a string; a streamed body is not compared
Requests are first normalised the way HttpClient does it: json, query, base_uri, auth_basic, auth_bearer… end up in the recorded URL, body and headers.
Secrets redacted on both sides, and the random boundary of a multipart body replaced with a fixed value.
Redaction is deterministic: the real request, with its real secrets, still matches.
Why not store a hash of the real request next to it? A short secret in a query string could still be guessed offline from a committed file.
// Recorded: an asynchronous export polled until it is ready
$client->request('GET', 'https://api.example.com/exports/42')->toArray(); // 202
$client->request('GET', 'https://api.example.com/exports/42')->toArray(); // 200
// On replay: 202, then 200, then 200 (the last response is served again)
KernelBrowserRetryableHttpClient cancels the failed attempt: a 500 then a 200 only records the 200Side B · Part 4
// Not recorded: the exception consumes the response
$response->getContent(); // ClientException on a 404
// Recorded with its status and its body
$response->getContent(false);
$response->toArray(false);
Only fully received responses are written. A response destroyed without being read, cancelled, or consumed through the exception is not recorded: on replay, the test fails clearly instead of receiving an empty body.
{"access_token":"[REDACTED]","id_token":"[REDACTED]","token_type":"Bearer"}
id_token will failredact_except, or your own RedactorInterfaceSide B · Part 5
500 · timeout · diff
$client = new MockHttpClient([
// The provider is down
new JsonMockResponse(['error' => 'unavailable'], ['http_code' => 503]),
// The provider never answers: an empty chunk is an idle timeout
new MockResponse((static function () { yield ''; })()),
// The connection fails before any response
new MockResponse(info: ['error' => 'Could not resolve host']),
]);
$service = new PaymentService($client);
A real API will not give you a 503 or a timeout when you ask for one. Here the handwritten mock is the right tool: the response is short, and it is the scenario itself.
Your code handles the response as the API sent it on recording day: real fields, real formats, real headers.
That the API still answers that way. If the provider renames a field tomorrow, the replay stays green.
Better than a handwritten mock, but the same blind spot. So we check the contract regularly, by hand, in dev, never in CI.
# on your machine, with sandbox keys, every few weeks
SYMFONY_HTTP_RECORDER=passthrough vendor/bin/phpunit --group third-party
passthrough: real calls, .har files neither read nor writtenSecrets in CI, a bill on every run, failures you do not control, real payments. This check stays a manual step: it does not get automated.
SYMFONY_HTTP_RECORDER=record vendor/bin/phpunit --group third-party
git diff tests/records/
"content": {
"mimeType": "application/json",
- "text": "{\"status\":\"succeeded\",\"amount\":4200}"
+ "text": "{\"status\":\"paid\",\"amount\":{\"value\":4200}}"
}
An unchanged exchange keeps its exact place in the file: the diff only shows what the API changed. Review it, adapt the code, commit the new contract.
Side B · Part 6
We do want record and replay in HttpClient […] build on what is already there instead of alongside it.
None of this is a rejection of the idea. It is a request to make the recorder produce real HAR that our existing reader consumes, to fail closed, and to keep secrets out of files people commit. Nicolas Grekas, August 17, 2026
| First version | Today | |
|---|---|---|
| Secrets | Authorization, cookies, tokens written as is | Redacted by default, request and response |
| Missing entry | Real network call by default, silently | Exception, never the network |
stream() | Broken, and getContent() serialised the requests | AsyncResponse, recorded chunk after chunk |
| Options | timeout: 5 became 60 s when recording | Original options passed through as is |
Side B · Part 7
RecorderHttpClient
Real exchanges, in the standard HAR format
DefaultRedactor
Secrets, by default, before anything is written
method · URL · body
The right response, in the right order
MockHttpClient
Without the network, with a simple #[UseRecord]
One attribute, one command, and your tests no longer depend on the network.

@nicolas-grekas

@Jean-Beru

@Neirda24

@welcoMattic
Imen Ezzine
@imenezzine