Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/Parsers/ResponseParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,24 @@ public function parse(ResponseInterface $response): DocumentInterface

private function responseHasBody(ResponseInterface $response): bool
{
return (bool) $response->getBody()->getSize();
$body = $response->getBody();
$size = $body->getSize();

if ($size === 0) {
return false;
}
if (is_int($size) && $size > 0) {
return true;
}

$contents = (string) $body;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we read just a few bytes instead of the entire stream?

$hasBody = trim($contents) !== '';

if ($body->isSeekable()) {
$body->rewind();
}

return $hasBody;
}

private function responseHasSuccessfulStatusCode(ResponseInterface $response): bool
Expand Down
60 changes: 60 additions & 0 deletions tests/Parsers/ResponseParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Swis\JsonApi\Client\Tests\Parsers;

use GuzzleHttp\Psr7\PumpStream;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Swis\JsonApi\Client\CollectionDocument;
Expand Down Expand Up @@ -59,6 +60,65 @@ public function it_parses_a_response_with_an_empty_body()
$this->assertSame($response, $document->getResponse());
}

/**
* @test
*/
public function it_parses_a_response_with_an_empty_body_and_unknown_size()
{
$documentParser = $this->createMock(DocumentParser::class);
$documentParser->expects($this->never())
->method('parse');

$parser = new ResponseParser($documentParser);

$stream = new PumpStream(function () {
return false;
});

$response = new Response(204, [], $stream);

$document = $parser->parse($response);

$this->assertInstanceOf(Document::class, $document);
$this->assertSame($response, $document->getResponse());
}

/**
* @test
*/
public function it_parses_a_response_with_a_body_and_unknown_size()
{
$json = json_encode(['meta' => ['ok' => true]]);

$stream = new PumpStream(function () use ($json) {
static $done = false;
if ($done) {
return false;
}
$done = true;

return $json;
});

$parsedDocument = new Document;

$documentParser = $this->createMock(DocumentParser::class);
$documentParser
->expects($this->once())
->method('parse')
->with($this->isType('string'))
->willReturn($parsedDocument);

$parser = new ResponseParser($documentParser);

$response = new Response(200, [], $stream);

$document = $parser->parse($response);

$this->assertSame($parsedDocument, $document);
$this->assertSame($response, $document->getResponse());
}

/**
* @test
*/
Expand Down