DroppingStream.php 1.1 KB

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