Skip to content

Instantly share code, notes, and snippets.

@fancyweb
Created March 30, 2023 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancyweb/0a54ae6293eaf02c3823e9b921cada5a to your computer and use it in GitHub Desktop.
Save fancyweb/0a54ae6293eaf02c3823e9b921cada5a to your computer and use it in GitHub Desktop.
49796.php
<?php
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpClient\TraceableHttpClient;
final class Foo
{
public function __construct(private readonly HttpClientInterface $httpClient)
{
}
public function bar(): \Generator
{
$contentGenerator = $this->streamContent();
while ($contentGenerator->valid()) {
$content = $contentGenerator->current();
if (yield $content) {
$contentGenerator->send(true);
continue;
}
$contentGenerator->send(false);
}
}
private function streamContent(): \Generator
{
$response = $this->httpClient->request('GET', 'https://symfony.com');
foreach ($this->httpClient->stream($response) as $response => $chunk) {
if (yield $chunk->getContent()) {
$response->cancel();
break;
}
}
}
}
$mockResponse = new MockResponse([
'fo',
'o',
'ba',
'r',
]);
$httpClient = new TraceableHttpClient(new MockHttpClient($mockResponse));
$generator = (new Foo($httpClient))->bar();
while ($generator->valid()) {
$content = $generator->current();
if ('ba' === $content) {
$generator->send(true);
continue;
}
$generator->send(false);
}
dump($mockResponse->getInfo('canceled')); // false
dump($httpClient->getTracedRequests()[0]['info']['canceled']); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment