InflateStream.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\StreamInterface;
  5. /**
  6. * Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content.
  7. *
  8. * This stream decorator converts the provided stream to a PHP stream resource,
  9. * then appends the zlib.inflate filter. The stream is then converted back
  10. * to a Guzzle stream resource to be used as a Guzzle stream.
  11. *
  12. * @link http://tools.ietf.org/html/rfc1950
  13. * @link http://tools.ietf.org/html/rfc1952
  14. * @link http://php.net/manual/en/filters.compression.php
  15. */
  16. final class InflateStream implements StreamInterface
  17. {
  18. use StreamDecoratorTrait;
  19. /** @var StreamInterface */
  20. private $stream;
  21. public function __construct(StreamInterface $stream)
  22. {
  23. $resource = StreamWrapper::getResource($stream);
  24. // Specify window=15+32, so zlib will use header detection to both gzip (with header) and zlib data
  25. // See http://www.zlib.net/manual.html#Advanced definition of inflateInit2
  26. // "Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection"
  27. // Default window size is 15.
  28. stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15 + 32]);
  29. $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource));
  30. }
  31. }