Navigation Menu

Skip to content

Commit

Permalink
bug #33058 [HttpClient] fix data loss when streaming as a PHP resourc…
Browse files Browse the repository at this point in the history
…e (nicolas-grekas)

This PR was merged into the 4.4 branch.

Discussion
----------

[HttpClient] fix data loss when streaming as a PHP resource

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

I've just experienced failures like:
> StreamWrapper::stream_read - read 822 bytes more data than requested (9014 read, 8192 max) - excess data will be lost

This fixes it.

Commits
-------

99884e6 [HttpClient] fix data loss when streaming as a PHP resource
  • Loading branch information
nicolas-grekas committed Aug 8, 2019
2 parents bf73bd4 + 99884e6 commit f91fa10
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/Symfony/Component/HttpClient/Response/StreamWrapper.php
Expand Up @@ -22,7 +22,7 @@
*/
class StreamWrapper
{
/** @var resource */
/** @var resource|string|null */
public $context;

/** @var HttpClientInterface */
Expand Down Expand Up @@ -103,7 +103,7 @@ public function stream_open(string $path, string $mode, int $options): bool

public function stream_read(int $count)
{
if (null !== $this->content) {
if (\is_resource($this->content)) {
// Empty the internal activity list
foreach ($this->client->stream([$this->response], 0) as $chunk) {
try {
Expand All @@ -127,13 +127,32 @@ public function stream_read(int $count)
}
}

if (\is_string($this->content)) {
if (\strlen($this->content) <= $count) {
$data = $this->content;
$this->content = null;
} else {
$data = substr($this->content, 0, $count);
$this->content = substr($this->content, $count);
}
$this->offset += \strlen($data);

return $data;
}

foreach ($this->client->stream([$this->response]) as $chunk) {
try {
$this->eof = true;
$this->eof = !$chunk->isTimeout();
$this->eof = $chunk->isLast();

if ('' !== $data = $chunk->getContent()) {
if (\strlen($data) > $count) {
if (null === $this->content) {
$this->content = substr($data, $count);
}
$data = substr($data, 0, $count);
}
$this->offset += \strlen($data);

return $data;
Expand All @@ -155,12 +174,12 @@ public function stream_tell(): int

public function stream_eof(): bool
{
return $this->eof;
return $this->eof && !\is_string($this->content);
}

public function stream_seek(int $offset, int $whence = SEEK_SET): bool
{
if (null === $this->content || 0 !== fseek($this->content, 0, SEEK_END)) {
if (!\is_resource($this->content) || 0 !== fseek($this->content, 0, SEEK_END)) {
return false;
}

Expand Down

0 comments on commit f91fa10

Please sign in to comment.