DroppingStream.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace GuzzleHttp\Psr7;
  3. use Psr\Http\Message\StreamInterface;
  4. /**
  5. * Stream decorator that begins dropping data once the size of the underlying
  6. * stream becomes too full.
  7. */
  8. class DroppingStream implements StreamInterface
  9. {
  10. use StreamDecoratorTrait;
  11. private $maxLength;
  12. /**
  13. * @param StreamInterface $stream Underlying stream to decorate.
  14. * @param int $maxLength Maximum size before dropping data.
  15. */
  16. public function __construct(StreamInterface $stream, $maxLength)
  17. {
  18. $this->stream = $stream;
  19. $this->maxLength = $maxLength;
  20. }
  21. public function write($string)
  22. {
  23. $diff = $this->maxLength - $this->stream->getSize();
  24. // Begin returning 0 when the underlying stream is too large.
  25. if ($diff <= 0) {
  26. return 0;
  27. }
  28. // Write the stream or a subset of the stream if needed.
  29. if (strlen($string) < $diff) {
  30. return $this->stream->write($string);
  31. }
  32. return $this->stream->write(substr($string, 0, $diff));
  33. }
  34. }