Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add buffered stream to decoder plugin #99

Closed
wants to merge 1 commit into from
Closed
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
28 changes: 24 additions & 4 deletions src/Plugin/DecoderPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Http\Client\Common\Plugin;
use Http\Message\Encoding;
use Http\Message\Stream\BufferedStream;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
Expand All @@ -26,6 +27,12 @@ final class DecoderPlugin implements Plugin
* If set to false only the Transfer-Encoding header will be used
*/
private $useContentEncoding;

/**
* @var bool Whether this plugin should buffer the output of the decoded stream, this ensure that the stream is
* seekable and can be rewind / seek for multiple usages.
*/
private $buffered;

/**
* @param array $config {
Expand All @@ -38,11 +45,14 @@ public function __construct(array $config = [])
$resolver = new OptionsResolver();
$resolver->setDefaults([
'use_content_encoding' => true,
'buffered' => false,
]);
$resolver->setAllowedTypes('use_content_encoding', 'bool');
$resolver->setAllowedTypes('buffered', 'bool');
$options = $resolver->resolve($config);

$this->useContentEncoding = $options['use_content_encoding'];
$this->buffered = $options['buffered'];
}

/**
Expand Down Expand Up @@ -123,18 +133,28 @@ private function decodeOnEncodingHeader($headerName, ResponseInterface $response
*/
private function decorateStream($encoding, StreamInterface $stream)
{
$decorated = null;

if ('chunked' === strtolower($encoding)) {
return new Encoding\DechunkStream($stream);
$decorated = new Encoding\DechunkStream($stream);
}

if ('deflate' === strtolower($encoding)) {
return new Encoding\DecompressStream($stream);
$decorated = new Encoding\DecompressStream($stream);
}

if ('gzip' === strtolower($encoding)) {
return new Encoding\GzipDecodeStream($stream);
$decorated = new Encoding\GzipDecodeStream($stream);
}

if ($decorated === null) {
return null;
}

if ($this->buffered) {
$decorated = new BufferedStream($decorated);
Copy link
Member Author

Choose a reason for hiding this comment

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

In fact this is a bad place as we only need this buffer once at the end, if we have a stream that is both gzip and chunked encoded we will have 2 buffered streams :/

}

return false;
return $decorated;
}
}