Skip to content

Commit 4b00f81

Browse files
committed
fix: read just one byte to check if a body is present
1 parent 6758ec7 commit 4b00f81

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

src/Parsers/ResponseParser.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,15 @@ private function responseHasBody(ResponseInterface $response): bool
5656
return true;
5757
}
5858

59-
$contents = (string) $body;
60-
$hasBody = trim($contents) !== '';
61-
6259
if ($body->isSeekable()) {
63-
$body->rewind();
60+
$pos = $body->tell();
61+
$chunk = $body->read(1);
62+
$body->seek($pos);
63+
} else {
64+
$chunk = $body->read(1);
6465
}
6566

66-
return $hasBody;
67+
return $chunk !== '';
6768
}
6869

6970
private function responseHasSuccessfulStatusCode(ResponseInterface $response): bool

tests/Parsers/ResponseParserTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use GuzzleHttp\Psr7\PumpStream;
88
use GuzzleHttp\Psr7\Response;
99
use PHPUnit\Framework\TestCase;
10+
use Psr\Http\Message\StreamInterface;
1011
use Swis\JsonApi\Client\CollectionDocument;
1112
use Swis\JsonApi\Client\Document;
1213
use Swis\JsonApi\Client\InvalidResponseDocument;
@@ -119,6 +120,36 @@ public function it_parses_a_response_with_a_body_and_unknown_size()
119120
$this->assertSame($response, $document->getResponse());
120121
}
121122

123+
/**
124+
* @test
125+
*/
126+
public function it_parses_a_response_with_a_seekable_stream_and_unknown_size()
127+
{
128+
$stream = $this->createMock(StreamInterface::class);
129+
$stream->method('getSize')->willReturn(-1);
130+
$stream->method('isSeekable')->willReturn(true);
131+
$stream->method('tell')->willReturn(0);
132+
$stream->expects($this->once())->method('read')->with(1)->willReturn('x');
133+
$stream->expects($this->once())->method('seek')->with(0);
134+
135+
$parsedDocument = new Document();
136+
137+
$documentParser = $this->createMock(DocumentParser::class);
138+
$documentParser
139+
->expects($this->once())
140+
->method('parse')
141+
->with($this->isType('string'))
142+
->willReturn($parsedDocument);
143+
144+
$parser = new ResponseParser($documentParser);
145+
$response = new Response(200, [], $stream);
146+
147+
$document = $parser->parse($response);
148+
149+
$this->assertSame($parsedDocument, $document);
150+
$this->assertSame($response, $document->getResponse());
151+
}
152+
122153
/**
123154
* @test
124155
*/

0 commit comments

Comments
 (0)