Remplacement du wrapper http PHP
<?php
// based on Alexandre Daubois code
// Refactored to make it running here
class MockHttp
{
private string $data = '';
private int $pos = 0;
public $context;
public function stream_open(
string $path,
string $mode,
int $options,
?string &$opened_path = null
): bool {
$this->data = json_encode([
'mocked' => true,
'url' => $path,
]);
$this->pos = 0;
return true;
}
public function stream_read(int $count): string
{
$result = substr($this->data, $this->pos, $count);
$this->pos += strlen($result);
return $result;
}
public function stream_eof(): bool
{
return $this->pos >= strlen($this->data);
}
public function stream_stat(): array
{
return [
'size' => strlen($this->data),
];
}
// Required when using STREAM_IS_URL in modern PHP versions
public function url_stat(string $path, int $flags): array|false
{
return [
'size' => strlen($this->data),
];
}
}
stream_wrapper_unregister('http');
stream_wrapper_register('http', MockHttp::class, STREAM_IS_URL);
$data = file_get_contents('http://api.example.com/users');
var_dump($data);
stream_wrapper_restore('http');
Saviez-vous que vous pouvez remplacer des protocoles intégrés tels que https:// ?
Vous pouvez créer des mocks ! Je vous conseille d’utiliser des outils dédiés comme #Symfony MockHttpClient. Mais dans le cas de PHP vanilla…
Je vous laisse me dire si c’est une bonne ou une terrible idée 😉.
See Also
- original tweet
- http wrapper renewed [Try me]
PHP Features
Last updated: 09 November 2026