DroppingStream.php 1.0 KB

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